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

Tag : c# (8 posts)

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>

 


  

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");

 


  

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

 


  

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);
        }
    }
}

  

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.


  

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


  

.Net Coding Standards/Guidelines (C# .Net)

Tue, 15 Jul, 2008

Table of Contents

1. Introduction

2. Style Guidelines

2.1 Tabs & Indenting

2.2 Bracing

2.3 Commenting

2.3.1 Documentation Comments

2.3.2 Comment Style

2.4 Spacing

2.5 Naming

2.6 Naming Conventions

2.6.1 Interop Classes

2.7 File Organization

1. Introduction

First, read the .NET Framework Design Guidelines. Almost all naming conventions, casing rules, etc., are spelled out in this document. Unlike the Design Guidelines document, you should treat this document as a set of suggested guidelines. These generally do not effect the customer view so they are not required.

2. Style Guidelines

2.1 Tabs & Indenting

Tab characters (\0x09) should not be used in code. All indentation should be done with 4 space characters.

2.2 Bracing

Open braces should always be at the beginning of the line after the statement that begins the block. Contents of the brace should be indented by 4 spaces. For example:

if (someExpression)
{
DoSomething();
}
else
{
DoSomethingElse();
}

“case” statements should be indented from the switch statement like this:

switch (someExpression)
{

case 0:
DoSomething();
break;

case 1:
DoSomethingElse();
break;

case 2:
{
int n = 1;
DoAnotherThing(n);
}
break;
}

Braces should never be considered optional. Even for single statement blocks, you should always use braces. This increases code readability and maintainability.

for (int i=0; i<100; i++) { DoSomething(i); }

2.3 Single line statements

Single line statements can have braces that begin and end on the same line.

public class Foo
{
int bar;

public int Bar
{
get { return bar; }
set { bar = value; }
}

}

It is suggested that all control structures (if, while, for, etc.) use braces, but it is not required.

2.4 Commenting

Comments should be used to describe intention, algorithmic overview, and/or logical flow. It would be ideal, if from reading the comments alone, someone other than the author could understand a function’s intended behavior and general operation. While there are no minimum comment requirements and certainly some very small routines need no commenting at all, it is hoped that most routines will have comments reflecting the programmer’s intent and approach.

2.4.1 Copyright notice

Each file should start with a copyright notice. To avoid errors in doc comment builds, you don’t want to use triple-slash doc comments, but using XML makes the comments easy to replace in the future. Final text will vary by product (you should contact legal for the exact text), but should be similar to:

//-----------------------------------------------------------------------
// <copyright file="ContainerControl.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

2.4.2 Documentation Comments

All methods should use XML doc comments. For internal dev comments, the <devdoc> tag should be used.

public class Foo
{

/// <summary>Public stuff about the method</summary>
/// <param name=”bar”>What a neat parameter!</param>
/// <devdoc>Cool internal stuff!</devdoc>
///
public void MyMethod(int bar) { … }

}

However, it is common that you would want to move the XML documentation to an external file – for that, use the <include> tag.

public class Foo
{

/// <include file='doc\Foo.uex' path='docs/doc[@for="Foo.MyMethod"]/*' />
///
public void MyMethod(int bar) { … }

}

UNDONE§ there is a big doc with all the comment tags we should be using… where is that?

2.4.3 Comment Style

The // (two slashes) style of comment tags should be used in most situations. Where ever possible, place comments above the code instead of beside it. Here are some examples:

// This is required for WebClient to work through the proxy
GlobalProxySelection.Select = new WebProxy("http://itgproxy");

// Create object to access Internet resources
//
WebClient myClient = new WebClient();

Comments can be placed at the end of a line when space allows:

public class SomethingUseful
{
private int itemHash; // instance member
private static bool hasDoneSomething; // static member
}

2.5 Spacing

Spaces improve readability by decreasing code density. Here are some guidelines for the use of space characters within code:

  • Do use a single space after a comma between function arguments.
    Right: Console.In.Read(myChar, 0, 1);
    Wrong: Console.In.Read(myChar,0,1);
  • Do not use a space after the parenthesis and function arguments
    Right: CreateFoo(myChar, 0, 1)
    Wrong: CreateFoo( myChar, 0, 1 )
  • Do not use spaces between a function name and parenthesis.
    Right: CreateFoo()
    Wrong: CreateFoo ()
  • Do not use spaces inside brackets.
    Right: x = dataArray[index];
    Wrong: x = dataArray[ index ];
  • Do use a single space before flow control statements
    Right: while (x == y)
    Wrong: while(x==y)
  • Do use a single space before and after comparison operators
    Right: if (x == y)
    Wrong: if (x==y)
2.6 Naming

Follow all .NET Framework Design Guidelines for both internal and external members. Highlights of these include:

  • Do not use Hungarian notation
  • Do not use a prefix for member variables (_, m_, s_, etc.). If you want to distinguish between local and member variables you should use “this.” in C# and “Me.” in VB.NET.
  • Do use camelCasing for member variables
  • Do use camelCasing for parameters
  • Do use camelCasing for local variables
  • Do use PascalCasing for function, property, event, and class names
  • Do prefix interfaces names with “I”
  • Do not prefix enums, classes, or delegates with any letter

The reasons to extend the public rules (no Hungarian, no prefix for member variables, etc.) is to produce a consistent source code appearance. In addition a goal is to have clean readable source. Code legibility should be a primary goal.

2.7 Naming Conventions
2.7.1 Interop Classes

Classes that are there for interop wrappers (DllImport statements) should follow the naming convention below:

  • NativeMethods – No suppress unmanaged code attribute, these are methods that can be used anywhere because a stack walk will be performed.
  • UnsafeNativeMethods – Has suppress unmanaged code attribute. These methods are potentially dangerous and any caller of these methods must do a full security review to ensure that the usage is safe and protected as no stack walk will be performed.
  • SafeNativeMethods – Has suppress unmanaged code attribute. These methods are safe and can be used fairly safely and the caller isn’t needed to do full security reviews even though no stack walk will be performed.

class NativeMethods
{
private NativeMethods() {}

[DllImport(“user32”)]
internal static extern void FormatHardDrive(string driveName);
}

[SuppressUnmanagedCode]
class UnsafeNativeMethods
{
private UnsafeNativeMethods() {}

[DllImport(“user32”)]
internal static extern void CreateFile(string fileName);
}

[SuppressUnmanagedCode]
class SafeNativeMethods
{
private SafeNativeMethods() {}

[DllImport(“user32”)]
internal static extern void MessageBox(string text);
}

All interop classes must be private, and all methods must be internal . In addition a private constructor should be provided to prevent instantiation.

2.8 File Organization
  • Source files should contain only one public type, although multiple internal classes are allowed
  • Source files should be given the name of the public class in the file
  • Directory names should follow the namespace for the class

For example, I would expect to find the public class “System.Windows.Forms.Control” in “System\Windows\Forms\Control.cs”…

  • Classes member should be alphabetized , and grouped into sections (Fields, Constructors, Properties, Events, Methods, Private interface implementations, Nested types)
  • Using statements should be inside the namespace declaration.

namespace MyNamespace
{

using System;

public class MyClass : IFoo
{

// fields
int foo;

// constructors
public MyClass() { … }

// properties
public int Foo { get { … } set { … } }

// events
public event EventHandler FooChanged { add { … } remove { … } }

// methods
void DoSomething() { … }
void FindSomethind() { … }

//private interface implementations
void IFoo.DoSomething() { DoSomething(); }

// nested types
class NestedType { … }

}

}

Advertisement
Car Insurance - Compare Motor Insurance Quotes
Saga Car Insurance Post Office Car Insurance Prudential Car Insurance
Elephant Car insurance Privilege Car Insurance Esure Car Insurance

Original article posted by http://www.misfitgeek.com/


  

Resizing Images to match it's Scale in C# .Net

Mon, 18 Aug, 2008


Use the following code to generate the scaled Image which will be scaled to given PictureBox....
In this you can change the size of PictureBox and see how resizing works..


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

namespace ImageTest
{
    public class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private Button btnLoadImage;
        private PictureBox pictureBox1;
        private ColorDialog colorDialog1;

        /// 
        /// Required designer variable.
        /// 
        private System.ComponentModel.IContainer components = null;

        /// 
        /// Clean up any resources being used.
        /// 
        /// true if managed resources should be disposed; otherwise, false.
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void btnLoadImage_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog fd = new OpenFileDialog())
            {
                if (fd.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        using (Image img = Image.FromFile(fd.FileName))
                        {
                            ProcessImage(img);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error processing Image File" + Environment.NewLine + "Please check that file is valid image");
                    }
                }
            }
        }

        private void ProcessImage(Image img)
        {
            Rectangle newRect = GetScaledRectangle(img, pictureBox1.ClientRectangle);
            pictureBox1.Image = GetResizedImage(img, newRect);
        }

        #region Windows Form Designer generated code

        /// 
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// 
        private void InitializeComponent()
        {
            this.btnLoadImage = new System.Windows.Forms.Button();
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.colorDialog1 = new System.Windows.Forms.ColorDialog();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            // 
            // btnLoadImage
            // 
            this.btnLoadImage.Location = new System.Drawing.Point(377, 110);
            this.btnLoadImage.Name = "btnLoadImage";
            this.btnLoadImage.Size = new System.Drawing.Size(75, 23);
            this.btnLoadImage.TabIndex = 0;
            this.btnLoadImage.Text = "Load Image";
            this.btnLoadImage.UseVisualStyleBackColor = true;
            this.btnLoadImage.Click += new System.EventHandler(this.btnLoadImage_Click);
            // 
            // pictureBox1
            // 
            this.pictureBox1.BackColor = System.Drawing.SystemColors.AppWorkspace;
            this.pictureBox1.Location = new System.Drawing.Point(29, 46);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(200, 200);
            this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
            this.pictureBox1.TabIndex = 1;
            this.pictureBox1.TabStop = false;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(514, 366);
            this.Controls.Add(this.pictureBox1);
            this.Controls.Add(this.btnLoadImage);
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Form1";
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        public static Rectangle GetScaledRectangle(Image img, Rectangle thumbRect)
        {
            if (img.Width < thumbRect.Width && img.Height < thumbRect.Height)
                return new Rectangle(thumbRect.X + ((thumbRect.Width - img.Width) / 2), thumbRect.Y + ((thumbRect.Height - img.Height) / 2), img.Width, img.Height);

            int sourceWidth = img.Width;
            int sourceHeight = img.Height;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)thumbRect.Width / (float)sourceWidth);
            nPercentH = ((float)thumbRect.Height / (float)sourceHeight);

            if (nPercentH < nPercentW)
                nPercent = nPercentH;
            else
                nPercent = nPercentW;

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            if (destWidth.Equals(0))
                destWidth = 1;
            if (destHeight.Equals(0))
                destHeight = 1;

            Rectangle retRect = new Rectangle(thumbRect.X, thumbRect.Y, destWidth, destHeight);

            if (retRect.Height < thumbRect.Height)
                retRect.Y = retRect.Y + Convert.ToInt32(((float)thumbRect.Height - (float)retRect.Height) / (float)2);

            if (retRect.Width < thumbRect.Width)
                retRect.X = retRect.X + Convert.ToInt32(((float)thumbRect.Width - (float)retRect.Width) / (float)2);

            return retRect;
        }

        public static Image GetResizedImage(Image img, Rectangle rect)
        {
            Bitmap b = new Bitmap(rect.Width, rect.Height);
            Graphics g = Graphics.FromImage((Image)b);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.DrawImage(img, 0, 0, rect.Width, rect.Height);
            g.Dispose();

            try
            {
                return (Image)b.Clone();
            }
            finally
            {
                b.Dispose();
                b = null;
                g = null;
            }
        }

    }
}

  

Powered by NineOn Inc.