Thursday, January 31, 2008

Write XML file using DataTable in C#

We can read data from and write data to an xml file using a DataTable object in C# or Visual Basic. What we need to do is to define a DataTable structure and then use that structure to read and write xml file.

In this article I'll show you how to write data to an xml file, but the read process will be shown in the next post. So, let's get the ball rolling!

Okay, the only namespace we need to import is System.Data. This namespace contains DataTable class.

using System.Data;

Declare a DataTable object:

DataTable dt;

Define DataTable structure:

dt = new DataTable("MyTempTable");
dt.Columns.Add("FirstName", System.Type.GetType("System.String"));
dt.Columns.Add("LastName", Type.GetType("System.String"));
dt.Columns.Add("Address", Type.GetType("System.String"));

Declare a DataRow:

DataRow dr;

Create a new DataRow object:

dr = new DataRow();

Create a record to be inserted in the xml file:

dr["FirstName"] = "Joe";
dr["LastName"] = "Somebody";
dr["Address"] = "Somewhere in the world!";

Now add this row to the DataTable:

dt.Rows.Add(dr);

You can add multiple rows in the datatable just like the procedure above. The next step is to simply write the contents or records in an xml file.
And you can write this by simply using the following line of code:

dt.WriteXml("datafilename.xml");

You can write many complex procedures by using this simple tip.
I hope this helps. I'll also write the next post about reading data back into DataTable from XML file. So, stay tuned! :)

Wednesday, January 30, 2008

soap formatter to serialize objects in C#

Guys, we have already seen that how can we serialize an object using C# in visual studio 2005. Now, we'll look into the process of serializing an object using soap formatter. It is also known as xml serialization. In this article we'll get into the details of serializing an object using soap formatter.

First of all, import following two namespaces in your project.

using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;

We'll use the same example of the Product class, which we used in object serializatin using binary formatter.

[Serializable]
class Product{
public int ProductID;
public double Price;
public string Name;

public Product(int _productID, double _price, string _name)
{
ProductID = _productID;
Price = _price;
Name = _name;
}
}

For basic understanding of object serialization you can view following post

Object serialization using binary formatters in C#

Following code serializes an object using soap formatter:

Product objProduct = new Product(2,500,'some product');
FileStream fs = new FileStream("c:\\productobjectsoapformatted.Data", FileMode.Create);
SoapFormatter sf = new SoapFormatter();
sf.Serialize(fs, objProduct);
fs.Close();

To deserialize you'll have to use the following code:

Product objProduct;
FileStream fs = new FileStream("c:\\productobjectsoapformatted.Data", FileMode.Open);
SoapFormatter sf = new SoapFormatter();
sf.Serialize(fs, objProduct);
fs.Close();

If you open this data file in some text editor you'll see following output:


<?xml:namespace prefix = soap-env /><soap-env:envelope encodingstyle="http://schemas.xmlsoap.org/soap/encoding/" clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" env="http://schemas.xmlsoap.org/soap/envelope/" enc="http://schemas.xmlsoap.org/soap/encoding/" xsd="http://www.w3.org/2001/XMLSchema" xsi="http://www.w3.org/2001/XMLSchema-instance"><soap-env:envelope xsi="http://www.w3.org/2001/XMLSchema-instance" xsd="http://www.w3.org/2001/XMLSchema" enc="http://schemas.xmlsoap.org/soap/encoding/" env="http://schemas.xmlsoap.org/soap/envelope/" clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" encodingstyle="http://schemas.xmlsoap.org/soap/encoding/">
<soap-env:body<
<a1:shoppingcartitem id="ref-1" a1="http://schemas.microsoft.com/clr/nsassem/Serialization/Serialization%2C%20Version%3D1.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull">
<productid>1</productid>
<price>5</price>
<items>3</items>
<total>15</total>
</a1:ShoppingCartItem>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</soap-env:body>
</soap-env:envelope>

Monday, January 28, 2008

Build transparent windows form using C#

