Friday, December 26, 2008

Add memory stream data as attachment in the email using C#

Sometimes we have data in a stream object and we want to send that data as an attachment with an email. We can have data either in basic stream object, file stream object, or memory stream object. Let say, for this example we use memory stream object and below lines are used to add this memory stream data as attachment with an email and send it using SMTP Client.


objMemoryStream.Position = 0;
objMailMessage.Attachments.Add(new System.Net.Mail.Attachment(objMemoryStream, "testattachment.txt"));

Second line reads the memory stream and attach it with the mail message object as a text file.

Wednesday, November 05, 2008

Free ASP.NET 3.5 Training Video Downloads

Here is a list of asp.net 3.5 videos available freely from asp.net website. For your comfort I have listed the download links in a single post.

You can download and learn a lot from all of these video tutorials:

ASP.NET AJAX Support in Visual Studio 2008
The ListView Control
The DataPager Control
Visual Studio 2008 and Nested Masterpages
New Designer Support in Visual Studio 2008
JavaScript Intellisense Support in Visual Studio 2008
JavaScript Debugging in Visual Studio 2008
Multi Targeting Support in Visual Studio 2008
Quick Tour of the Visual Studio 2008 Integrated Development Environment
Creating and Modifying a CSS File
Adding AJAX Functionality to an Existing ASP.NET Page
Creating and Using an AJAX-enabled Web Service in a Web Site
How Do I: Create a Master Page in Visual Studio 2008
How Do I: Create Nested Master Page in Visual Studio 2008
How Do I: Cascading Style Sheets in Visual Studio 2008
How Do I: Working with Visual Studio 2008 .NET Framework
How Do I: Adding Elements to a CSS File and Create New CSS on the Fly
How Do I: Advance Cascading Style Sheet Features and Management
How Do I: Converting a .NET 2.0 Windows Forms Application to .NET 3.5
How Do I: Get Started with the Entity Framework
How Do I: Use the New Entity Data Source
ASP.NET AJAX: A demonstration of ASP.NET AJAX
How Do I: Serialize a Graph with the Entity Framework
Watch ASP.NET Development in Action
How Do I: Use MSBuild to Automate the ASP.NET Compiler and Merge Utilities

I hope you'll enjoy these videos.

Friday, February 15, 2008

Find if network is available and connected using C#

There are different ways to find out manually that whether we're connecte to some network or not. But how we do this via programming - especially in .Net? In this post I'll give you the idea to find out that if we're connected to the network or not. This code snippet can also give us the number of the networks available to our machine.

In order to find out connected networks in Microsoft.Net using either C# or Visual Basic.Net we can use System.Management namespace. There are two classes available in this namespace that can help us achieve this goal. These two calsses are ObjectQuery and ManagementObjectSearcher. The following code snippet first creates a query object that will be used to get all the networks available to our machine and then the ManagementObjectSearcher class' object will execute this query to return the results.

ObjectQuery objQuery = new ObjectQuery("select * from Win32_NetworkAdapter Where NetConnectionStatus=2");

Here NetConnectionStatus=2 means the network connections that are connected right now. Normally, these are the connections which are connected to the internet i.e. Cable, Wireless internet connection etc.

ManagementObjectSearcher searcher = new ManagementObjectSearcher(objQuery);

int connectednetworks = searcher.Get().Count;

if (connectednetworks <= 0)
return false;

Wednesday, February 13, 2008

How to ping a server programatically in .net using C#

Normally, in Windows operating system we can ping a machine using Ping command in the command window. What we need to do is just provide the IP of the target machine we want to ping. Ping command returns the response which tells us that the other machine is active on the network and available. This same kind of functionality need to be achieved via programming. In this article I'll show you the code snippet which can help you ping a system in C# or Visual Basic.Net.

Microsoft.Net framework 2.0 provides Ping class under System.Net.NetworkInformation namespace which can be used to ping an IP. Following is the snippet which let you do this:

Ping objPing = new Ping();
PingReply objPingReply = objPing.Send("IP of the Machine");

if (objPingReply.Status == IPStatus.Success)
{
return true;
}
else
{
return false;
}

Tuesday, February 12, 2008

Register a COM DLL from .Net application using C#

The problem with the COM components i.e. DLL is that they need to be registered in the windows to put them to work. Registry Server can be used to register those DLLs. While doing this task manually one need to use command window to register the DLL file using Registry Server executable. Whoever, sometimes we also need to register some DLL from our application code using either C# or Visual Basic.Net. In this post I'll show you the code to register a COM DLL using C# code. This procedure can also be used with Visual Basic.Net as well with a slight modifications in syntax.

