Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Friday, June 14, 2013

Error - Operation is not valid due to the current state of the object.

Untitled Document
Whenever a postback is done, this error occurs when form fields are very large in number. The stack trace is:
at System.Web.HttpValueCollection.ThrowIfMaxHttpCollectionKeysExceeded() at System.Web.HttpValueCollection.FillFromEncodedBytes(Byte[] bytes, Encoding encoding) at System.Web.HttpRequest.FillInFormCollection()
By default, the maximum value of MaxHttpCollection is 1000.
To solve this error, increase the MaxHttpCollection value. Try adding the following setting in your web.config's <appsettings> block.
<appSettings>
      <add key="aspnet:MaxHttpCollectionKeys" value="2001" />  
</appSettings>
It can solve your problem. If you have very large records on your page, say 600 records in a grid, and you click on Submit, then increase the value of MaxHttpCollection.
Then change value 2000 to 5000 and test again. It will be resolved. :-)
-->

Thursday, June 6, 2013

.Net Garbage Collection

Memory management is the main concern for any application whether application is window based or web based. In .Net, CLR has garbage collector that executes as a part of our program and responsible for reclaiming the memory of no longer used objects. Garbage collector free the memory for objects that are no longer referenced and keeps the memory for future allocations.

Advantage of Garbage Collector

  1. Allow us to develop an application without having worry to free memory.
  2. Allocates memory for objects efficiently on the managed heap.
  3. -Reclaims the memory for no longer used objects and keeps the free memory for future allocations.
  4. Provides memory safety by making sure that an object cannot use the content of another object.

Memory Allocation in Managed Heap

The managed heap is a series of allocated memory segments (approx 16Mb in size each) to store and manage objects. The memory for newly created object is allocated at the next available location on the managed heap. If there is available free memory, the garbage collector doesn't search the dead objects for memory reclaim and memory allocations has been done very fast. If the memory is insufficient to create the object, the garbage collector search the dead objects for memory reclaim for the newly object.

An object is created using the new operator. This operator first makes sure that the bytes required by the new object fit in the reserved region (committing storage if necessary). If the object fits, NextObjPtr points to the object in the heap and object's constructor is called and the new operator returns the address of the object.

Key points about Garbage Collector

  1. All objects in the heap are allocated from one contiguous range of memory address and heap is divided into generations so that it is easy to eliminate the garbage objects by looking at only a small fraction of the heap.
  2. Gen 0 and Gen 1 occupy a single segment known as the ephemeral segment. Gen 2 is a set of further segments and the large object heap is yet another group of segments.
  3. Almost, all objects with-in a generation are of the same age.
  4. The newest objects are created at higher memory address while oldest memory objects are at lowest memory address with in the heap.
  5. The allocation pointer for the new objects marks the boundary between the allocated and free memory.
  6. Periodically the heap is compacted by removing the dead objects and sliding up the live objects towards the lower memory address end of the heap as shown in above fig.
  7. The order of objects (after memory reclaims) in memory remains the same as they were created.
  8. There are never any gaps among the objects in the heap.
  9. Only some of the free memory is committed when required and more memory is acquired from the OS in the reserved address range.

Generations in Managed Heap

The managed heap is organized into three generations so that it can handle short lived and long lived objects efficiently. Garbage collector first reclaim the short lived objects that occupy a small part of the heap.

  1. Generation 0

    This is the youngest generation and contains the newly created objects. Generation 0 has short-lived objects and collected frequently. The objects that survive the Generation 0 are promoted to Generation 1.
    Example : A temporary object.
  2. Generation 1

    This generation contains the longer lived objects that are promoted from generation 0. The objects that survive the Generation 1 are promoted to Generationen 2. Basically this generation serves as a buffer between short-lived objects and longest-lived objects.
  3. Generation 2

    This generation contains the longest lived objects that are promoted from generation 1 and collected infrequently.
    Example : An object at application level that contains static data which is available for the duration of the process.