Developing a transparent windows form in Visual Studio 2005 using C# is not that big deal! By just setting a few properties, you can design a windows form you can look through. This article elaborates the process of converting a windows form into a transparent form using C#.

Create Visual Studio 2005 project using C# as a language of choice. In the picture of the transparent form I'm about to show you, I just made it borderless by settings its FormBorderStyle property to None. It is just to make it look interesting, otherwise it has nothing to do with the actual process of making it transparent.

To make the windows form look transparent just set its BackColor property to whatever color you like (or the color you don't like...because this color will not be visible due to transparency :) ). I set it to MediumSlateBlue. The second most important property which you need to set to achieve the objective of form transparency is Transparencykey. The important point to note here is that the color should be same in TransparencyKey and Form's BackColor. So, I'll set the TransparencyKey value to MediumSlateBlue.


It looks like a broken form, but actually its not! It is a transparent windows form shown on my computer's desktop. The bars at the top and left (if you can see that as well :) ) are the labels with some other background color. And there are two text boxes and one close button on the form that are viewable and working, while you can see through the form.



Add windows form application in registry to run at startup

If you want to install a windows application on the client machine, specially if you have to deploy a smart client application and you also want to run that application on startup, then you can add the path of the executable of the application in the registry. In this article, I'll show how you can do this.

First of all, import following namespace in your C# Windows Form application project.

using Microsoft.Win32;

Now, you have to add following code on the application load.

RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

Above line of code opens a registry sub key which allows to run the application at startup. In the following line you have to check that if your required registry key value is not there then add it otherwise you can ignore, so you wouldn't add it every time your application loads.

if (rkApp.GetValue("MyAppRegKey") == null)
{
rkApp.SetValue("MyAppRegKey", Application.ExecutablePath.ToString());
}

After running the application for the first time you'll see MyAppRegKey at the following path in registry editor SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run. You'll have to look for this path in the current user category of the registry editor

Oh...by the way, you can open registry editor as under:

Start -> Run -> Type regedit and Press Enter key.

Saturday, January 26, 2008

Object serialization using binary formatters in C#

In this article I'll show you the method of serializing a class object on a disk drive in a data file using binary formatters in C#. When we serialize an object, we actually preserve the state of the object on the disk so we can pick its state right from there where we left.

A classic example can be of a video game. For example you're developing a video game and you want to stop and exit the game but you would also like to start playing the game from where you left it. You could achieve this functionality as a game developer to serialize all of your objects on the disk.

We have already seen how we can serialize and deserialize some text using binary formatter in Microsoft.Net in a previous article:
Serialization of data using binary formatters in C#

In this article we're using binary formatter again for serialization but this time we'll serialize an object. You'll need following two namespaces for this purpose.

using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

First of all we need to define a class which is serializable:

[Serializable]
class Product
{
public int ProductID;
public double Price;
public string Name;


public Product(int _productID, double _price, string _name)
{
ProductID = _productID;
Price = _price;
Name = _name;
}
}

This is a simple product class having attribute Serializable, which makes objects of this class capable of being serialized.

Following code serializes the object of class product on the disk.

Product objProduct = new Product(1,200,'someproduct');
FileStream fs = new FileStream("c:\\productobject.Data", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, objProduct);
fs.Close();

You'll see that when you execute this code it'll create a file with the specified name on the hard drive and will save the object's status in it.

Now, when you want to deserialize the object, that is, you want to load the state of the object in to an object of Product class you'll use following code.

Product objProduct;
FileStream fs = new FileStream("c:\\productobject.Data", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
objProduct = (Product)bf.Deserialize(fs);
fs.Close();

In some next article I'll show you how can we serialize an object using Soap formatter that is also known as XML serialization.

Friday, January 25, 2008

Serialization of data using binary formatters in C#

Sometimes our program needs to save objects and data on hard drive. It is actually a process to preserve state of an object on the hard drive. Microsoft.Net provides a mechanism called serialization and the reverse process by which we load the state of object again is called the deserialization.

There are two methods to perform serialization knows as binary and soap. In this article I’ll use binary serialization and I’ll try to keep the things simple in this article. So, I’ll just try to serialize text to hard drive and then deserialize it again. In some later article I’ll show you how to serialize application class objects to hard drive.

First of all include following namespaces:

using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

let say we want to serialize some text from the text box and here is the code:

FileStream fs = new FileStream("c:\\SerializedData.Data", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, this.textBox1.Text);
fs.Close();

Now, you have serialized text in a data file on the hard drive. In order to deserialize it use the following code and show deserialized data in a text box.

FileStream fs = new FileStream("c:\\SerializedData.Data", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
string data = (string)bf.Deserialize(fs);
fs.Close();
this.textBox1.Text = data;

Thursday, January 24, 2008

Send email in asp.net web application using C#

Sending email in a web application is a common requirement. You might need this feature to send comments, feedback, newsletter, or tell a friend email etc. I’ll show the easiest way to send an email in Microsoft.net 2.0 and asp.net using C#.

First of all include following namespace in your asp.net web form.

using System.Net.Mail;

This namespace provide you different classes to specify various parameters to send an email. I’ll let you understand them one by one.

MailAddress class helps you create an email object. Remember in .net 2.0 you need to create an object for each email address. Or you can also you email address collection to specify multiple email addresses separated by commas.

We’re about to create from and to objects:

MailAddress objFrom = new MailAddress(“from email”,”from name”);
MailAddress objTo = new MailAddress(“to email”);

Now create a mail message, using from and to mail address objects:

MailMessage msgMail = new MailMessage(objFrom, objTo);

Let say, you want to send an email to multiple people then you’ll have to create a mail address collection object using MailAddressCollection class, and then add MailAddress objects in that collection.

MailAddressCollection objCCCollection = new MailAddressCollection();
MailAddress objCC = new MailAddress(“cc email1”);
objCCCollection.Add(objCC);

objCC = new MailAddress(“cc email2”);
objCCCollection.Add(objCC);

Now, add this email collection address in your mail message object:

msgMail.CC.Add(objCCCollection);

Similar is the case with BCC:

MailAddressCollection objBCCCollection = new MailAddressCollection();
MailAddress objBCC = new MailAddress(“bcc email”);

msgMail.Bcc.Add(objBCCCollection);

An email can be sent using two formats i.e. HTML or Text. You can specify this format as under:
msgMail.IsBodyHtml = true;

Now, set email subject and email body as under:

msgMail.Subject = sSubject;
msgMail.Body = sBody;


An SMTP server is used to send an email, you an either use your own server settings or your web host’s smtp mail settings. You need to check your hosting details or ask your hosting service provider about your SMTP settings.

SmtpClient objSMTP = new SmtpClient();

Follwing statement will assign credentials to this smtp object. The credentials should be a valid email account on your mail server.

objSMTP.Credentials = new System.Net.NetworkCredential("youusername", "yourpassword");

Sepecify your smtp server’s host and port number, by default it is 25:

objSMTP.Host = "mail.youdomain.com”
objSMTP.Port = 25;

Following statement will send your composed email to the recipients.

objSMTP.Send(msgMail);

Wednesday, January 23, 2008

Custom paging in SQL Server stored procedure

Microsoft.net provides controls which have paging capability by default – that is they have built in feature that can let you apply data paging by just setting a few properties or with just a few lines of code. The problem with this approach is that all the data is cashed in the memory i.e. using dataset etc, which effects application performance. Custom data paging in SQL Server stored procedure is a solution to this problem. I’ll explain how to perform this in such a way that you can use it either in SQL Server 2000 or SQL Server 2005 or even later versions.

You need to pass three parameters to the stored procedure which are page number, page size, and sort order. Following stored procedure code will return a page at a particular page number with your specified page size, sorted in your specified order i.e. Asc or Desc.

First of all, pass following three parameter to the stored procedure:

@PageNumber Int,
@PageSize Int,
@SortOrder Varchar(10) = 'DESC'

We have to apply this custom data paging on Article table. First create a temporary table in stored procedure.

Declare @TempTable Table
(
TempID int Identity,
ArticleID Int
)


Following code snippet will help you sort the data in your required order and keep it in temp table.

if @SortOrder='DESC'
Begin
Insert Into @TempTable (ArticleID)
Select ArticleID
From Article
Where StatusID=1
Order By
ArticleID Desc
End
Else
Begin
Insert Into @TempTable (ArticleID)
Select ArticleID
From Article
Where StatusID=1
Order By ArticleID Asc
End

The reason to keep the data in temporary table first is just to attach a unique id in a sequence to help get a proper page from the table. As, in your actually table some records might have been removed, so if you would apply paging directly on Article table, it might not return proper set or records for a particular page.

Following two local variables will help you get the proper page.

Declare @StartIndex Int
Declare @EndIndex Int

You can perform custom paging using either 1 based or 0 based index. The formulas for both approaches are as under. You can use any one of your choice.


--If page number is 1 based
Set @StartIndex = ((@PageNumber-1)* @PageSize) +1
Set @EndIndex = @PageNumber * @PageSize

--if page number is 0 bases then
Set @StartIndex = (@PageNumber * @PageSize) + 1
Set @EndIndex = @PageSize * (@PageNumber + 1)

Now, just perform a join of Article and TempTable and get all the records between StartIndex, and EndIndex.

Select E.* From Article E
Inner Join @TempTable T
On E.ArticleID= T.ArticleID
Where T.TempID Between @StartIndex And @EndIndex

Tuesday, January 22, 2008

Programmatically input data on a form and click submit button using C#

Usually form data is input manually by the user and then a button is clicked to send this form to the server for processing. Sometimes this process needs to be automated. You need to input form data with the help of the code and then click on the submit button programmatically. I’ll show you the code sample to perform this task in visual studio 2005 using C#.

In this article I’ll explain how to login to a web page programmatically. Let say you have a form with user name and password input boxes on it and a login button. You enter user name and password in the form and then click login button, then the application lets you enter into the application password restricted area.

First of all create a Windows Form application in Visual Studio 2005 using C#. Drop a Web Browser control on the form and give it proper height and width, because we’ll access login page in this Web Browser control and it should be visible properly. We're going to show the webpage on the windows form. You can add WebBrowser control from the tool box of the visual studio 2005.

Now, provide the URL of the login form to the WebBrowser control. You need to use navigate method to get the webpage and show it on the windows form. Let say we have given a name wbControl to the dropped web browser control. The following line of code will show the web page on the form.

wbControl.Navigate(“www.yourdomain.com/loginpage”);

You need to find the ids - unique id - of the controls which you want to handle in the code. You can find the ids of the particular controls by viewing the source of the web page in the browser window. Just for your reference when a page is rendered the server side code appends some extra attributes to the control id to make it unique.

Let say we have a user name control with the id “ctl00$ContentPlaceHolder2$Login1$UserName”. We’ll set the user name programmatically as follows.

wbControl.Document.GetElementById("ctl00$ContentPlaceHolder2$Login1$UserName").SetAttribute("value", "yourusername");

The id of our password control is "ctl00$ContentPlaceHolder2$Login1$Password" and following line shows how to set the password in the input box.

webBrowser1.Document.GetElementById("ctl00$ContentPlaceHolder2$Login1$Password").SetAttribute("value", "yourpassword");

Finally, you need to find the id of the button control which is "ctl00$ContentPlaceHolder2$Login1$LoginButton". Now, we have to click the button to login to the page and following line does the work.

webBrowser1.Document.GetElementById("ctl00$ContentPlaceHolder2$Login1$LoginButton").InvokeMember("click");

You’ll see that you’re logged into the application. Write this code in a button’s click event on the windows form.

Monday, January 21, 2008

Fetch contents of a web page using C#

If you are looking for some code help which can help you fetch contents of a web page using C# in asp.net then you’re at the right place. Sometimes you do need to read a web page programmatically so you could process the contents of the page.

In order to perform this task you need to import three Microsoft.net namespaces:

using System.IO;
using System.Net;
using System.Text;

First of all lets review the concept of web page request and response mechanism. When ever you type a URL in a browser window to get a web page, you’re actually making a request to the server to get a particular page. To perform this task programmatically we’ll use WebRequest class of System.Net namespace. We’ll create a request to simulate a manual request.

WebRequest objReq = WebRequest.Create("www.yoururl.com/anypage");

When a request is sent to the server, the application server or say web server returns a response with the required page contents. In manual request the browser itself receives the response and shows it to the user, but in our case we’ll receive this response in a specific response object of .net’s System.Net namespace called WebResponse.

WebResponse objResp = objReq.GetResponse();

First we need to create a stream from this response object so can prepare our page contents to be read by our stream reader which will read the actuall contents.

Stream objStream = objResp.GetResponseStream();

Now, we need to get the contents from this stream object. We’ll get a stream of the contents or text in ASCII format in a stream object.

StreamReader objSR = new StreamReader(objStream,Encoding.ASCII);

Finally, you simply need to get the text from this stream reader into a string variable.

String content = objSR.ReadToEnd();

Now, you can either save the contents or can display it on some other page. You can also process the contents of the page output. Remember the output text will contain the whole HTML format page – I mean with the head and body tags etc. If you want to display this text on some other page just remove those extra tags and just copy the actuall contents required. You can also get a subscring at some particular location. It’s all up to you now how you play with these simple statements. :)

Sunday, January 20, 2008

Accessing aspx page in javascript code using src attribute

Sometimes .net web developers need to access an asp.net web page in the javascript. A scenario where this kind of feature can be very helpful is one when you want to make some kind of processing using aspx page at your website or web server and then you want to show the output of this processing on some other website which can be static HTML site or using some other server side processing language i.e. PHP or JSP etc.

To achieve this functionality add an aspx page in your .net web application. Remove all the code from the aspx source file except the page directive at the top.

Now there are two ways to through output from this page to other file. Either you can write the contents using document.write method in the aspx source file or using document.write in the Response.write inside code behind file.

First Response.Write and then document.write enclosed in Response.write.

To access this page from other website or page just add the script tag in the html code of the page and specify language as javascript and the page as src of the script tag.

Saturday, January 19, 2008

Upload files using FileUpload control in asp.net using C#

Microsoft.Net has provided a server side asp.net control to upload files on the web server. This control is FileUpload:


Add a FileUpload control on asp.net web page. I want to upload image files so I have given this server side file upload control an id ImageUpload. You also need to add a button control which will allow you to upload the image file when it'll be clicked.


btnOK is the id of the button control which will be used in the code behind page to process the file. When you click this OK button it'll trigger btnOK_Click event, which will perform rest of the task to save the file on the server.

Also add a text box control to the asp.net page. You'll enter a name of your own choice for the image and that uploaded image will be saved with this name.

If you place a label control on the page it'll serve a purpose to show error message in case there is some exception or validation message required.

In asp.net 2.0 file upload is very easy task. Following event contains the code to upload a save the file on the server:


protected void btnOK_Click(object sender, EventArgs e)
{

if (this.ImageUpload.HasFile == true)
{
string imageName = this.txtImageName.Text;
string imageURL = this.txtImageName.Text + ".jpg";
ImageUpload.SaveAs(HostingEnvironment.ApplicationPhysicalPath + "//uploadedimages//" + imageURL);
this.txtImageName.Text = "";
this.lblMessage.Text = "Image saved successfully.";
}
else
{
this.lblMessage.Text = "Please browse file to upload.";
}
}

this.ImageUpload.HasFile will return true if the FileUpload control contains some file to be uploaded otherwise you'll show a message to request the user to select some file.

string imageURL = this.txtImageName.Text + ".jpg";

I have added .jpg extension to my custom file name because the file I have to upload is a jpg type file and I just want to save it with my specified name having the same extension.
ImageUpload.SaveAs(HostingEnvironment.ApplicationPhysicalPath + "//uploadedimages//" + imageURL);


SaveAs method of ImageUpload control saves the file on the server. HostingEnvironment.ApplicationPhysicalPath give you the physical path of your application on the web server, and UploadedImages is a folder under your root application directory. Remember if you already have a file with the same name it'll be replaced with the new file. If image is uploaded successfully the label control will show a success message.

In some later article I'll show you how to show the list of all the images on the server.


Friday, January 18, 2008

Get file list from the server using ftp web request in C#

Sometimes developers need to get a list of all the files on a server, and this needs to be done using ftp. Microsoft .Net provides classes to handle ftp requests. I'll show you some other functions performed using these classes in my later posts. Today, I'll focus only on getting a list of files from ftp server. I'll use FTPWebRequest class to fetch the list of files, and a StreadReader class to read the stream returned by FTPWebRequest method. Code is in C# (C-Sharp).

First of all you need to include two namespaces:

using System.Collections.Generic;
using System.Net;

System.Net namespace provides FTPWebRequest class to make a web request to an ftp server.

Now, declare a generic list of strings to keep the list of the fetched files:

List strList = new List();

In order to understand how to use generic list you can view my following post:
Using a generic list of strings or other class objects

Declare an object of type FTPWebRequest, and create an instance using the ftp server IP.
Here ftpServerIP is the IP of FTP server from where you want to fetch the list of files.

FtpWebRequest fwr = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP));

