Q. Reading and Writing with Files.FileStream fs=File.Create("C:\myfile.txt");fs.close();--------------------StreamWriter stw = File.CreateText("C:\myfile.txt");stw.WriteLine("Welcome to bixam's blog");stw.Close();--------------------StreamReader str = File.OpenText("C:\myfile.txt")string contents = str.ReadToEnd();txtFileContents.Text = contents;str.Close();Q. Sending mail in asp.net.using System.Web.Mail;MailMessage MMsg=new MailMessage();MMsg.From = "bixam.rprjdr@gmail.com";MMsg.To = "bixam_rprjdr@yahoo.com";MMsg.Subject = "Hi";MMsg.Body = "Welcome to Rookie's blog";MailAttachment MAtt = new MailAttachment("C:\myfile.txt");MMsg.Attachments.Add(MAtt);SmtpMail.SmtpServer = "";SmtpMail.Send(MMsg);Q. Inserting images iteself into database.int intLength;byte[] arrContent;string fileName = fileupld.PostedFile.FileName;string imgType = fileupld.PostedFile.ContentType;string ext = System.IO.Path.GetExtension(fileName);//fileName.LastIndexOf(".");if (ext != ".gif" && ext != ".bmp" && ext != ".jpg"){lblStatus.ForeColor = System.Drawing.Color.Red;lblStatus.Text = "Only gif, bmp, or jpg format files supported.";}else{try{intLength = (int)fileImage.PostedFile.InputStream.Length;arrContent = new byte[intLength];fileImage.PostedFile.InputStream.Read(arrContent, 0, intLength);cmd = new SqlCommand("insert into IMAGES(IMAGE_DATA,IMAGE_TITLE,IMAGE_TYPE,IMAGE_LENGTH) values(@content,@title,@type,@length)", conn);cmd.Parameters.AddWithValue("@content", arrContent);cmd.Parameters.AddWithValue("@title", txtTitle.Text);cmd.Parameters.AddWithValue("@type", imgType);cmd.Parameters.AddWithValue("@length", intLength);conn.Open();cmd.ExecuteNonQuery();conn.Close();lblStatus.ForeColor = System.Drawing.Color.Green;lblStatus.Text = "Image uploaded successfully.";}catch (Exception ex){lblStatus.ForeColor = System.Drawing.Color.Red;lblStatus.Text = "Error:" + ex.Message;}Q. Retrieving images from database.da = new SqlDataAdapter("select * from IMAGES", conn);da.Fill(ds, "images");ds.Tables["images"].Columns.Add("IMAGE_FILE");foreach (DataRow tmprow in ds.Tables["images"].Rows){tmprow["IMAGE_FILE"] = "ImageGrabber.aspx?id=" + tmprow["IMAGE_ID"];}gvImages.DataSource = ds.Tables["images"];gvImages.DataBind();------------------------------byte[] arrContent;da = new SqlDataAdapter("select * from IMAGES where IMAGE_ID="+Request.QueryString["id"], conn);da.Fill(ds, "image");drow = ds.Tables["image"].Rows[0];arrContent = (byte[])drow["IMAGE_DATA"];string conType = drow["IMAGE_TYPE"].ToString();int imgLength = int.Parse(drow["IMAGE_LENGTH"].ToString());Response.ContentType = conType;Response.OutputStream.Write(arrContent, 0, imgLength);Response.End();Q. Working with StoredProcedures.--Scalar valued functionsCREATE FUNCTION NEWUSERID() RETURNS INTASRETURN(SELECT MAX(USERID) FROM USERS)------------------------SqlCommand newidcmd = new SqlCommand();da.SelectCommand = newidcmd;da.SelectCommand.Connection = conn;da.SelectCommand.CommandType = CommandType.StoredProcedure;da.SelectCommand.CommandText = "NEWUSERID";da.SelectCommand.Parameters.Add("@uid", SqlDbType.Int).Direction = ParameterDirection.ReturnValue; DataTable dt = new DataTable();da.Fill(dt);int uid=int.Parse(newidcmd.Parameters["@uid"].Value.ToString())+1;txt_ins_uid.Text = uid.ToString();--Insert Stored ProcedureCREATE PROCEDURE ADDUSER(@UID INT,@UNAME VARCHAR(20),@PWD VARCHAR(20))ASINSERT INTO USERS(USERID,USERNAME,PASSWORD) VALUES(@UID,@UNAME,@PWD)---------------------SqlCommand inscmd = new SqlCommand();da.InsertCommand = inscmd;da.InsertCommand.Connection = conn;da.InsertCommand.CommandText = "ADDUSER";da.InsertCommand.CommandType = CommandType.StoredProcedure;da.InsertCommand.Parameters.Add("@uid", SqlDbType.Int, 10, "UserID");da.InsertCommand.Parameters.Add("@uname", SqlDbType.VarChar, 20, "UserName");da.InsertCommand.Parameters.Add("@pwd", SqlDbType.VarChar, 20, "Password");DataRow drow = ds.Tables["users"].NewRow();drow["UserID"] = int.Parse(txt_ins_uid.Text);drow["UserName"] = txt_ins_uname.Text;drow["Password"] = txt_ins_pwd.Text;ds.Tables["users"].Rows.Add(drow);da.Update(ds,"users");Q. Gridview editing with bound fields.asp:GridView ID="GridView1"runat="server"AutoGenerateColumns="False"Style="z-index: 100;left: 371px; position: absolute; top: 80px"AllowSorting="True"OnRowCancelingEdit="GridView1_RowCancelingEdit"OnRowDeleting="GridView1_RowDeleting"OnRowEditing="GridView1_RowEditing"OnRowUpdating="GridView1_RowUpdating"OnSelectedIndexChanging="GridView1_SelectedIndexChanging"AllowPaging="True"OnPageIndexChanging="GridView1_PageIndexChanging"OnSorting="GridView1_Sorting"PageSize="5"DataKeyNames="UserID"EnableViewState="True" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">asp:templatefield headertext="UserID" sortexpression="order by UserID">' CommandName="Select">/asp:TemplateField>asp:boundfield datafield="UserName" headertext="UserName" sortexpression="order by UserName">asp:boundfield datafield="Password" headertext="Password" sortexpression="order by Password">asp:commandfield headertext="Update" updatetext="Upate" showeditbutton="True">asp:templatefield headertext="Delete">/asp:LinkButton>/asp:GridView>---------------------------------------------------public partial class GVWithBoundFields : System.Web.UI.Page{SqlConnection conn = new SqlConnection(@"Server=.\SQLEXPRESS;Database=ROOKIE;Trusted_Connection=True;");static SqlDataAdapter da=new SqlDataAdapter();DataSet ds = new DataSet();SqlCommandBuilder cmdb = new SqlCommandBuilder(da);protected void Page_Load(object sender, EventArgs e){if (!Page.IsPostBack){ShowData();}}protected void ShowData(){ds.Clear();da = new SqlDataAdapter("select * from USERS", conn);da.Fill(ds, "users");GridView1.DataSource = ds.Tables["users"];GridView1.DataBind();}protected void FillData(){ds.Clear();da = new SqlDataAdapter("select * from USERS", conn);da.Fill(ds, "users");}protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e){//GridView1.Rows[e.NewSelectedIndex].BackColor = System.Drawing.Color.AliceBlue; //will be fired with Bound Fields}protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e){GridView1.EditIndex = e.NewEditIndex;ShowData();}protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e){TextBox t1 = (TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0];TextBox t2 = (TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0];FillData();DataRow drow = ds.Tables["users"].Rows[e.RowIndex];drow[1] = t1.Text;drow[2] = t2.Text;cmdb.DataAdapter = da;da.Update(ds, "users");GridView1.EditIndex = -1;ShowData();}protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e){GridView1.EditIndex = -1;ShowData();}protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e){FillData();ds.Tables["users"].Rows[e.RowIndex].Delete();cmdb.DataAdapter = da;da.Update(ds, "users");GridView1.EditIndex = -1;ShowData();}protected void GridView1_Sorting(object sender, GridViewSortEventArgs e){ds.Clear();da = new SqlDataAdapter("select * from USERS " + e.SortExpression, conn);da.Fill(ds, "users");GridView1.DataSource = ds.Tables["users"];GridView1.DataBind();}protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e){GridView1.PageIndex = e.NewPageIndex;//GridView1.EditIndex = -1;ShowData();}protected void GridView1_SelectedIndexChanged(object sender, EventArgs e){//Response.Write("SelectedIndexChanged");GridView1.Rows[GridView1.SelectedIndex].BackColor = System.Drawing.Color.BurlyWood; //will be fired with template fields//GridView1.EditIndex = -1;//ShowData();}}Q. Retrieving connectionstring from web.config?;database=Northwind;user id=sa;password=secret;">'Get connection string from Web.Config:string strConnection = ConfigurationSettings.AppSettings["conStr"].toString();---------------------------connectionString="Data Source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=DataDirectoryaspnetdb.mdf;User Instance=true"providerName="System.Data.SqlClient" />
SSPI -> Security Support Provider Interface, allows an application to use various security models available on a computer or network without changing the interface to the security system.'Get connection string from Web.Config:string strConnString = ConfigurationManager.ConnectionStrings[ "conStr"].ConnectionString.ToString();Q. Exception handling in asp.net?Exceptions or errors are unusual occurrences that happen within the logic of an application.If an exception occurs within an application, the user is presented with a yellow page that looks ugly. So, how do you deal with these situations? You use exception handling techniques in ASP.NET.
There are three ways to handle exceptions/errors in ASP.NET:
try-catch block. This is also called Structured Exception Handling (SEH).
Error Events.
Custom Error Page.http://www.codeguru.com/csharp/.net/net_asp/miscellaneous/article.php/c12385/
Validation controls:
Regular expression validator:
Simple RegularExpressionValidator Sample
One more example on validation controls:
<%@ Page Language="VB" %>
Sign In Form Validation Sample
Sign In Form Validation Sample
Datalist control:
http://www.dotnetspider.com/resources/19355-Working-with-datalist-control.aspx
edit,delete,update,cancel in datalist control
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Drawing;
public partial class DataListControl : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadData();
DataList1.DeleteCommand += new DataListCommandEventHandler( this.DataList1_DeleteCommand);
}
private void LoadData()
{
SqlConnection cn = new SqlConnection("user id=sa;password=sa;database=master;data source=netsvr");
cn.Open();
SqlCommand cmd = new SqlCommand("select EmployeeCode,EmployeeName,Salary,Department from Employee", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "Employee");
//bind data to the repeater control
DataList1.DataSource = ds;
DataList1.DataBind();
}
//item command for selecting a row
protected void Employee_Select(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "Cancel")
{
DataList1.EditItemIndex = -1;
LoadData();
}
}
protected void DataList1_EditCommand(object source, DataListCommandEventArgs e)
{
DataList1.EditItemIndex = e.Item.ItemIndex;
LoadData();
}
protected void DataList1_DeleteCommand(object source, DataListCommandEventArgs e)
{
try
{
int id = e.Item.ItemIndex;
SqlConnection cn = new SqlConnection("user id=sa;password=sa;database=master;data source=netsvr");
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "delete from Employee where EmployeeCode=" +id;
cmd.ExecuteNonQuery();
DataList1.EditItemIndex = -1; //Reset the index
LoadData();
}
catch (Exception ex)
{
throw ex;
}
}
protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)
{
Label lbl;
TextBox tbox;
int empcode;
string empname;
int salary;
string dept;
// ---retrieves the key for the row---
lbl = ((Label)(e.Item.FindControl("EmpCodeLabel")));
empcode = Convert.ToInt32(lbl.Text);
//empcode = Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex]);
// ---find the textbox control containing the EmpName
tbox = ((TextBox)(e.Item.FindControl("EmpNameTextBox")));
empname = tbox.Text;
// ---find the textbox control containing the salary
tbox = ((TextBox)(e.Item.FindControl("SalaryTextBox")));
salary = Convert.ToInt32(tbox.Text);
//----find the textbox control containing the department
tbox = ((TextBox)(e.Item.FindControl("DepartmentTextBox")));
dept = tbox.Text;
// ---updates the database---
string sql = "UPDATE Employee SET EmployeeName='" + empname + "' , Salary=" +salary + ", Department='" + dept + "' WHERE EmployeeCode=" + empcode ;
SqlConnection conn = new SqlConnection(("user id=sa;password=sa;database=master;data source=netsvr"));
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
DataList1.EditItemIndex = -1;
LoadData();
}
}
Good one:
http://www.codeproject.com/KB/books/master_aspnet.aspx
String and String builder : good artical:
http://www.codeproject.com/KB/books/0735616485.aspx
No comments:
Post a Comment