Garbage Collector Working Phase

  1. Marking Phase

    In this phase garbage collector finds and creates a list of all live objects.
  2. Relocating Phase

    In this phase garbage collector updates the references to the objects that will be compacted.
  3. Compacting Phase

    In this phase garbage collector reclaims the memory occupied by the dead objects and compacts the surviving objects. The compacting phase moves the surviving objects toward the older end of the memory segment.

Note

  1. The large object heap is not compacted, because copying large objects imposes a performance penalty.

Garbage Collection Algorithm

Garbage collector determine whether any object in the heap is dead or not being used by the application. If such objects exist then memory used by these objects can be reclaimed. But how garbage collector know about these objects?
Each and every application has a set of roots and these identify the storage locations for the objects on the managed heap.
Example : All the global, static objects pointers and all the local variable/ parameter object pointers on the thread's stack in the application are considered part of the appilcation's roots. More over any CPU registers containing pointers to objects in the managed heap are also considered a part of the application's roots.
The list of active roots is maintained by the JIT compiler and CLR, and is made accessible to the garbage collector's algorithm.

Memory Reclaim Process

Now the garbage collecor starts go through the roots and make a graph of all the objects reachable from the roots. The below fig. shows a heap with allocated objects. In this heap the application roots directly refer to the objects 1,3,4,6 and object 3 & 6 refers to the objects 8 & 10. Hence all these objects will bacome the part of the live objects graph.

The objects which are not reachable from application's roots, are considered as garbage since these are not accessible by the application. In above heap objects 2,5,7,9 will be considered as dead objects.

The garbage collector then remove the dead objects from the heap and live objects will move toward the older end of the memory segment as shown in below fig. Garbage collector also updates all the references(including root references) to the moving objects in the heap.

Difference between Response.Redirect and Server.Transfer

In ASP.Net Technology both "Server" and "Response" are objects of ASP.Net. Server.Transfer and Response.Redirect both are used to transfer a user from one page to another. But there is some remarkable differences between both the objects which are as follow.

Response.Redirect

  1. Response.Redirect() will send you to a new page, update the address bar and add it to the Browser History. On your browser you can click back.
  2. It redirects the request to some plain HTML pages on our server or to some other web server.
  3. It causes additional roundtrips to the server on each request.
  4. It doesn’t preserve Query String and Form Variables from the original request.
  5. It enables to see the new redirected URL where it is redirected in the browser (and be able to bookmark it if it’s necessary).
  6. Response. Redirect simply sends a message down to the (HTTP 302) browser.

Server.Transfer

  1. Server.Transfer() does not change the address bar, we cannot hit back.One should use Server.Transfer() when he/she doesn’t want the user to see where he is going. Sometime on a "loading" type page.
  2. It transfers current page request to another .aspx page on the same server.
  3. It preserves server resources and avoids the unnecessary roundtrips to the server.
  4. It preserves Query String and Form Variables (optionally).
  5. It doesn’t show the real URL where it redirects the request in the users Web Browser.
  6. Server.Transfer happens without the browser knowing anything, the browser request a page, but the server returns the content of another.

Difference between int, Int16, Int32 and Int64

In the learning phase developer are not much aware of the difference between primitive, FCL (framework class library), reference, and value types. This cause bugs and performance issues into the code. In this article, I would like to expose the different behavior of integer type.

int

  1. It is a primitive data type defined in C#.
  2. It is mapped to Int32 of FCL type.
  3. It is a value type and represent System.Int32 struct.
  4. It is signed and takes 32 bits.
  5. It has minimum -2147483648 and maximum +2147483647 capacity.

Int16

  1. It is a FCL type.
  2. In C#, short is mapped to Int16.
  3. It is a value type and represent System.Int16 struct.
  4. It is signed and takes 16 bits.
  5. It has minimum -32768 and maximum +32767 capacity.

