Tuesday, January 27, 2009

imp point Query String

Often you need to pass variable content between your html pages or aspx webforms in context of Asp.Net. For example in first page you collect information about your client, her name and last name and use this information in your second page.

For passing variables content between pages ASP.NET gives us several choices. One choice is using QueryString property of Request Object. When surfing internet you should have seen weird internet address such as one below.

http://www.localhost.com/Webform2.aspx?name=Atilla&lastName=Ozgur

This html addresses use QueryString property to pass values between pages. In this address you send 3 information.

Webform2.aspx this is the page your browser will go.
name=Atilla you send a name variable which is set to Atilla
lastName=Ozgur you send a lastName variable which is set to Ozgur

As you have guessed ? starts your QueryString, and & is used between variables. Building such a query string in Asp.Net is very easy. Our first form will have 2 textboxes and one submit button.

Put this code to your submit button event handler.

Collapse Copy Codeprivate void btnSubmit_Click(object sender, System.EventArgs e)
{
Response.Redirect("Webform2.aspx?Name=" +
this.txtName.Text + "&LastName=" +
this.txtLastName.Text);
} Our first code part builds a query string for your application and send contents of your textboxes to second page. Now how to retrieve this values from second page. Put this code to second page page_load.

Collapse Copy Codeprivate void Page_Load(object sender, System.EventArgs e)
{
this.txtBox1.Text = Request.QueryString["Name"];
this.txtBox2.Text = Request.QueryString["LastName"];
} Request.QueryString is overloaded with a second way. You can also retrieve this values using their position in the querystring. There is a little trick here. If your QueryString is not properly built Asp.Net will give error.

Collapse Copy Codeprivate void Page_Load(object sender,

System.EventArgs e)
{
this.txtBox1.Text = Request.QueryString[0];
this.txtBox2.Text = Request.QueryString[1];
}
Some other ways to reach contents of QueryString.

Collapse Copy Codeforeach( string s in Request.QueryString)
{
Response.Write(Request.QueryString[s]);
}
Or

Collapse Copy Codefor (int i =0;i < Request.QueryString.Count;i++)
{
Response.Write(Request.QueryString[i]);
} Advantages of this approach

It is very easy.
Disadvantages of this approach

QueryString have a max length, If you have to send a lot information this approach does not work.
QueryString is visible in your address part of your browser so you should not use it with sensitive information.
QueryString can not be used to send & and space characters.
If you write this code and try them you will see that you have a problems with space and & characters, e.g. if you need to send a variable which contains & such as "Mark & Spencer". There must be a solution for this problem. If you look to Google’s query string you will see that it contains a lot of %20. This is the solution of our third disadvantage. Replace space with %20 and & with %26 for example.

Collapse Copy Codeprivate void btnSubmit_Click(object sender, System.EventArgs e)
{
string p1 = this.txtName.Text.Replace("&","%26");
p1 = this.txtName.Text.Replace(" ","%20");
string p2 = this.txtLastName.Text.Replace("&","%26");
p2 = this.txtName.Text.Replace(" ","%20");
"WebForm2.aspx?" +
"Name=" + p1 +
"&LastName=" + p2;
Response.Redirect(p2);
} Since this is a such a common problem Asp.Net should have some way to solve. There it is Server.UrlEncode. Server.UrlEncode method changes your query strings to so that they will not create problems.

Collapse Copy Code private void btnSubmit_Click(object sender, System.EventArgs e)
{
Response.Redirect("WebForm2.Aspx?" +
"Name=" + Server.UrlEncode(this.txtName.Text) +
"&LastName=" + Server.UrlEncode(this.txtLastName.Text));
}
Same solution is in Microsoft .Net Quick Start tutorials.

ASP.NET --- Working with Web Controls ---

--- Performing Page Navigation (Scenario 1) ---
--- Performing Page Navigation (Scenario 2) ---

Look at them also if you want to see more example for this technique. Also I advise you to look at Alex Beynenson's article about building QueryString(s).



License

Friday, January 23, 2009

public partial class Form1 : Form
{
string path = "";
public Form1()
{
InitializeComponent();
}

private void button2_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
pictureBox1.ImageLocation= openFileDialog1.FileName;
path = openFileDialog1.FileName;
}

private void button1_Click(object sender, EventArgs e)
{
loaddata();
}

private void loaddata()
{

FileStream st = new FileStream(path, FileMode.Open);
byte[] buffer = new byte[st.Length];
st.Read(buffer, 0, (int)st.Length);
st.Close();

SqlConnection cn = new SqlConnection("User ID=sa;Initial Catalog=test;Data Source=.");
SqlCommand cmd = new SqlCommand("insert into emp values('"+textBox1.Text+"',@photo)",cn);
cmd.Parameters.Add("@photo", buffer);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}

private void button3_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("User ID=sa;Initial Catalog=test;Data Source=.");
SqlCommand cmd = new SqlCommand("select * from emp where empno=" + textBox2.Text,cn);
cn.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
textBox1.Text = dr[1].ToString();
byte[] image = (byte[])dr[2];
// System.Web.HttpContext.Current.Response.ContentType = "image/jpeg";

System.Drawing.Image _image = System.Drawing.Image.FromStream(new System.IO.MemoryStream(image));

//System.Drawing.Image _newimage = _image.GetThumbnailImage(_width, _height, null, new System.IntPtr());

//_newimage.Save(System.Web.HttpContext.Current.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

pictureBox1.Image = _image;
cn.Close();
}
}


CREATE TABLE [dbo].[emp] (
[empno] [int] IDENTITY (1, 1) NOT NULL ,
[ename] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[eimage] [image] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Wednesday, January 21, 2009

read write text file in asp.net

************************read text file*************************

Dim fp As StreamReader

Try
fp = File.OpenText(Server.MapPath(".\Upload\") & "test.txt")
txtMyFile.Text = fp.ReadToEnd()
lblStatus.Text = "File Succesfully Read!"
fp.Close()


*********************create text file*****************************
Dim fp As StreamWriter

Try
fp = File.CreateText(Server.MapPath(".\Upload\") & "test.txt")
fp.WriteLine(txtMyFile.Text)
lblStatus.Text = "File Succesfully created!"
fp.Close()
Catch err As Exception
lblStatus.Text = "File Creation failed. Reason is as follows

************************write doc file*******************************

private void WriteToWordFile()
{
// Any folder
string path = @"C:\ServerFolder\MyWordFile.doc";

string text = TextBox2.Text;
// Put it in try-catch finally :)
FileStream fs = File.Create(path);
fs.Close();
StreamWriter sw = new StreamWriter(path);
sw.Write(text);
sw.Close();

}

****************************write text into file*****************************

Writing to a Text File
Listing 1: Writing Text Data to a File: TextFileWriter.cs
using System;
using System.IO;

namespace csharp_station.howto
{
class TextFileWriter
{
static void Main(string[] args)
{
// create a writer and open the file
TextWriter tw = new StreamWriter("date.txt");

// write a line of text to the file
tw.WriteLine(DateTime.Now);

// close the stream
tw.Close();
}
}
}



****************************read text from file*****************************


using System;
using System.IO;

namespace csharp_station.howto
{
class TextFileReader
{
static void Main(string[] args)
{
// create reader & open file
Textreader tr = new StreamReader("date.txt");

// read a line of text
Console.WriteLine(tr.ReadLine());

// close the stream
tr.Close();
}
}
}