Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts
Wednesday, March 24, 2010
What is Reflection
Reflection means to find out metadata information of any modules or assembly. You can also create class using reflection.
Developer can load any assembly runtime and find out metadata information of that assembly. He can also create object of any type which are exist in that assembly and also able to assign value and call any method from that object at runtime.
Let’s take an example, you have to use any third party control (DLL). You can get your requested type dynamically.
Here I explained you how to load any assembly which is added as a reference in your project.
You are getting one Test Library1 (TestLibrary1.dll) and you have to find out “Class1” type. You have to add reference of that class library and call this code snippet to load library:
Assembly assembly = Assembly.Load("TestLibrary1");
Type t = assembly.GetType("TestLibrary1.Class1");
Here we have pass “TestLibrary1” as a parameter of Assembly.Load method is an assembly name. This is same as a namespace name.
Assembly is in-built .net class which has static method “Load” which load assembly so developer can easily find out types.
After loading assembly, you can find out your type using GetType method of assembly object.
Load method of Assembly class has different overloads. You can also pass physical path or Assembly name or byte array of assembly name.
You can download code from here.
Wednesday, February 10, 2010
Implementing Singleton Design Pattern in C# application
Introduction
Sometime we need to create only one object of any class in our application then we need to implement Singleton design pattern to achieve this.
For an example, you have logging functionality which takes value as a parameter and store information in external device (like database or xml file or flat file). This logging class doesn’t have any state value. You can design that class using singleton design pattern.
Problem and solution
First problem is that you need to be sure that your class must be initializing once and the reference is available at anytime so your application can use that reference to use singleton class method.
You can solve the above problem using private constructor. When you define private constructor then nobody can initialize object of that class. (Make sure that singleton class doesn’t have any public constructor).
public class SingletonTest
{
private SingletonTest()
{
}
}
Second problem, if you create private constructor then how can we initialize the class first time when we need it?
We can create and initialize object of singleton class (which have only private constructor) within that class. To achieve this we need to implement one public static method which will return object of Singleton class.
public class SingletonTest
{
private static SingletonTest singletonTest = null;
private SingletonTest()
{
}
public static SingletonTest RetrieveObject()
{
if (singletonTest == null)
singletonTest = new SingletonTest();
return singletonTest;
}
}
Now, we can create and initialize object of our singleton class using below code:
SingletonTest singletonTest = SingletonTest.RetrieveObject();
When user will call this method first time, this method will create new object of SingletonTest class and assign it to private static variable and return that variable.
When user will call the same method again, this method will check that the private static variable is initialized. If private static variable is initialized then it will return it. In our case it initialized already when user called this first time.
So it confirms that our SingletonTest class has only one reference during whole application life cycle.
Labels:
.Net 2008,
C#,
Design Pattern,
Microsoft .Net,
Private Constructor,
Singleton
Thursday, February 4, 2010
Send HTTP Web Request using C# Application
In some application, we need to send HTTP web request to web application server. While sending http request to server our .Net code block the execution till the response come back to us. But in some scenario we need not wait for response on the same time because we need that output later on.
For the above problem, we can send asynchronous HTTP web request to web application server. When we send web request asynchronous then our application resume the execution and when we need the output of that web request then we can get is using IAsyncResult object.
Here I explained come sample to send asynchronous HTTP web request to web application.
Before starting it, we need to understand the web request types. Actually, any browser send HTTP request using two methods:
- GET
- POST
In POST method, Browser sends form data with URL as an attachment. User can’t see the POST data in address bar so it is not possible to change the data from address bar.
First we go through asynchronous HTTP web request method using “GET”. Please check the code below:
///
/// Gets the response.
///
/// <param name="StrURL">The URL.
///
public string GetResponse(string StrURL)
{
string strReturn = "";
HttpWebRequest objRequest = null;
IAsyncResult ar = null;
HttpWebResponse objResponse = null;
StreamReader objs = null;
try
{
objRequest = (HttpWebRequest)WebRequest.Create(StrURL);
ar = objRequest.BeginGetResponse(new AsyncCallback(GetScrapingResponse), objRequest);
//// Wait for request to complete
ar.AsyncWaitHandle.WaitOne(1000 * 60, true);
if (objRequest.HaveResponse == false)
{
throw new Exception("No Response!!!");
}
objResponse = (HttpWebResponse)objRequest.EndGetResponse(ar);
objs = new StreamReader(objResponse.GetResponseStream());
strReturn = objs.ReadToEnd();
}
catch (Exception exp)
{
throw exp;
}
finally
{
if (objResponse != null)
objResponse.Close();
objRequest = null;
ar = null;
objResponse = null;
objs = null;
}
return strReturn;
}
///
/// Gets the scraping response.
///
/// <param name="result">The result.
protected void GetScrapingResponse(IAsyncResult result)
{
}
Let’s understand the above code:
We have created the method “GetResponse” which take URL as a parameter. You have to pass query string data with URL in this method.
For example: you can call this method like
GetResponse(“http://www.codeproject.com/?cat=4”);
In this method, I created object for HttpWebRequest, HttpWebResponse, StreamReader and IAsyncResult.
- HttpWebRequest: This object is used to send http web request to web application server. You can use BeginGetResponse and EndGetResponse method of HttpWebRequest object to get response asynchronously.
- HttpWebResponse: This object is used to get response from web application server.
- StreamReader: This object is used to get response stream.
- IAsyncResult: This object is used to send and retrieve asynchronous http web request.
We created HttpWebRequest object using WebRequest.Create method. After creating object, I called BeginGetResponse method to send the http request to web application server. After calling this method, our application execution resume because we used asynchronous method for Http Web Request.
When you need web response then you can use the HttpWebRequest object and call EndGetResponse method. After getting response successfully, we converted it in stream and later on in string variable.
If web applications use “POST” method to send the request data then you have to change the method little bit.
///
/// Gets the response with post.
///
/// <param name="StrURL">The URL.
/// <param name="strPostData">The post data.
///
protected string GetResponseWithPost(string StrURL, string strPostData)
{
string strReturn = "";
HttpWebRequest objRequest = null;
ASCIIEncoding objEncoding = new ASCIIEncoding();
Stream reqStream = null;
HttpWebResponse objResponse = null;
StreamReader objReader = null;
try
{
objRequest = (HttpWebRequest)WebRequest.Create(StrURL);
objRequest.Method = "POST";
byte[] objBytes = objEncoding.GetBytes(strPostData);
objRequest.ContentLength = objBytes.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";
reqStream = objRequest.GetRequestStream();
reqStream.Write(objBytes, 0, objBytes.Length);
IAsyncResult ar = objRequest.BeginGetResponse(new AsyncCallback(GetScrapingResponse), objRequest);
//// Wait for request to complete
ar.AsyncWaitHandle.WaitOne(1000 * 60 * 3, true);
if (objRequest.HaveResponse == false)
{
throw new Exception("No Response!!!");
}
objResponse = (HttpWebResponse)objRequest.EndGetResponse(ar);
objReader = new StreamReader(objResponse.GetResponseStream());
strReturn = objReader.ReadToEnd();
}
catch (Exception exp)
{
throw exp;
}
finally
{
objRequest = null;
objEncoding = null;
reqStream = null;
if (objResponse != null)
objResponse.Close();
objResponse = null;
objReader = null;
}
return strReturn;
}
///
/// Gets the scraping response.
///
/// <param name="result">The result.
protected void GetScrapingResponse(IAsyncResult result)
{
}
I created one more method “GetResponseWithPost”. This method actually sends data using Post method to web server. This method takes two parameters: URL and PostData. URL is just an URL of any web application. URL is not contains any query string data. Another parameter PostData contains data to post on the web server.
We need following changes to work with POST method:
- We need one more parameter to pass Post Data
- Need to assign “POST” to Http Web Request method property
- Need to set ContentLength and ContentType
- Create Stream before sending actual web request to web server
I think you have question, how to know the POST data while submitting web request to web server using browser. For this you can use LiveHTTPHeader add-ons in Firefox. This add-ons display all the post data when you access the web application using Firefox.
Subscribe to:
Posts (Atom)