Int32

  1. It is a FCL type.
  2. In C#, int is mapped to Int32.
  3. It is a value type and represent System.Int32 struct.
  4. It is signed and takes 32 bits.
  5. It has minimum -2147483648 and maximum +2147483647 capacity.

Int64

  1. It is a FCL type.
  2. In C#, long is mapped to Int64.
  3. It is a value type and represent System.Int64 struct.
  4. It is signed and takes 64 bits.
  5. It has minimum –9,223,372,036,854,775,808 and maximum 9,223,372,036,854,775,807 capacity.

Note

  1. A number of developers think that int represents a 32-bit integer when the application is running on a 32-bit OS and it represents a 64-bit integer when the application is running on a 64-bit OS. This is absolutely wrong.
  2. In C# int is a primitive data type and it always mapped to System.Int32 whether the OS is 32-bit or 64-bit.

Difference between Generics and Collections

Generics provides the type safe code with re-usability like as algorithm. In algorithms such as sorting, searching, comparing etc. you don’t specify what data type(s) the algorithm operates on. The algorithm can be operates with any types of data. In the same way Generics operate, you can provide different data type to Generics. For example, a sorting algorithm can operates on integer type, decimal type, string type, DateTime type etc.
In this article, I will demonstrate the advantage of Generics over Collections. Following are the main advantage of Generics.

Code Re-usability with Generics

Suppose, you required to sort the integer and floating type numbers, then let's see how to do in collections and generics.

How to do it using Collections

  1. //Overloaded sort methods
  2. private int[] Sort(int[] inputArray)
  3. {
  4. //Sort array
  5. //and return sorted array
  6. return inputArray;
  7. }
  8. private float[] Sort(float[] inputArray)
  9. {
  10. //Sort array
  11. //and return sorted array
  12. return inputArray;
  13. }

How to do it using Generics

  1. private T[] Sort(T[] inputArray)
  2. {
  3. //Sort array
  4. //and return sorted array
  5. return inputArray;
  6. }
Here, T is short for Type and can be replaced with the Type defined in the C# language at runtime. So once we have this method, we can call it with different data types as follows and can see the beauty of Generics. In this way Generics provide code re-usability.

Now if you thinking you can make fool to the compiler by passing an integer array while it is asking for a float, you are wrong. Compiler will shows the error at compile time like as:

Type Safety with Generics

Suppose, you want to make a list of students, then let's see how to do in collections and generics.

How to do it using Collections

In collections we can use ArrayList to store a list of Student objects like as:
  1. class Student
  2. {
  3. public int RollNo{get; set;}
  4. public string Name{get; set;}
  5. }
  6.  
  7. //List of students
  8. ArrayList studentList = new ArrayList();
  9. Student objStudent = new Student();
  10. objStudent.Name = "Rajat";
  11. objStudent.RollNo = 1;
  12.  
  13. studentList.Add(objStudent);
  14.  
  15. objStudent = new Student();
  16. objStudent.Name = "Sam";
  17. objStudent.RollNo = 2;
  18.  
  19. studentList.Add(objStudent);
  20.  
  21. foreach (Object s in studentList)
  22. {
  23. //Type-casting. If s is anything other than a student
  24. Student currentStudent = (Student)s;
  25. Console.WriteLine("Roll # " + currentStudent.RollNo + " " + currentStudent.Name);
  26. }

Problem with Collections

Suppose by mistake you have added a string value to ArrayList like as
  1. studentList.Add("Generics"); //Fooling the compiler
Since ArrayList is a loosely typed collection and it never ensure compile-time type checking. Hence above statement will compile without error but it will throw an InvalidCastException at run time when you try to cast it to Student Type.

How to do it using Generics

