Close AD

Chintan Patel's Blog
Home | Archive | Photo Albums | Links | Contact Sign In | Sign Up

About Author

Chintankumar Patel
09 Jun, 2008

Contact Me  

Working as a Technical Consultant for Conchango.

Having experience in to IT from 7+ years and working on Microsoft Technologies

Archive

2009 Dec   (1)
2008 Dec   (1)
2008 Oct   (3)
2008 Sep   (6)
2008 Aug   (1)
2008 Jul   (2)
2008 Jun   (7)

Recent Posts

Windows 7 review
Comments : 0
Not Rated  
Disable System Restore in Windows Vista
Comments : 3
Not Rated  
What's New in the .NET Framework 2.0 ?
Comments : 2
Not Rated  
How to work with partitions in Windows Vista / XP when Disk Management doesn’t work
Comments : 3
Not Rated  
How to resize a partition in Windows Vista?
Comments : 3
Not Rated  
Top 10 tricks for handling null values in Microsoft Office Access
Comments : 17
Not Rated  
What is Vista's ReadyBoost and SuperFetch Technology
Comments : 5
Not Rated  
What is YouTube? - An introduction to the YouTube.com
Comments : 5
Not Rated  
SQL DATEDIFF Function - Applies to MS SQL Server and MS Office Access
Comments : 4
Not Rated  
Booting from USB Pen/Key/Flash Drive (Windows/Linux)
Comments : 5
Not Rated  

Categories

.Net Graphics   (2)
.Net Technology   (6)
ASP.Net   (1)
General   (2)
Microsoft Access   (1)
Microsoft Visual Studio   (1)
Microsoft Windows   (4)
SQL   (1)
USB   (1)
Windows 7   (1)
Windows Vista   (2)

Tags

.Net , .Net Framework 2.0 , .Net Graphics , Asp.Net , Boot , C# , Class Library , Coding Standards , Convert File System , Database , DATEDIFF , DATEDIFF Function , Disk Management , Embedded Resources , EnableEventValidation , EnableViewState , EncoderParameter , FAT32 to NTFS , Form Authentication , HDD , High Quality Thumbnail , Intellisense , Linux , Microsoft Access , Microsoft's SQL , Partition , ReadyBoost , ReSharper , Resize Image , Resize Partition , Security , SQLDataReader , SuperFetch , System Restore , USB , Usb device not recognized , Vista , Visual Studio 2005 , What's New , Windows , Windows 7 , Windows Application , Windows Errors , Windows Vista , Windows XP , YouTube

2008 Jun (7 Posts)

Dynamic Event(e.g. Button Click) creating and handling in C# ASP.Net

Fri, 27 Jun, 2008

Here this article on dynamic event assignment will explain you how the ASP.Net event system works and fires an event.

We will take following things to be covered

  • Taking System.Web.UI.WebControls.Button as a testing Control
  • Flow of HTTP protocol and execution/handling of event
  • Failure of ASP.Net Event handling

General

When there .Net Framework was not introduced we had to check for the value of the HTML controls to process further and had to maintain the state of the INPUT control of HTML in multiple POSTs

The old way in Classic ASP to get the value of input element and to work on that Request.Form("InputElementName")

 

Where ASP.Net takes care of the stuff which we had to do in Classic ASP like maintaining state of the HTML elements between multiple POSTs.

Taking System.Web.UI.WebControls.Button as a testing Control

Creating Button control dynamically and adding on the Form following way and assign Click event to it,
Code in the Page_Load method will be called every time the Form Post
btn_Click method will be executed whenever the Dynamically created Button clicked.

protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
Button btn = new Button();
btn.ID = "btn" + i.ToString();
btn.Text = "Button " + i.ToString();
btn.Click += new EventHandler(btn_Click);

this.form1.Controls.Add(btn);
}
}

void btn_Click(object sender, EventArgs e)
{
//Get the button index so we can identify that which button has been clicked..
//because click event is same for every button
int btnIndex = Convert.ToInt32(((Button)sender).ID.Substring(3, 1));
Response.Write(btnIndex.ToString());
}



Flow of HTTP protocol and execution/handling of event

Basic flow is as follows

  • Browser sends HTTP request to IIS
  • IIS looks for the path on the server, and forwards the request to .Net CLR
  • Where CLR looks for the application domain and forwards the request to respective domain
  • .Net CLR process the request and revert back with the response and give it back to IIS and IIS to client.

Now see how events get handled in above case

If Page directives "EnableViewState" and "EnableEventValidation" is set to true( by default these are set to true )

 

  • Each control has ClientID property, which used to keep the track while execution of the event
  • When you assign event handler to any control(e.g. Button) it adds an entry to the Page's hidden input element "__EVENTVALIDATION" stating that which event is bound to which control,
    This will be in only case when "EnableEventValidation" is set to "true"
  • When fresh request has made the response will have hidden input element named "__EVENTVALIDATION" with the event mapping information, this mechanism reduces the risk of unauthorized postback requests and callbacks.
    Actually this information is used to validate the request on the server for the following security reason.
    • No one can make false request and invoke the server side method.
    • Using "EnableEventValidation" is good idea to increase security but this puts a load on bandwidth, because your page size increases.
  • When Button is clicked the HTML Page (Actually it is HTML but for server it is ASP.Net) posts the information to the server,
    where on server Page_Load method is going to call again and event will be assigned as per the code.
    but not exactly it will reassign the event... but it will reevaluate the HTTP Request and will map the fired event with the existing one and executes the assigned method.

