Archive

Archive for the ‘C Sharp’ Category

Dynamically write text on an image

March 8th, 2010 amitmathur31 No comments

This posts basically concentrates on dynamically writing some text content on image. This technique can be used in many of our development tasks like for developing captcha, printing of email addresses on websites which actually avoids spammers and many other purposes as per the development requirements.

Below given is the sample code to print sometext “Hey! this is me.” on an image.

Namespaces to be used:

using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Text;

Text and Image load content:

Bitmap bitMapImage = new System.Drawing.Bitmap(Server.MapPath(”Amit.jpg”));
Graphics graphicImage = Graphics.FromImage(bitMapImage);
graphicImage.SmoothingMode = SmoothingMode.AntiAlias;
graphicImage.DrawString(”Hey! This is me.”, new Font(”Arial”, 12, FontStyle.Bold),SystemBrushes.WindowText, new Point(100, 250));
graphicImage.DrawArc(new Pen(Color.Red, 3), 90, 235, 150, 50, 0, 360);

Response.ContentType = “image/jpeg”;
//Save the new image to the response output stream.

bitMapImage.Save(Response.OutputStream, ImageFormat.Jpeg);

graphicImage.Dispose();
bitMapImage.Dispose();

VN:F [1.6.3_896]
Rating: 0.0/5 (0 votes cast)
Categories: ASP.Net, C Sharp Tags:

C# Using Statement – Try / Finally – IDisposable – Dispose() – SqlConnection – SqlCommand

November 17th, 2009 Neeraj Mathur 1 comment

While viewing some of the C# code written by a new programmer, I noticed that they lack of calling Dispose() method on SqlConnection and SqlCommand objects. And the dabase code was not placed in try/finally blocks. This coding style is typical newbie style of development that everyone, including myself, attempted in the very beginning.

SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(commandString, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();

The problem in the above code is that SqlConnection and SqlCommand implement IDisposable, which means they could have unmanaged resources to cleanup and it is our job, to make sure Dispose() gets called on these classes after we are finished with them. And, because an exception could be raised if the database is unavailable, we need to make sure Dispose() gets called even in the case of an exception.

Its better to use the “using” keyword in C#. Internally, this generates a try / finally around the object being allocated and calls Dispose() for you. It saves you the hassle of manually creating the try / finally block and calling Dispose().

The new code would looking something like this:

using (SqlConnection con = new SqlConnection(connectionString))
{
    using (SqlCommand cmd = new SqlCommand(commandString, con))
   {
      con.Open();
      cmd.ExecuteNonQuery();
   }
}

This is essentially equivalent to the following:

SqlConnection con = null;
SqlCommand cmd = null;
try
{
     con = new SqlConnection(connectionString);
     cmd = new SqlCommand(commandString, cn);
     con.Open();
     cmd.ExecuteNonQuery();
}
finally
{
      if (null != cm);
         cmd.Dispose();
      if (null != cn)
         con.Dispose();
}

You may notice the lack of calling Close() on the SqlConnection class, con. Internally, Dispose() checks the status of the connection and closes it for you. Therefore, technically you don’t need to call Close() on the connection (con) as Dispose() will do it for you. In addition, Dispose() destroys the connection string of the SqlConnection class. Therefore, if you want to re-open the connection after calling Dispose() on con, you will have to re-establish the connection string. Not doing so will throw an exception.

VN:F [1.6.3_896]
Rating: 4.7/5 (3 votes cast)
Categories: ASP.Net, C Sharp Tags: , , ,

Optional Parameter C# 4.0 New Feature

October 11th, 2009 Neeraj Mathur No comments

Microsoft has introduced a new Optional Parameter feature in C# 4.0. In this if we will not specify the value of parameter then function will automatically take default value rather then giving the compile time error.

Lets look at the example:

public void SendEMail(string toAddress, string bodyText, bool ccAdmin = true, bool isBodyHtml = false)
{
   // Full implementation here
}

Least specified “overload” consuming code written will look like this:

SendEMail("jhon@foo.com", "Hello World");

The IL that the C# compiler will generate will actually be the equivalent of this:

SendEMail("jhon@foo.com", "Hello World", true, false);

The best part in this is that, unlike traditional method overloading, you have the ability to omit only the 3rd parameter in conjunction with the new Named Parameters language feature and write your code like this:

SendEMail("jhon@foo.com", "Hello World", isBodyHtml: true);

This will allow consuming code to only pass 3 arguments for succinctness but still invoke the appropriate overload since the IL generated in that instance will be equivalent to this:

SendEMail("jhon@foo.com", "Hello World", true, true);
VN:F [1.6.3_896]
Rating: 3.5/5 (2 votes cast)
Categories: C Sharp Tags: , , ,

Lambda Expressions in C# 3.0

September 29th, 2009 govindsyadav 1 comment

In this post we are discussing the new feature Lambda Expressions being introduced in c# 3.0 .

C# 3.0 introduces a new feature called lambda expressions. While this is not a revolutionary thing, it opens up a plethora of new possibilities for .Net programming. This post aims to introducing the Lambda Expressions by providing a background, the syntax for using it , and a suitable example.

A Little Bit of History

With the release of C# 2.0, came anonymous methods. For those of you who don’t know it, anonymous methods allow developers to write a block of code in places where a delegate is expected. Prior to this, developers are required to explicitly declare methods and attach them to delegates.

Just summing up over here , about delegates .

Delegates can be understood as a type safe object capable of pointing to another function (s) or method (s), or in very simple terms we can say function pointers.

Delegates do basically have 3 important pieces.

a. Name of method to which it is going to call or point

b. Arguments that will be passed

c. The return value .

In c# , delegate keyword is used while creating delegates .

ex : public delegate int mydeleg(int x);

Lambda Expression (Lambda expressions are simply delegate functions.(enhanced version))

In order to learn functional programming and a more declarative style of writing code, we need first to cover some basic material.  One of the first concepts is that of lambda expressions.  Lambda expressions can be summarized in one sentence:

Lambda expressions are simply functions/methods.

They have a different syntax, primarily so that they can be written in expression context (more on this shortly) instead of as a member of a class.  However, that is all they are.  For instance, the following lambda expression:

c => c + 1

is a function that takes one argument, c, and returns the value c + 1.

Actually, they are slightly more complicated than this, but not much more.  For the purposes of this tutorial, you only use lambda expressions when calling a method that takes a delegate as a parameter.  Instead of writing a method, creating a delegate from the method, and passing the delegate to the method as a parameter, you can simply write a lambda expression in-line as a parameter to the method.

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

All lambda expressions use the lambda operator =>, which is read as “goes to”. The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read “x goes to x times x.” This expression can be assigned to a delegate type as follows:

 

 

C#

delegate int del(int i);
static void Main(string[] args)
{
 del myDelegate = x => x * x;
 int j = myDelegate(5); //j = 25
}

More about Lambda Expressions can be found here :
http://blogs.msdn.com/ericwhite/pages/Lambda-Expressions.aspx
http://msdn.microsoft.com/en-us/library/bb397687.aspx

VN:F [1.6.3_896]
Rating: 0.0/5 (0 votes cast)

HttpWebRequest, HttpWebResponse and send POST request to another web server

September 23rd, 2009 Neeraj Mathur No comments

Some times we do have a requirement to call external web pages through our application.

The System.Net.HttpWebRequest Class allow us to make a call to any web page programmatically.

In the below code you will see how we can make a call to any webpage and get there response on our page.

if (!(IsPostBack))
     {
       try
        {
                    System.Net.HttpWebRequest webReader;
                    Uri targetUri = new Uri("http://www.soliddotnet.com/index.php/contributors/neeraj-mathur");
webReader = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(targetUri);
 
//In the above code http://www.soliddotnet.com/index.php/contributors/neeraj-mathur/ is used as an example 
 
//it can be a different domain with a different filename and extension
                    if ((webReader.GetResponse().ContentLength > 0))
                    {
 
         System.IO.StreamReader strResponse = new System.IO.StreamReader(webReader.GetResponse().GetResponseStream());
 
         Response.Write(strResponse.ReadToEnd());
 
         if (strResponse != null) strResponse.Close();
 
         }
 
        }
 
        catch (System.Net.WebException ex)
        {
 
         Response.Write("Page does not exist.");
 
         }
 
 }

NOTE: If you will try to access any web page from your localhost then this example wont work at all, you need to be on web domain to test this code

Now comes How to use HttpWebRequest to send POST request to another web server?

Typical example of this kind of situation is when you need to access some web resource through your application and that requires login credentials, So for this you can send post request to another server.

private void OnPostInfoClick(object sender, System.EventArgs e)
{
	string strUserId = txtUserId.Text;
	string strPassword = txtPassword.Text;
 
	ASCIIEncoding encoding=new ASCIIEncoding();
	string postData="userid="+strUserId;
	postData += ("&password="+strPassword);
	byte[]  data = encoding.GetBytes(postData);
 
	// Prepare web request...
	HttpWebRequest myRequest =
	  (HttpWebRequest)WebRequest.Create("http://yourwebresource/MyIdentity/Default.aspx");
	myRequest.Method = "POST";
	myRequest.ContentType="application/x-www-form-urlencoded";
	myRequest.ContentLength = data.Length;
	Stream newStream=myRequest.GetRequestStream();
	// Send the data.
	newStream.Write(data,0,data.Length);
	newStream.Close();
}

Resources :

http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx

http://www.codeproject.com/KB/IP/httpwebrequest_response.aspx

VN:F [1.6.3_896]
Rating: 5.0/5 (1 vote cast)