In generics we can use generic List to store a list of Student objects like as:
  1. List lstStudents = new List();
  2. Student objStudent = new Student();
  3. objStudent.Name = "Rajat";
  4. objStudent.RollNo = 1;
  5. lstStudents.Add(objStudent);
  6. objStudent = new Student();
  7. objStudent.Name = "Sam";
  8. objStudent.RollNo = 2;
  9. lstStudents.Add(objStudent);
  10. //Looping through the list of students
  11. foreach (Student currentSt in lstStudents)
  12. {
  13. //no need to type cast since compiler already knows that everything inside
  14. //this list is a Student
  15. Console.WriteLine("Roll # " + currentSt.RollNo + " " + currentSt.Name);
  16. }

Advantage with Generics

In case of collections you can make fool to compiler but in case of generics you can't make fool to compiler as shown below. Hence Generics provide Type Safety.

Cleaner Code with Generics

Since compiler enforces type safety with Generics. Hence fetching data from Generics doesn't required type casting which means your code is clean and easier to write and maintain.

Better Performance with Generics

As you have seen in above example, at the time of fetching the data from the ArrayList collection we need to do type casting which cause performance degrades. But at the time of fetching the data from the generic List we don't required to do type casting. In this way Generics provide better performance than collections.

virtual, override and new keyword in C#

As you know Polymorphism is the concepts of OOPS which includes method overriding and method overloading. Virtual and Override keyword are used for method overloading and new keyword is used for method hiding. Let's have look on these keywords in C# and try to understand each importance.

Simple Class Inheritance

Consider the below class hierarchy with classes A, B and C. A is the super/base class, B is derived from class A and C is derived from class B.
If a method Test() is declared in the base class A and classes B or C has no methods as shown below.
  1. using System;
  2. namespace Polymorphism
  3. {
  4. class A
  5. {
  6. public void Test() { Console.WriteLine("A::Test()"); }
  7. }
  8.  
  9. class B : A { }
  10.  
  11. class C : B { }
  12.  
  13. class Program
  14. {
  15. static void Main(string[] args)
  16. {
  17. A a = new A();
  18. a.Test(); // output --> "A::Test()"
  19.  
  20. B b = new B();
  21. b.Test(); // output --> "A::Test()"
  22.  
  23. C c = new C();
  24. c.Test(); // output --> "A::Test()"
  25.  
  26. Console.ReadKey();
  27.  
  28. }
  29. }
  30. }
Suppose you have Test() method in all the classes A, B, C as shown below:
  1. using System;
  2. namespace Polymorphism
  3. {
  4. class A
  5. {
  6. public void Test() { Console.WriteLine("A::Test()"); }
  7. }
  8.  
  9. class B : A
  10. {
  11. public void Test() { Console.WriteLine("B::Test()"); }
  12. }
  13.  
  14. class C : B
  15. {
  16. public void Test() { Console.WriteLine("C::Test()"); }
  17. }
  18.  
  19. class Program
  20. {
  21. static void Main(string[] args)
  22. {
  23. A a = new A();
  24. B b = new B();
  25. C c = new C();
  26.  
  27. a.Test(); // output --> "A::Test()"
  28. b.Test(); // output --> "B::Test()"
  29. c.Test(); // output --> "C::Test()"
  30.  
  31. a = new B();
  32. a.Test(); // output --> "A::Test()"
  33.  
  34. b = new C();
  35. b.Test(); // output --> "B::Test()"
  36.  
  37. Console.ReadKey();
  38. }
  39. }
  40. }
When you will run the above program, it will run successfully and gives the O/P. But this program will show the two warnings as shown below:
  1. 'Polymorphism.B.Test()' hides inherited member 'Polymorphism.A.Test()'. Use the new keyword if hiding was intended.
  2. 'Polymorphism.C.Test()' hides inherited member 'Polymorphism.B.Test()'. Use the new keyword if hiding was intended.

Method Hiding (new keyword)