Note: "EnableEventValidation" actually not used to execute/mapping the event on the server, but it is allows to match the what event(s) was assigned before the PostBack and what event has been assigned on the server, and reduces the risk of unauthorized postback requests and callbacks.

Failure of ASP.Net Event handling

In some cases developers faces some issues regarding firing of event has been not working....
The root cause behind this is, while PostBack the control doesn't have event assignment will not able to fire up the event.
See the following code

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
for (int i = 0; i < 10; i++)
{
Button btn = new Button();
btn.ID = "btn" + i.ToString();
btn.Text = "Button " + i.ToString();
btn.Click += new EventHandler(btn_Click);

this.form1.Controls.Add(btn);
}
}
}

void btn_Click(object sender, EventArgs e)
{
int btnIndex = Convert.ToInt32(((Button)sender).ID.Substring(3, 1));
Response.Write(btnIndex.ToString());
}


In above scenario Page_Load method doesn't creating mapping for the dynamically created buttons and not able to fire event because it will only be executed when there is no PostBack.




Disclaimer:Author is not responsible if any kind of provided information may false


  

Anonymous Methods/Delegates in C# .Net 2.0

Fri, 20 Jun, 2008

 

C# 2.0 provides a new feature called Anonymous Methods, which allow you to create inline un-named ( i.e. anonymous ) methods in your code, which can help increase the readability and maintainability of your applications by keeping the caller of the method and the method itself as close to one another as possible. This is akin to the best practice of keeping the declaration of a variable, for example, as close to the code that uses it.

Here is a simple example of using an anonymous method to find all the even integers from 1...10:

 

private int[] _integers =
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
}; int[] evenIntegers = Array.FindAll(_integers,
delegate(int
integer) { return (integer%2 == 0); } );

 

The Anonymous Method is:

 

 delegate(int integer)
    {
       
return (integer%2 == 0
);
    }

 

which is called for each integer in the array and returns either true or false depending on if the integer is even.

If you don't use an anonymous method, you will need to create a separate method as such:

 

private int[] _integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int[] evenIntegers = Array.FindAll(_integers, IsEven);

private bool IsEven(int integer)
{
    return (integer%2 == 0);
}

 

When you have very simple methods like above that won't be reused, I find it much more elegant and meaningful to use anonymous methods. The code stays closer together which makes it easier to follow and maintain.

Here is an example that uses an anonymous method to get the list of cities in a state selected in a DropDownList ( called States ):

 

List<City> citiesInFlorida =
cities.FindAll(delegate(City city)
     {
         return city.State.Name.Equals(States.SelectedValue);
     }
);

 

You can also use anonymous methods as such:

 

button1.Click +=

    delegate
        {
            MessageBox.Show("Hello");
        };

 

which for such a simple operation doesn't “deserve“ a separate method to handle the event.

Other uses of anonymous methods would be for asynchronous callback methods, etc.

Anonymous methods don't have the cool factor of Generics, but they do offer a more expressive in-line approach to creating methods that can make your code easier to follow and maintain.


  

Create High Quality Thumbnails/Resize using System.Drawing.Graphics - ASP.Net C# Code

Wed, 18 Jun, 2008

 

This post will help you to create High Quality Thumbnails or can Resize the image
The GetThumbnailImage() method of Bitmap class produces a thumbnail image from the file specified. Life is so easy with it. Not always though. Sometimes the thumbnails produced are low quality - pixelated and blurred

Why it Happens?

Image formats like jpeg may store the thumbnail inside the same file. If we use System.Drawing.Bitmap method GetThumbnailImage, method checks if there’s a thumbnail image stored into the file and, if the thumb is found, it returns that thumbnail version scaled to the width and height you requested. If the thumbnail version of the image is smaller then the size you requested to produce, thats when problem occurs. The thumbnails produced become pixelated as we know stretching an image to a larger once reduces the Image Quality.

Solution

First of all you will need to include the reference of following namespaces

using System.Drawing;
using System.Drawing.Design;


Use the following code to create High Quality Thumbnail/Resize the image.

string originalFilePath = "C:\\originalimage.jpg"; //Replace with your image path
string thumbnailFilePath = string.Empty;
 
Size newSize = new Size(120,90); // Thumbnail size (width = 120) (height = 90)
 
