Visual Studio 2005, 2008; ASP.NET 2.0, 3.0, 3.5; ADO.NET; C#; Visual Basic.NET; XML; Web Services; Windows Services; AJAX; Silverlight; LINQ; Visual Studio Team System; REST;
Thursday, January 08, 2009
Using partial classes in C# and .Net 2.0
Here is the sample code:
file: ModuleMain.cs
code:
public partial class Module
{
//constructor
public Module() {}
//some methods go here
public bool MainMethod()
{
return true;
}
}
file: ModuleExtended.css
code:
public partial class Module
{
//extended methods go here
public bool ExtendedMethod()
{
return true;
}
}
Now, when you'll access the class Module from your code, you'll see that the intellisense will show all the methods from both of these files.
Sometimes, this feature comes very handy. For example, I wrote a utility to generate code for asp.net application. But the problem was that the classes generated by the utility would overwrite the additional methods added manually. So, I split the functionality using partial classes and separated the generated and manual code into two different files. I hope this feature will help you too.
Friday, February 15, 2008
Find if network is available and connected using C#
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#
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#
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);
Thursday, February 07, 2008
Release memory in Windows Form application using 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#
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#
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#
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: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#
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
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#
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.
Thursday, January 24, 2008
Send email in asp.net web application 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);
Tuesday, January 22, 2008
Programmatically input data on a form and click submit button 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.
Saturday, January 19, 2008
Upload files using FileUpload control in asp.net using C#
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#
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
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
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
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
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
}
Thursday, September 14, 2006
C# (C Sharp) Sample Chapters
Visual C# 2005: A Developer's Notebook - Chapter 1: C# 2.0 (PDF Format)
C# Cookbook - Chapter 8: Regular Expressions (PDF Format)
Learning C# 2005 - Chapter 11: Inheritance and Polymorphism (PDF Format)