As you have seen in the above example the compiler generate the warnings since C# also supports method hiding. For hiding the base class method from derived class simply declare the derived class method with new keyword. Hence above code can be re-written as :
  1. using System;
  2. namespace Polymorphism
  3. {
  4. class A
  5. {
  6. public void Test() { Console.WriteLine("A::Test()"); }
  7. }
  8.  
  9. class B : A
  10. {
  11. public new void Test() { Console.WriteLine("B::Test()"); }
  12. }
  13.  
  14. class C : B
  15. {
  16. public new void Test() { Console.WriteLine("C::Test()"); }
  17. }
  18.  
  19. class Program
  20. {
  21. static void Main(string[] args)
  22. {
  23. A a = new A();
  24. B b = new B();
  25. C c = new C();
  26.  
  27. a.Test(); // output --> "A::Test()"
  28. b.Test(); // output --> "B::Test()"
  29. c.Test(); // output --> "C::Test()"
  30.  
  31. a = new B();
  32. a.Test(); // output --> "A::Test()"
  33.  
  34. b = new C();
  35. b.Test(); // output --> "B::Test()"
  36.  
  37. Console.ReadKey();
  38. }
  39. }
  40. }
Moreover, if you are expecting the fourth and fifth output should be "B::Foo()" and "C::Foo()" since the objects a and b are referenced by the object of B and C respectively then you have to re-write the above code for Method Overriding.

Method Overriding (virtual and override keyword)

In C#, for overriding the base class method in derived class, you have to declare base class method as virtual and derived class method as override as shown below:
  1. using System;
  2. namespace Polymorphism
  3. {
  4. class A
  5. {
  6. public virtual void Test() { Console.WriteLine("A::Test()"); }
  7. }
  8.  
  9. class B : A
  10. {
  11. public override void Test() { Console.WriteLine("B::Test()"); }
  12. }
  13. class C : B
  14. {
  15. public override void Test() { Console.WriteLine("C::Test()"); }
  16. }
  17. class Program
  18. {
  19. static void Main(string[] args)
  20. {
  21. A a = new A();
  22. B b = new B();
  23. C c = new C();
  24. a.Test(); // output --> "A::Test()"
  25. b.Test(); // output --> "B::Test()"
  26. c.Test(); // output --> "C::Test()"
  27. a = new B();
  28. a.Test(); // output --> "B::Test()"
  29. b = new C();
  30. b.Test(); // output --> "C::Test()"
  31.  
  32. Console.ReadKey();
  33. }
  34. }
  35. }

Mixing Method Overriding and Method Hiding

You can also mix the method hiding and method overriding by using virtual and new keyword since the method of a derived class can be virtual and new at the same time. This is required when you want to further override the derived class method into next level as I am overriding Class B, Test() method in Class C as shown below:
  1. using System;
  2. namespace Polymorphism
  3. {
  4. class A
  5. {
  6. public void Test() { Console.WriteLine("A::Test()"); }
  7. }
  8.  
  9. class B : A
  10. {
  11. public new virtual void Test() { Console.WriteLine("B::Test()"); }
  12. }
  13.  
  14. class C : B
  15. {
  16. public override void Test() { Console.WriteLine("C::Test()"); }
  17. }
  18.  
  19. class Program
  20. {
  21. static void Main(string[] args)
  22. {
  23.  
  24. A a = new A();
  25. B b = new B();
  26. C c = new C();
  27.  
  28. a.Test(); // output --> "A::Test()"
  29. b.Test(); // output --> "B::Test()"
  30. c.Test(); // output --> "C::Test()"
  31.  
  32. a = new B();
  33. a.Test(); // output --> "A::Test()"
  34.  
  35. b = new C();
  36. b.Test(); // output --> "C::Test()"
  37.  
  38. Console.ReadKey();
  39. }
  40. }
  41. }

Note

  1. The virtual keyword is used to modify a method, property, indexer, or event declared in the base class and allow it to be overridden in the derived class.
  2. The override keyword is used to extend or modify a virtual/abstract method, property, indexer, or event of base class into derived class.
  3. The new keyword is used to hide a method, property, indexer, or event of base class into derived class.