using (Bitmap bmp = new Bitmap(originalFilePath))
{
    thumbnailFilePath = "C:\\thumbnail.jpg"; //Change the thumbnail path if you want
 
    using (Bitmap thumb = new Bitmap((System.Drawing.Image)bmp, newSize))
    {
        using (Graphics g = Graphics.FromImage(thumb)) // Create Graphics object from original Image
        {
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
 
            //Set Image codec of JPEG type, the index of JPEG codec is "1"
            System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
 
            //Set the parameters for defining the quality of the thumbnail... here it is set to 100%
            System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);
            eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
 
            //Now draw the image on the instance of thumbnail Bitmap object
            g.DrawImage(bmp, new Rectangle(0, 0, thumb.Width, thumb.Height));
 
            thumb.Save(thumbnailFilePath, codec, eParams);
        }
    }
}

  

Adding/Using Embedded Resources in .Net Windows Application/Class Library (C#/VB.Net/ASP.Net)

Wed, 11 Jun, 2008

In .Net when you don’t want to relay for a file on physical location, then it is very good option to take an advantage of Embedded resources.

Using embedded resources you can add any file type in the assembly/DLL/EXE when they get compiled. And whenever you want to use it, load it from the assembly, the files get stored in the metadata of Assembly.

Here is an example of how to use Embedded Resources.

1.
Open Microsoft Visual Studio and create new project for C# Windows Application, here I have created Windows Application named “EmbeddedTest”, even you can use “Class Library” 2.
To add a file in the project Right click on the project name in Solution Explorer, select “Add” >> “Existing Item…”

Uploaded Image

3.
Now we have added a file to the project, so it doesn’t mean that it will automatically embedded in the Assembly, for that we need to change the files “Build Action” property to “Embedded Resource”, and compiler will include this file in metatdata. Here I have added Image file(dog.jpg), you can add one or more any kind of files


Uploaded Image

4.
Now use the following code in Form1_Load method to list all the Embedded Resources available in the Assembly

private void Form1_Load(object sender, EventArgs e){Assembly a = Assembly.GetExecutingAssembly(); string[] resources = a.GetManifestResourceNames(); foreach (string resourceName in resources){listBox1.Items.Add(resourceName);}}


5.
The following code is used to get the resource from the Manifest of the Assembly when user clicks on the listBox1

private void listBox1_SelectedIndexChanged(object sender, EventArgs e){if (listBox1.SelectedIndex == -1)return; string selectedResourceName = listBox1.SelectedItem.ToString(); Assembly a = Assembly.GetExecutingAssembly(); Stream stream = a.GetManifestResourceStream(selectedResourceName); if (stream != null){pictureBox1.Image = null;try{Bitmap bmp = Bitmap.FromStream(stream) as Bitmap; pictureBox1.Image = bmp;}catch (Exception ex){MessageBox.Show("Selected item is not Image");} }}


In Step 5 the we first got the Stream by using GetManifestResourceStream() and then after we load it in to Bitmap object, if in between error occurs when the Resource is not type of Bitmap an Exception is thrown and error message is displayed.

Download Full Source Code

Download Project EmbeddedTest.zip (349.79 KB)

Download Project With Example of using Class Library (866.59 KB)



Uploaded Image

 


  

Intellisense problem in Visual Studio 2005 after uninstalling JetBrains’ ReSharper

Tue, 10 Jun, 2008

After uninstalling JetBrains’ ReSharper tool I found that Intellisense wasn’t working and after a little digging around found that it was turned off in the Microsoft Visual Studio 2008 options.

The ReSharper tool does not reinstate those options when it uninstalls (I am assuming it turns those options off when installed to disable native VS Intellisense and provide its own).

Solution :

Navigate following path in to Microsoft Visual Studio 2005
Tools -> Options -> TextEditor -> C#
Under the “Statement Completion” option I ticked the two boxes: “Auto list members” and “Parameter Information”.

 

 

Uploaded Image


  

Connecting to Microsoft SQL Server using Windows Authentication

Mon, 09 Jun, 2008


To connect to MS SQL Server use the following connection string...

 SqlConnection _connection = new SqlConnection("data source=localhost;initial catalog=blog;integrated security=SSPI;persist security info=False;Trusted_Connection=Yes");

 When using ASP.Net application you may get an error of SqlDataReader or SqlCommand that 

 e.g. There is already an open DataReader associated with this Command which must be closed first

 In this case use the following connection string to avoid such errors...

 SqlConnection _connection = new SqlConnection("MultipleActiveResultSets=True;data source=.;initial catalog=blog;integrated security=SSPI;persist security info=False;Trusted_Connection=Yes");

 


  

Forms Authentication timeout attribute's default in ASP.NET 2.0

Mon, 09 Jun, 2008

The defualt TimeOut value for Form Authentication is 30

There are two type of Expiration of Authentication which is defined using slidingExpiration attribute

  1. Sliding
  2. Relative / Not Sliding

 in SlidingExpiration the user's authentication expiration time will reset eveytime he hits the server

when the SlidingExpiration is set to false the Authentication will expires when user reaches the timeout limit...

If you want to change the timeout value to be longer  in your local web.config file which is in minutes...

 

<configuration>

<system.web>

<authentication mode="Forms">

                  <forms loginUrl="~/Login.aspx" name="_LOGON" timeout="500000" path="/" slidingExpiration="false"></forms>

            </authentication>

</system.web>

</configuration>

 


  

Powered by NineOn Inc.