FTPWebRequest method requires proper credentials to authenticate the request. In the statement below ftpUserID and ftpPassword variables serve this purpose.

fwr.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

WebRequestMethod in the following code line tells the FTP Web Request object the operation you want to perform. In our current scenario we want to get the list of all the files in the root directory at the ftp server, so we'll use ListDirectory method type.

fwr.Method = WebRequestMethods.Ftp.ListDirectory;

Now, we'll create an object of type StreamReader as given below:

StreamReader sr = new StreamReader(fwr.GetResponse().GetResponseStream());

The important thing to understand here is 'fwr.GetResponse().GetResponseStream()'. As you already know that fwr is an FTPWebRequest type object and GetResponse method of this object returns an object of type WebResponse, so call an other method named GetResponseStream to create a StreamReader object. It shouldn't be confusing; nevertheless I'll discuss streams and related stuff in some later posts.

Okay, fellas! Now, we're ready to reap the benefits of all the labor we have done until now. :-)

We'll read the stream one line at a time - which will be a string - and we'll add these strings in the strList collection.

string str = sr.ReadLine();
while (str != null)
{
strList.Add(str);
str = sr.ReadLine();
}

Remember that the stream we received from the ftp server contained a list of files that is one file in one line!

So, we're almost done with the task we were supposed to do, but don't forget to impress your development manager or technical lead by the following statements - be smart and don't leave the labor for the garbage collector!

sr.Close();
sr = null;
fwr = null;

Wednesday, January 16, 2008

Using a generic list of strings or other class objects

Microsoft has introduced a new concept of generics in C#.Net 2.0. It is a kind of design pattern, and a part of the .net type system which allows your code to define the type. A generic can be of intrinsic .net data type or some class object type.

Phew..!!! enough theory...let's get back to the real stuff! :-)

Okay, let say you have to define a list of some type say string, you can use generic List class for that purpose. But, remember first of all you'll have to include the following namespace:

using System.Collections.Generic;

Now declare the a list of strings as:

List strList = new List();

This list can contain strings which can be added, removed, or found using different methods, and provide more felxibility as compared to the array of strings.

strList.Add("some string");

Remove, Find, and other methods can also be used like this.

If you want to create a list of your own custom class objects, you can do that as well.

For example, you have a class named Customer, then below is the code to create a generic list of the objects of type customer:

List custList = New List();
Customer objCust = New Customer("Customer Name");

custList.Add(objCust);

You can also loop through the list of items as given below:

foreach(Customer objCustomer in custList)
{

//process objCustomer here

}