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
|
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 : .net (9 posts)
|
|
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
- Sliding
- 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>
|
|
|
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");
|
|
|
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…”
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
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)

|
|
|
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);
}
}
}
|
|
|
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.
|
|
|
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
|
|
|
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
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.
Tab characters (\0x09) should not be used in code. All indentation should be done with 4 space characters.
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); }
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.
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?
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 }
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)
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.
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.
- 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 { … }
}
}
Original article posted by http://www.misfitgeek.com/
|
|
|
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;
}
}
}
}
|
|
|
Mon, 20 Oct, 2008
|
|
|
In this you will learn about new feature in .NET Framework 2.0. Various aspects such as Support for 64 bit platform application development, Access control list support (ACL), ADO.NET, ASP.NET, Authenticated streams,COM Interop Service Enhancements, Console Class Additions, Data Protection API, Detecting changes in Network connectivity, Disjunctive Demands, Distributed Computing, EventLog Enhancements, Expanded Certificate Management, FTP Support, Generics and Generic Collection, I/O Enhancements and several other feature are discussed here below.
The Microsoft.NET framework of Version 2.0 extends the .NET framework of Version 1.1. It was developed under the code name ‘Whidbey”. Whidbey includes the .NET framework, various user interface types such as Windows forms, ASP.NET and the compact framework. It also includes the official languages C#, Visual Basic.NET and J# and the Development environment. In this section we shall focus on the main changes brought into the .NET framework by the 2.0 version.
Support for 64 bit platform application development. These applications can run faster and take advantage of more memory that is available and users can build managed code libraries or easily use unmanaged code libraries on 64.bit machines.
Access control list support (ACL). This is used to grant or revoke permission to use a particular resource on a computer. Several new classes have been added to the .NET Framework to enable manage code to create and modify ACL. Members that use ACL have been added to the I/O, registry and threading classes.
ADO.NET now supports user defined types, asynchronous database operations, XML data types, large value types, snapshot isolation, and has attributes that allow applications to support multiple active result sets(MARS) with SQL Server 2005.
ASP.NET has received most attention. A number of new features have been added to ASP.NET such as new controls for development of dynamic web pages. New Data controls for displaying and editing data that do not require the user to write code add to the ease of application development. The code behind model developed for use in ASP.NET makes it more robust. New caching features such as ability to cache dependency tables in SQL server database have been introduced. The current version allows users customize web pages in a number of ways. Property values for individual user profiles can be automatically tracked. Web parts can be used to allow users customize their pages in the browser. Navigation menus using simple controls can be added. Master pages enables users create layouts for all pages in the site and themes allow him to define a consistent look and feel for the site. The Web site can be precompiled to produce an executable code from source files. The resulting output can be displayed on a production server. ASP.NET enhancements also include new tools and classes which make website management easier and comprehensive. A wide variety of browsers are accommodated in ASP.NET and by default controls render output that is compatible with XHTML 1.1 standards. The device filter can be used to specify different property values for the same control on different browsers.
Authenticated streams is the new class introduced into the .NET Framework to enable users transmit secure information between a client and a server. The System.Net.NegotiateStream and System.Net.SslStream are classes which authenticate the transmission of data. These stream classes support mutual authentication, data encryption and data signing. The System.Net.NegotiateStream class uses security protocol for authentication while the later uses the Secure socket layer for authentication.
COM Interop Service Enhancements include enhancements that have been made to classes and tools that support interoperability with COM. These enhancements are of four kinds.The System.Runtime.InteropServices.SafeHandle and System.Runtime.InteropServices.CriticalHandle classes and the derived classes are designed to provide safe and reliable means of manipulating the operating system handles.Enhancements to interop marchaler has given the user the ability to wrap native function pointers into delegates and to marshal fixed size arrays of structures inside structures. The performance calls between applications in different domains have been fine tuned. Type Library Importer and Type Library export switches have eliminated the dependency on the registry for resolution of type library references.
Console Class Additions of members to the System.Console Class enable the manipulation of dimensions of the console window and screen buffer. This is extremely useful for creation of animations which require moving a rectangular area of the screen buffer. Other new members in this class help control the foreground and background colors of texts, the visibility and size of the cursor and the frequency and duration of the console beep.
Data Protection API has been expanded with the inclusion of four new methods that allow applications encrypt passwords, keys, connection strings and so on. Blocks of memory can also be encrypted if the operating system is Windows Server 2003 or above.
Debugger Display Attributes have been tweaked to give the user control over how the class is displayed in the debugger. The user can now identify the most useful information he needs to display in the debugger and make the required settings for the same.
Debugger Edit and Continue Support is reintroduced into 2.0 .NET Framework to enable users who are debugging applications to make changes to source code while executing in the break mode. The user can now make the changes, resume the execution and observe the effect. This feature is available in all languages.
Detecting changes in Network connectivity is enabled by the use of the System.Net.NetworkInformation.NetworkChange. The user can now receive notification when an Internet Protocol (IP) address of a network Interface changes. This can occur due to disconnected network cable, hardware failure etc.
Disjunctive Demands allows multiple code identities to access a class or method. The new security actions that have been created allow multiple identity permissions to be simultaneously demanded, inheritance demanded or link demanded. The DemandChoice security action now allows the user demand several strong name identities to allow the stack walk to succeed. The InheritanceDemandChoice and LinkDemandChoice are the two other security codes that have been introduced in this version of Visual Studio.NET.
Distributed Computing gives support for FTP client requests, caching of HTTP resources, automatic proxy discovery, and obtaining network traffic and statistical information. The Web server class has now been added to the namespace and this can be used to create simple web server for responding to HTTP requests. Output trace information for application debugging and diagnostics are generated by classes. Performance and security enhancements have been added to the System.Net.Sockets.Socket and System.Uri classes. Support for SOAP 1.2 and nullable elements have been added to System.Web.Services. Channel security features have been added to System.Runtime.Remoting.Channels. Authentication, encryption and load balancing are now supported by the TCP channel.
EventLog Enhancements enable the use of custom DLLs for messages, parameters and categories.
Expanded Certificate Management now supports X.509 certificate stores, chains and extensions. Certificates can be signed and verified without platform invoke using X.509 certificates. PKCS7 signatures, encryption and CMS are also supported
FTP Support is now integrated into 2.0 with the introduction of the classes System.Net.WebRequest, System.Net.WebResponse and System.Net.WebClient.
Generics and Generic Collection allow the user create flexible, reusable code. The generics act as templates that allow classes, methods, structures, interfaces and methods to be declared and defined with an Unspecified parameters. The types are specified only when the generic is used. System.Namespace and System.Collections.Generic provide the generic classes and methods. While the latter namespace supports strongly typed collections, System.Nullable provides for a standard representation of optional values. VB.NET, C# and C++ support generics. Generic types and methods can be examined and manipulated at runtime using reflection which has been extended. New members have been added to System.Type and System.Reflection.MethodInfo to identify generic types, obtain type parameter lists or create specific types.
Globalization has been extended with five new features to support custom cultures and languages. Minor customizations of existing cultures or creation of new cultures becomes possible with the new .NET 2.0. Encoding and decoding are done by mapping a Unicode character to and from a stream of bytes that are transferred to a physical medium such as a disk or communication line. Failure to complete the mapping operation can be compensated using the new encoding and decoding fallback feature supported by several classes in the System.Text Namespace. The .NET framework also supports the latest normalization standard defined by the Unicode consortium and the process converts character representations of text to a standard form that can be compared for equivalence.
I/O Enhancements have made the various I/O classes usable and functional. Users can now read and write text files easily and obtain information about a drive if needed. The System.IO.Compression namespace helps read and write data with the GZIP compression and decompression standard described by the IETF REC 1951 and RFC 1952 specifications.
Manifest Based Activation provides support for loading and activating applications using a manifest. This is essential for ClickOnce applications which use the manifest to load the application as against the traditional usage of the assembly to load the application.
.NET Framework Remoting now supports IPv6 addresses and the exchange of generic types. The process of authentication and encryption is supported by System.Runtime.Remoting.Channels.Tcp namespace. The System.Runtime.Remoting.Channels.Ipc permit applications in the same computer communicate with each other without using the network. A connection cache time out can be configured and the number of method retries can be set to improve network performance where remote clusters are involved.
Local computer Network configuration and Usage Information can be obtained by using the classes in the System.Net.NetworkInformation namespace. IP, IPv4, IPv6, TCP and UDP network traffic statistics can be obtained. Local computers network adapter information can also be viewed by users.
Ping enables the user verify whether a remote computer is accessible over the network. The System.Net
Processing HTTP requests from within applications. The System.Net.HttpListener class can be used to create a simple web server that responds to HTTP requests. This web server remains active so long as the application is live and is available only on applications running on Windows XP with Service Pack 2 or Windows Server 2003
Control of Caching can now be done programmatically using the System.Net.Cache namespace. Applications can control the caching of resources obtained using System.Net>WebRequest, System.Net.WebResponse and System.Net.WebClient classes. The .NET framework provides predefined cache policies or the user can specify a custom cache policy for each request.
Programming Languages: A number of changes have been brought into the programming languages used with the .NET framework such as Operator overloading , partial classes, generics, xml documentation, New data types and New keywords in VB.NET and generics, Iterators, anonymous methods and Partial classes in C# . We will study the changes brought into ASP.NET and C# in some detail later in this series.
In this section of the tutorial we have listed out and briefly defined some the major changes that have been wrought into the .NET Framework. The direction of the change was to ensure that developers are freed from writing codes for 70% of the functionality required for their application. The idea was to help them develop in the language that they are familiar with and at the same time provide them with interoperability features that make the language selected seamlessly integrate with other languages of the .NET framework. In the sections that follow we shall examine the impact of these changes on how developers work within the new .NET framework.
|
|
|
|