Following code snippet uses Process class of System.Diagnostics namespace. Just create an object of process class and pass few arguments to get the DLL registered in windows.

System.Diagnostics.Process Proc = new System.Diagnostics.Process(); Proc.StartInfo.FileName = "regsvr32.exe";
Proc.StartInfo.Arguments = "filename.dll /s";
Proc.StartInfo.CreateNoWindow = true;
Proc.Start();
Proc.WaitForExit();

Monday, February 11, 2008

Open a webpage on button click in asp.net using C#

Sometimes we need to open a web page using a button click event. This post contains a sample code that can be used in a button click event to show a page using Javascript Window.open method. This code snippet is just a small piece just to give you an idea for the startup stuff. I hope you can improve, and modify it according to your need to achieve your required goal.

Here is the sample code. You can put this code in the click event of a button etc.


string strpage = "Url of the page to be opened";
string url = "";
this.RegisterStartupScript("", url);

Friday, February 08, 2008

Get date and time parts in SQL Server 2005 using Transact SQL

Datetime data type in SQL Server 2000 or SQL Server 2005 provides a way to store data in date and time format. This type of variable or field contains both date and time togather, but sometimes we need either date or time portion only separately. For that purpose we can use Transact SQL. In this article I'll explain the way we can process datetime type data and get date and time parts as string.

We'll use some variations of Convert function to get both date and time. Let say we have an AddressBook table in our database which contains an UpdateDateTime field.

First of all we'll get only the time part of this datetime field:

SELECT CONVERT(CHAR(8),UpdateDateTime,8) FROM AddressBook

Above statement will give you the time part in string or text format like 15:13:03, Sowe can use it accordingly.

Following four Transact SQL statements return date part in different formats using Convert funciton:


--Date Part 10-26-2007
SELECT CONVERT(CHAR(10),UpdateDateTime,110) FROM AddressBook
--Date Part 2007/10/26
SELECT CONVERT(CHAR(10),UpdateDateTime,111) FROM AddressBook
--Date Part 20071026
SELECT CONVERT(CHAR(10),UpdateDateTime,112) FROM AddressBook
--Date Part 26 Oct 2007
SELECT CONVERT(CHAR(11),UpdateDateTime,113) FROM AddressBook

The date format returned is given as comments above the statements.

Thursday, February 07, 2008

Release memory in Windows Form application using C#

Windows Form applications (Microsoft.Net Desktop applications) sometimes start consuming a lot of memory, which has different drawbacks, but I'll not get into the details of them here. What we'll look into is how to avoid the excess use of the memory resource in a windows application in C#.

In fact, you need to flush memory to release all the unused memory to make more space available for your current and other applications. First of all include following two namespaces:

using Microsoft.Win32;
using System.Runtime.InteropServices;

and then use the following code snippet to flush excesssive use of memory. You can view the currently consumed memory by viewing the application process name in the currently running processes list. For that purpose just go to the Task Manager, and then go to Processes tab and find out your application's process.

Following code imports a win32 dll and flushes the memory. But, before that it also uses Microsoft.Net's garbage collector to force an immidiate garbage collection:

public class MemoryManagement
{
[DllImportAttribute("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize", ExactSpelling = true, CharSet =
CharSet.Ansi, SetLastError = true)]

private static extern int SetProcessWorkingSetSize(IntPtr process, int minimumWorkingSetSize, int
maximumWorkingSetSize);

public static void FlushMemory()
{
GC.Collect();
GC.WaitForPendingFinalizers();
if (Environment.OSVersion.Platform == PlatformID.Win32NT) { SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
}
}

copy and use this class in your code and have fun reducing the memory size!

Wednesday, February 06, 2008

Read data from XML File using DataTable in C#

Reading data from an xml file with the help of DataTable in C# is very easy. You just need to use one method of DataTable called ReadXML. Here is this article I'll show you how to complete this task of reading xml data into a DataTable.

Before reading xml data into a DataTable you need to make sure that the table structure is consistent with the structure of the xml. The good idea would be to first write the xml file using this same table structure in this DataTable. You can write xml using DataTable and the detail is given in the follwing post:

Write XML file using DataTable in C#

Import follwing namespace:
using System.Data;

We need a DataTable object:

DataTable dt;

This DataTable requires a structure compatible with the xml file structure. We can make sure this compatibility with the help of xml schema as well, but in this article I'll not explain how can we use xml schema to make sure that the structure is same. However, in some next post I'll definitly explain that as well.

Here is the table 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"));

Now, read the xml file into this data table.

dt.ReadXml("filename");

Now, you can process data in the dt as a normal DataTable.

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

}