Monday, July 09, 2012
Thursday, April 22, 2010
.NET Framework General Reference
.NET Framework General Reference
Design Guidelines for Class Library Developers
http://msdn.microsoft.com/en-us/library/czefa0ke(vs.71).aspx
Design Guidelines for Class Library Developers
http://msdn.microsoft.com/en-us/library/czefa0ke(vs.71).aspx
Thursday, March 18, 2010
Monday, February 15, 2010
Limit the number of namespaces used in your .net project of VS
How to limit the number of namespaces included in your .net project in VS?
Method 1:
it involves changing the default project item templates. You can find them in %ProgramFiles%\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates (for Visual Studio 2008). You may need to
clear out \Common7\IDE\ItemTemplatesCache before Visual Studio picks up your changes, although it should do this automatically.
Be careful and make sure to backup these directories first, because damaging them will render you unable to add new items from Visual Studio.
Not sure whether VS Express support this feature!
Method2:
Right click your code in the editor, and on the context menu, select "Organize Usings", then on the pop-out, select "Remove Unused Usings".
Method 1:
it involves changing the default project item templates. You can find them in %ProgramFiles%\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates (for Visual Studio 2008). You may need to
clear out \Common7\IDE\ItemTemplatesCache before Visual Studio picks up your changes, although it should do this automatically.
Be careful and make sure to backup these directories first, because damaging them will render you unable to add new items from Visual Studio.
Not sure whether VS Express support this feature!
Method2:
Right click your code in the editor, and on the context menu, select "Organize Usings", then on the pop-out, select "Remove Unused Usings".
Sunday, February 14, 2010
LINQ: Anonymous Class - select new
http://nayyeri.net/use-anonymous-types-to-select-data-in-linq
When using LINQ, normally you select data by using regular types. But thank to new language features in .NET 3.5, you're able to select entities with Anonymous Types, too. Follow this post to see how!
Now I add a new LINQ to SQL file to my project and drop my tables into it.
Now that I have all generated classes for my purpose, I can implement my code in the console application.
Don't laugh to sample data, please!!
This was a sample of selecting all persons with a normal string type for their Name field. But alternatively, you can select them with anonymous types to have a combination of them.
Using anonymous types, I can also get the benefit of assigning new names to data fields as is shown below.
When using LINQ, normally you select data by using regular types. But thank to new language features in .NET 3.5, you're able to select entities with Anonymous Types, too. Follow this post to see how!
Sample Application
Let me write a simple sample console application to use in this post. After creating this console application for .NET 3.5, I create a database with two tables named Person and Address. As names suggest, they keep data for persons and their addresses and there is a relationship between a field in Address and a field in Person.Now I add a new LINQ to SQL file to my project and drop my tables into it.
Now that I have all generated classes for my purpose, I can implement my code in the console application.
Select Entities with Anonymous Types
First I write a simple code to select the name of persons.static void Main(string[] args)
{
Console.Title = "Use Anonymous Types to Select Entities in LINQ";
DataClasses1DataContext dataContext = new DataClasses1DataContext();
var myQuery = from p in dataContext.Persons
select p.Name;
foreach (var person in myQuery)
{
Console.WriteLine(person);
}
Console.ReadLine();
}
Don't laugh to sample data, please!!
This was a sample of selecting all persons with a normal string type for their Name field. But alternatively, you can select them with anonymous types to have a combination of them.
static void Main(string[] args)
{
Console.Title = "Use Anonymous Types to Select Entities in LINQ";
DataClasses1DataContext dataContext = new DataClasses1DataContext();
var myQuery = from p in dataContext.Persons
select new { p.Name, p.Age };
foreach (var person in myQuery)
{
Console.WriteLine(person);
}
Console.ReadLine();
}
Using anonymous types, I can also get the benefit of assigning new names to data fields as is shown below.
static void Main(string[] args)
{
Console.Title = "Use Anonymous Types to Select Entities in LINQ";
DataClasses1DataContext dataContext = new DataClasses1DataContext();
var myQuery = from p in dataContext.Persons
select new
{
PersonName = p.Name,
PersonAge = p.Age,
PersonAddress = p.Address.Line1 + "\n" +
p.Address.Line2 + "\n" +
p.Address.Zip
};
foreach (var person in myQuery)
{
Console.WriteLine(person);
}
Console.ReadLine();
}
LINQ: Anonymous types - select new
http://msdn.microsoft.com/en-us/library/bb397696.aspx
Anonymous Types (C# Programming Guide)
Updated: July 2008
Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type. The type name is generated by the compiler and is not available at the source code level. The type of the properties is inferred by the compiler. The following example shows an anonymous type being initialized with two properties called Amount and Message.
var v = new { Amount = 108, Message = "Hello" };
Anonymous types are typically used in the select clause of a query expression to return a subset of the properties from each object in the source sequence. For more information about queries, see LINQ Query Expressions (C# Programming Guide).
Anonymous types are created by using the new operator with an object initializer. For more information about object initializers, see Object and Collection Initializers (C# Programming Guide).
Anonymous types are class types that consist of one or more public read-only properties. No other kinds of class members such as methods or events are allowed. An anonymous type cannot be cast to any interface or type except for object.
The most common scenario is to initialize an anonymous type with some properties from another type. In the following example, assume a class that is named Product that includes Color and Price properties together with several other properties that you are not interested in. Products is a collection of Product objects. The anonymous type declaration starts with the new keyword. It initializes a new type that uses only two properties from Product. This causes a smaller amount of data to be returned in the query.
If you do not specify member names in the anonymous type, the compiler gives the anonymous type members the same name as the property being used to initialize them. You must provide a name to a property that is being initialized with an expression.
C#
var productQuery =
from prod in products
select new { prod.Color, prod.Price };
foreach (var v in productQuery)
{
Console.WriteLine("Color={0}, Price={1}", v.Color, v.Price);
}
When an anonymous type is assigned to a variable, that variable must be initialized with the var construct. This is because only the compiler has access to the underlying name of the anonymous type. For more information about var, see Implicitly Typed Local Variables (C# Programming Guide).
Remarks
Anonymous types are reference types that derive directly from object. The compiler gives them a name although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.
If two or more anonymous types have the same number and type of properties in the same order, the compiler treats them as the same type and they share the same compiler-generated type information.
An anonymous type has method scope. To pass an anonymous type, or a collection that contains anonymous types, outside a method boundary, you must first cast the type to object. However, this defeats the strong typing of the anonymous type. If you must store your query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type.
Anonymous types cannot contain unsafe types as properties.
Because the Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashcode of the properties, two instances of the same anonymous type are equal only if all their properties are equal.
Courtesy: MSDN
Anonymous Types (C# Programming Guide)
Updated: July 2008
Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type. The type name is generated by the compiler and is not available at the source code level. The type of the properties is inferred by the compiler. The following example shows an anonymous type being initialized with two properties called Amount and Message.
var v = new { Amount = 108, Message = "Hello" };
Anonymous types are typically used in the select clause of a query expression to return a subset of the properties from each object in the source sequence. For more information about queries, see LINQ Query Expressions (C# Programming Guide).
Anonymous types are created by using the new operator with an object initializer. For more information about object initializers, see Object and Collection Initializers (C# Programming Guide).
Anonymous types are class types that consist of one or more public read-only properties. No other kinds of class members such as methods or events are allowed. An anonymous type cannot be cast to any interface or type except for object.
The most common scenario is to initialize an anonymous type with some properties from another type. In the following example, assume a class that is named Product that includes Color and Price properties together with several other properties that you are not interested in. Products is a collection of Product objects. The anonymous type declaration starts with the new keyword. It initializes a new type that uses only two properties from Product. This causes a smaller amount of data to be returned in the query.
If you do not specify member names in the anonymous type, the compiler gives the anonymous type members the same name as the property being used to initialize them. You must provide a name to a property that is being initialized with an expression.
C#
var productQuery =
from prod in products
select new { prod.Color, prod.Price };
foreach (var v in productQuery)
{
Console.WriteLine("Color={0}, Price={1}", v.Color, v.Price);
}
When an anonymous type is assigned to a variable, that variable must be initialized with the var construct. This is because only the compiler has access to the underlying name of the anonymous type. For more information about var, see Implicitly Typed Local Variables (C# Programming Guide).
Remarks
Anonymous types are reference types that derive directly from object. The compiler gives them a name although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.
If two or more anonymous types have the same number and type of properties in the same order, the compiler treats them as the same type and they share the same compiler-generated type information.
An anonymous type has method scope. To pass an anonymous type, or a collection that contains anonymous types, outside a method boundary, you must first cast the type to object. However, this defeats the strong typing of the anonymous type. If you must store your query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type.
Anonymous types cannot contain unsafe types as properties.
Because the Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashcode of the properties, two instances of the same anonymous type are equal only if all their properties are equal.
Courtesy: MSDN
Thursday, January 21, 2010
Wednesday, December 23, 2009
Wednesday, December 16, 2009
20 most useful code snippet key words used in visual studio .net 2008
20 most useful code snippet key words used in visual studio .net 2008
Type any of the keyword followed by two tab keys ... I am sure it will help you gracefully to reduce typo. errors
01. class - to create a new empty class
02. ctor - to create an empty default constructor
03. do - to create an empty do while construct
04. exception - to create a new user defined exception
05. for - to create an empty for construct
06. forr - to create an empty reverse for construct
07. foreach - to create an empty foreach construct
08. if - to create an empty if block
09. interface - to create an empty interface
10. mbox - to add MessageBox.Show()
11. namespace - to create a new namespace
12. propg - to add a "get" accessor and a private "set" accessor
13. sim - to add static int Main()
14. struct - to create an empty structure
15. svm - to add static void Main()
16. switch - to add an empty switch block
17. try - to add an empty try block
18. tryf - to add an emptry try...finally block
19. while - to crate an empty while construct
20. ~ - to create an empty destructor
Happy .net programmin
Type any of the keyword followed by two tab keys ... I am sure it will help you gracefully to reduce typo. errors
01. class - to create a new empty class
02. ctor - to create an empty default constructor
03. do - to create an empty do while construct
04. exception - to create a new user defined exception
05. for - to create an empty for construct
06. forr - to create an empty reverse for construct
07. foreach - to create an empty foreach construct
08. if - to create an empty if block
09. interface - to create an empty interface
10. mbox - to add MessageBox.Show()
11. namespace - to create a new namespace
12. propg - to add a "get" accessor and a private "set" accessor
13. sim - to add static int Main()
14. struct - to create an empty structure
15. svm - to add static void Main()
16. switch - to add an empty switch block
17. try - to add an empty try block
18. tryf - to add an emptry try...finally block
19. while - to crate an empty while construct
20. ~ - to create an empty destructor
Happy .net programmin
Tuesday, October 20, 2009
Saturday, October 03, 2009
Friday, October 02, 2009
Swap value of two variables without using third variable(.NET)
int a, b;
a = 10;
b = 20;
Console.WriteLine("Before Swapping a="+a+" b="+b);
a = a + b;
b = a - b;
a = a - b;
Console.WriteLine("After Swapping a=" + a + " b=" + b);
a = 10;
b = 20;
Console.WriteLine("Before Swapping a="+a+" b="+b);
a = a + b;
b = a - b;
a = a - b;
Console.WriteLine("After Swapping a=" + a + " b=" + b);
Friday, September 25, 2009
Using in .NET
Using .NET
Introduction
I was at work today, and someone asked me what happens when you use the using keyword in C#. Most people will tell you that it is something you use that will clean up any unmanaged resources for the specified object, which is not incorrect. But what actually happens at the IL level? How does it "clean up" unmanaged resources? I had my assumptions, but I really didn't know. So, I set out to find out for myself.
Tests
I decided I was going to run through a couple of tests:
Test #1
I wanted to see what the generated MSIL code looks like when I use the using keyword. So, I wrote some very simple sample code in C#, compiled it, then I decompiled it using ILDASM to see the MSIL code.
Test #2
I wanted to see if I could write code without using the using keyword that would generate the exact same MSIL code. This process was a little more trial and error, but was fairly easy.
Test #1
Here is my sample code:
Collapse Copy Code
[STAThread]
private static void Main(string[] args)
{
using (Bitmap bitmap1 = new Bitmap(100, 100))
{
Console.WriteLine("Width: {0}, Height: {1}", bitmap1.Width, bitmap1.Height);
}
Console.ReadLine();
}
As you can see... nothing special in the code. Create a new Bitmap inside a using statement, write some output to the console, wait for user input, then exit.
What does this look like when we build the app, then decompile it into MSIL? Check it out:
Collapse Copy Code
.method private hidebysig static void Main(string[] args) cil managed
{
.custom instance void [mscorlib]System.STAThreadAttribute::.ctor()
.entrypoint
.maxstack 4
.locals init (
[0] [System.Drawing]System.Drawing.Bitmap bitmap1)
L_0000: ldc.i4.s 100
L_0002: ldc.i4.s 100
L_0004: newobj instance void
[System.Drawing]System.Drawing.Bitmap::.ctor(int32, int32)
L_0009: stloc.0
L_000a: ldstr "Width: {0}, Height: {1}"
L_000f: ldloc.0
L_0010: callvirt instance int32 [System.Drawing]System.Drawing.Image::get_Width()
L_0015: box int32
L_001a: ldloc.0
L_001b: callvirt instance int32 [System.Drawing]System.Drawing.Image::get_Height()
L_0020: box int32
L_0025: call void [mscorlib]System.Console::WriteLine(string, object, object)
L_002a: leave.s L_0036
L_002c: ldloc.0
L_002d: brfalse.s L_0035
L_002f: ldloc.0
L_0030: callvirt instance void [mscorlib]System.IDisposable::Dispose()
L_0035: endfinally
L_0036: call string [mscorlib]System.Console::ReadLine()
L_003b: pop
L_003c: ret
.try L_000a to L_002c finally handler L_002c to L_0036
}
Test #1 Results
So the results from test #1 are interesting. The using keyword is basically a try - finally block, without a catch , where IDisposable.Dispose() is called in the finally . One interesting thing to note is that the Bitmap constructor is called before the try block begins. This tells me that if, in the Bitmap constructor, an unmanaged resource is allocated, but not freed, then the constructor throws an exception, the unmanaged resource will not get freed by a call to the IDisposable.Dispose(). This also assumes that the IDisposable is implemented properly. Therefore the using keyword is useless if the IDisposable is not implemented properly. The constructor should clean up resources if it fails, and the Dispose() method should clean up all unmanaged resources. Chances are good that Microsoft has implemented IDisposable correctly in their classes, so watch out for this if you are implementing your own IDisposable.
Test #2
Based on the MSIL code that resulted from Test #1, I decided to write the same code using try - finally blocks. This is what I came up with:
Collapse Copy Code
[STAThread]
private static void Main(string[] args)
{
Bitmap bitmap1 = new Bitmap(100, 100);
try
{
Console.WriteLine("Width: {0}, Height: {1}", bitmap1.Width, bitmap1.Height);
}
finally
{
if (bitmap1 != null)
{
bitmap1.Dispose();
}
}
Console.ReadLine();
}
And this is what it looked like in MSIL:
Collapse Copy Code
.method private hidebysig static void Main(string[] args) cil managed
{
.custom instance void [mscorlib]System.STAThreadAttribute::.ctor()
.entrypoint
.maxstack 4
.locals init (
[0] [System.Drawing]System.Drawing.Bitmap bitmap1)
L_0000: ldc.i4.s 100
L_0002: ldc.i4.s 100
L_0004: newobj instance void
[System.Drawing]System.Drawing.Bitmap::.ctor(int32, int32)
L_0009: stloc.0
L_000a: ldstr "Width: {0}, Height: {1}"
L_000f: ldloc.0
L_0010: callvirt instance int32 [System.Drawing]System.Drawing.Image::get_Width()
L_0015: box int32
L_001a: ldloc.0
L_001b: callvirt instance int32 [System.Drawing]System.Drawing.Image::get_Height()
L_0020: box int32
L_0025: call void [mscorlib]System.Console::WriteLine(string, object, object)
L_002a: leave.s L_0036
L_002c: ldloc.0
L_002d: brfalse.s L_0035
L_002f: ldloc.0
L_0030: callvirt instance void [System.Drawing]System.Drawing.Image::Dispose()
L_0035: endfinally
L_0036: call string [mscorlib]System.Console::ReadLine()
L_003b: pop
L_003c: ret
.try L_000a to L_002c finally handler L_002c to L_0036
}
Test #2 Results
It is almost exactly like the MSIL generated from the using keyword, except this calls Image.Dispose() rather than IDisposable.Dispose(), but the effect is the same. Just for fun, I regenerated C# code using Lutz Roeder's .NET Reflector, which is an invaluable tool, and here is the result:
Collapse Copy Code
[STAThread]
private static void Main(string[] args)
{
using (Bitmap bitmap1 = new Bitmap(100, 100))
{
Console.WriteLine("Width: {0}, Height: {1}", bitmap1.Width, bitmap1.Height);
}
Console.ReadLine();
}
This looks exactly like our original code!!!
Conclusion
This was really a fun experiment that revealed a lot about the way .NET works behind the scenes. I hope you guys enjoy this as much as I did.
Courtesy: http://www.codeproject.com/KB/cs/CSharp_using.aspx, Peter Femiani
Introduction
I was at work today, and someone asked me what happens when you use the using keyword in C#. Most people will tell you that it is something you use that will clean up any unmanaged resources for the specified object, which is not incorrect. But what actually happens at the IL level? How does it "clean up" unmanaged resources? I had my assumptions, but I really didn't know. So, I set out to find out for myself.
Tests
I decided I was going to run through a couple of tests:
Test #1
I wanted to see what the generated MSIL code looks like when I use the using keyword. So, I wrote some very simple sample code in C#, compiled it, then I decompiled it using ILDASM to see the MSIL code.
Test #2
I wanted to see if I could write code without using the using keyword that would generate the exact same MSIL code. This process was a little more trial and error, but was fairly easy.
Test #1
Here is my sample code:
Collapse Copy Code
[STAThread]
private static void Main(string[] args)
{
using (Bitmap bitmap1 = new Bitmap(100, 100))
{
Console.WriteLine("Width: {0}, Height: {1}", bitmap1.Width, bitmap1.Height);
}
Console.ReadLine();
}
As you can see... nothing special in the code. Create a new Bitmap inside a using statement, write some output to the console, wait for user input, then exit.
What does this look like when we build the app, then decompile it into MSIL? Check it out:
Collapse Copy Code
.method private hidebysig static void Main(string[] args) cil managed
{
.custom instance void [mscorlib]System.STAThreadAttribute::.ctor()
.entrypoint
.maxstack 4
.locals init (
[0] [System.Drawing]System.Drawing.Bitmap bitmap1)
L_0000: ldc.i4.s 100
L_0002: ldc.i4.s 100
L_0004: newobj instance void
[System.Drawing]System.Drawing.Bitmap::.ctor(int32, int32)
L_0009: stloc.0
L_000a: ldstr "Width: {0}, Height: {1}"
L_000f: ldloc.0
L_0010: callvirt instance int32 [System.Drawing]System.Drawing.Image::get_Width()
L_0015: box int32
L_001a: ldloc.0
L_001b: callvirt instance int32 [System.Drawing]System.Drawing.Image::get_Height()
L_0020: box int32
L_0025: call void [mscorlib]System.Console::WriteLine(string, object, object)
L_002a: leave.s L_0036
L_002c: ldloc.0
L_002d: brfalse.s L_0035
L_002f: ldloc.0
L_0030: callvirt instance void [mscorlib]System.IDisposable::Dispose()
L_0035: endfinally
L_0036: call string [mscorlib]System.Console::ReadLine()
L_003b: pop
L_003c: ret
.try L_000a to L_002c finally handler L_002c to L_0036
}
Test #1 Results
So the results from test #1 are interesting. The using keyword is basically a try - finally block, without a catch , where IDisposable.Dispose() is called in the finally . One interesting thing to note is that the Bitmap constructor is called before the try block begins. This tells me that if, in the Bitmap constructor, an unmanaged resource is allocated, but not freed, then the constructor throws an exception, the unmanaged resource will not get freed by a call to the IDisposable.Dispose(). This also assumes that the IDisposable is implemented properly. Therefore the using keyword is useless if the IDisposable is not implemented properly. The constructor should clean up resources if it fails, and the Dispose() method should clean up all unmanaged resources. Chances are good that Microsoft has implemented IDisposable correctly in their classes, so watch out for this if you are implementing your own IDisposable.
Test #2
Based on the MSIL code that resulted from Test #1, I decided to write the same code using try - finally blocks. This is what I came up with:
Collapse Copy Code
[STAThread]
private static void Main(string[] args)
{
Bitmap bitmap1 = new Bitmap(100, 100);
try
{
Console.WriteLine("Width: {0}, Height: {1}", bitmap1.Width, bitmap1.Height);
}
finally
{
if (bitmap1 != null)
{
bitmap1.Dispose();
}
}
Console.ReadLine();
}
And this is what it looked like in MSIL:
Collapse Copy Code
.method private hidebysig static void Main(string[] args) cil managed
{
.custom instance void [mscorlib]System.STAThreadAttribute::.ctor()
.entrypoint
.maxstack 4
.locals init (
[0] [System.Drawing]System.Drawing.Bitmap bitmap1)
L_0000: ldc.i4.s 100
L_0002: ldc.i4.s 100
L_0004: newobj instance void
[System.Drawing]System.Drawing.Bitmap::.ctor(int32, int32)
L_0009: stloc.0
L_000a: ldstr "Width: {0}, Height: {1}"
L_000f: ldloc.0
L_0010: callvirt instance int32 [System.Drawing]System.Drawing.Image::get_Width()
L_0015: box int32
L_001a: ldloc.0
L_001b: callvirt instance int32 [System.Drawing]System.Drawing.Image::get_Height()
L_0020: box int32
L_0025: call void [mscorlib]System.Console::WriteLine(string, object, object)
L_002a: leave.s L_0036
L_002c: ldloc.0
L_002d: brfalse.s L_0035
L_002f: ldloc.0
L_0030: callvirt instance void [System.Drawing]System.Drawing.Image::Dispose()
L_0035: endfinally
L_0036: call string [mscorlib]System.Console::ReadLine()
L_003b: pop
L_003c: ret
.try L_000a to L_002c finally handler L_002c to L_0036
}
Test #2 Results
It is almost exactly like the MSIL generated from the using keyword, except this calls Image.Dispose() rather than IDisposable.Dispose(), but the effect is the same. Just for fun, I regenerated C# code using Lutz Roeder's .NET Reflector, which is an invaluable tool, and here is the result:
Collapse Copy Code
[STAThread]
private static void Main(string[] args)
{
using (Bitmap bitmap1 = new Bitmap(100, 100))
{
Console.WriteLine("Width: {0}, Height: {1}", bitmap1.Width, bitmap1.Height);
}
Console.ReadLine();
}
This looks exactly like our original code!!!
Conclusion
This was really a fun experiment that revealed a lot about the way .NET works behind the scenes. I hope you guys enjoy this as much as I did.
Courtesy: http://www.codeproject.com/KB/cs/CSharp_using.aspx, Peter Femiani
Monday, September 21, 2009
Friday, September 18, 2009
Subscribe to:
Posts (Atom)