How IDisposable works in .NET?

IDisposable

                MSDN Says – Provides a mechanism for releasing unmanaged resources .

                 IDisposable doesn’t only apply when you are using a come DLL. If you create an instance of a class which Implement IDisposable then you should actively manage the life time of that object.
Here is the class which implement IDisposable
1

 

 

 

 

If I want to use the instance of this class temporarily, I should declare it in using block like below

2

 

 

 

 

Using is a C# construct that the compiler actually renders as a try finally block calling dispose on the object in the finally. So the using code is functionally prevalent to creating the object using it and calling dispose. Depending on the situation that may mean the resources take longer to clean up as they wait for the next Garbage Collection event or object may retain references to those resources. So the object may never be released and so you app exits or throws OutOfMemory exception.

Using and Disposing SqlConnection

class Program
{
static void Main(string[] args)
{
using (var databaseState = new DatabaseState())
{
string date = databaseState.GetCurrentDate();
Console.WriteLine(date);
}
Console.ReadKey();
}
}
public class DatabaseState:IDisposable
{
private SqlConnection _connection;
public string GetCurrentDate()
{
if(_connection==null)
{
_connection =
new SqlConnection(@"Data Source=JAMEELM\SQL2012DEV;Initial Catalog= SampleDb;Integrated Security=True");
_connection.Open();
}
using (SqlCommand command=_connection.CreateCommand())
{
command.CommandText = "Select getdate()";
return command.ExecuteScalar().ToString();
}
}
public void Dispose()
{
Console.WriteLine("Disposing SqlConnection :{0}", _connection.GetHashCode());
_connection.Close();
_connection.Dispose();
}
}

When we run this program we get the output as date from the server also I have wrote a line of code which displays the hashcode of SqlConnection object. The hashcode will be different, each time we run the program because each time it will create a new SqlConnection object.

3

 

 

Again I am going to run this program by changing the code littile bit by adding the using statements inside a loop

for (int i = 0; i < 1000; i++)
{
using (var databaseState = new DatabaseState())
{
string date = databaseState.GetCurrentDate();
Console.WriteLine(date);
}
}

Every time the using block run, it will create a new SqlConnection and Dispose it.

4

 

 

 

 

 

 

 

 

 
Not Disposing SqlConnection
Change the previous code little bit by removing the using statement

for (int i = 0; i< 1000; i++)
{
var databaseState = new DatabaseState();
string date = databaseState.GetCurrentDate();
Console.WriteLine(date);
}

When we run the program we will get an unhandled exception after creating some SqlConnection objects

5

 

 

 

 

The exception is a time out from trying to connect SqlServer because all the connection in the connection pool are already being used. Inside the loop it creates connection but never dispose it. It will happen whether are no free connection in the pool and we get the error.

We can also specify the Max pool size and connection timeout in Sql connection string arbitrarily

_connection =
new SqlConnection(
@"Data Source=JAMEELM\SQL2012DEV;Initial Catalog=SampleDb;Integrated Security=True;App=Sample;Max pool size=215;Connection Timeout=2");

Enjoy Programming..

Alternative string concatenation of a two string in C#

public static string GetString(string string1,string string2)
{
char[] str1 = string1.ToCharArray();
char[] str2 = string2.ToCharArray();

string finalString = “”;
int length = str1.Length > str2.Length ? str2.Length : str1.Length;
for (int i = 0; i < length ; i++)
{
finalString = finalString + str1[i] + str2[i];
}
if (str1.Length > str2.Length)
{
int difference = str1.Length – str2.Length;
for (int i = 0; i < difference; i++)
{
char rem = str1[str2.Length + i];
finalString = finalString + rem;
}

}
else
{
int difference = str2.Length – str1.Length;
for (int i = 0; i < difference; i++)
{
char rem = str2[str1.Length + i];
finalString = finalString + rem;
}
}
return finalString;
}

string finalString = GetString(“USA”, “INDIA”);

Ouput : UISNADIA

Split numbers at nth occurrence in C#

class Program
{
static void Main(string[] args)
{

var finalResult = GetSplittedNumbers("1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30",10);
}
public static List<string> GetSplittedNumbers(string stringSeparatedByComma,int n)
{
var listOfSeparatedValues = new List<string>();
List<int> splittedIntArrays =
stringSeparatedByComma.Split(',').Select(
x => Convert.ToInt32(x)).ToList();
var splittedList = new List<int>();
foreach (int item in splittedIntArrays)
{

int status = item % n;
if (splittedList == null)
{
splittedList = new List<int>();
}

splittedList.Add(item);

if (status == 0)
{

string res = AgainCommaSeparated(splittedList);
listOfSeparatedValues.Add(res);
splittedList = null;
}
}
return listOfSeparatedValues;
}
private static string AgainCommaSeparated(IEnumerable<int> numbers )
{
var result= numbers.Aggregate("", (current, number) => current + number.ToString() + ",");
return result.Substring(0, result.Length - 1);
}
}

Dynamic Object in CSharp Example

In the previous article you had go through about ExpandoObject. DynamicObject is powerful than the ExpandoObject. Let us look at the below example similar to the previous article.

dynamic docXml=new DynamicXml("PersonDetails.xml");
foreach (var person in docXml.Persons)
{
Console.WriteLine(person.FirstName);
}

public class DynamicXml:DynamicObject,IEnumerable
{
private dynamic _xml;
public DynamicXml(string fileName)
{
_xml = XDocument.Load(fileName);
}
public DynamicXml(dynamic xml)
{
_xml = xml;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
var xml = _xml.Element(binder.Name);
if(xml!=null)
{
result = new DynamicXml(xml);
return true;
}
result = null;
return false;
}
public IEnumerator GetEnumerator()
{
foreach (var child in _xml.Elements())
{
yield return new DynamicXml(child);
}
}
public static implicit operator string (DynamicXml xml)
{
return xml._xml.Value;
}
}

Enjoy Programming…

Practical Use of Expando Object in CSharp

I am going to parse the below Person information in a XML file and Pull out the FirstName of each employee. There is a couple of way to do this .One way is by using Linq To XML like below

<?xml version="1.0" encoding="utf-8" ?>
<Persons>
<Person>
<FirstName>Jameel</FirstName>
</Person>
<Person>
<FirstName>Sreeraj</FirstName>
</Person>
<Person>
<FirstName>Vinayan</FirstName>
</Person>
<Person>
<FirstName>Anuraj</FirstName>
</Person>
<Person>
<FirstName>Niju</FirstName>
</Person>
</Persons>


private static void Main(string[] args)
{
var document = XDocument.Load("PersonDetails.xml");
var xElement = document.Element("Persons");
if (xElement != null)
foreach (var item in xElement.Elements("Person"))
{
var element = item.Element("FirstName");
if (element != null) Console.WriteLine(element.Value);
}
}

But it is little bit cluttered code. Let us try this same thing by using expando

var doc = XDocument.Load("PersonDetails.xml").AsExpando();
foreach (var person in doc.Persons)
{
Console.WriteLine(person.FirstName);
}

AsExpando is an extension method which create object graphs based on XDocument elements.You can reuse this method in this scenarios.

public static  class ExpandoXml
{
public static dynamic AsExpando(this XDocument xDocument)
{
return CreateExpando(xDocument.Root);
}


private static dynamic CreateExpando(XElement xElement)
{
var result = new System.Dynamic.ExpandoObject() as IDictionary<string, object>;
if(xElement.Elements().Any(x=>x.HasElements))
{
var list = new List<System.Dynamic.ExpandoObject>();
result.Add(xElement.Name.ToString(),list);
foreach (var childElement in xElement.Elements())
{
list.Add(CreateExpando(childElement));
}
}
else
{
foreach (var leafElement in xElement.Elements())
{
result.Add(leafElement.Name.ToString(),leafElement.Value);
}
}
return result;
}
}

Enjoy Programming..

Expando Object in CSharp

Expando Object

Once you create an instance of an Expando Object which is in the System.Dynamic namespace   then you have ability to arbitrarily add things to these object.

In the below code snippets I have create a new instance of ExpandoObject and add one property and method and then invoke that method.

dynamic expando = new System.Dynamic.ExpandoObject();
expando.Name = "Jameel";
expando.Display = new Action(() => Console.WriteLine(expando.Name));
expando.Display();

Output : Jameel

Enjoy Programming…

Dynamic Language Runtime Overview

Introduction

The DLR was created by Microsoft not only to support dynamic features in the main stream CLR languages but also to support new languages like Ruby and Python running on CLR running efficiently and effectively. DLR sit on the top of CLR and provide features these dynamic languages need like Call Site Caching. Call Site is the place you are performing some operations on a dynamic object. The DLR also supports other keywords such as Expando Object and Dynamic Object. This allows some interesting dynamic features n C#.

DLR

Enjoy Programming…

 

Dynamic Keyword Example of Excel Automation In CSharp – DEMO2

Let me show you another great use of dynamic keyword for COM interop. If you done any automation of Microsoft office application in the past then probably you familiar of adding COM assembly in to your project. I am going to do this without adding the assembly using dynamic.

class Program
{
static void Main(string[] args)
{
Type excelType = Type.GetTypeFromProgID("Excel.Application");
dynamic excel = Activator.CreateInstance(excelType);
excel.Visible = true;
excel.Workbooks.Add();
dynamic sheet = excel.ActiveSheet;
Process[] processes = Process.GetProcesses();
for (int i = 0; i < processes.Length; i++)
{
sheet.Cells[i + 1, "A"] = processes[i].ProcessName;
sheet.Cells[i + 1, "b"] = processes[i].Threads.Count;
}
}
}

It will open an excel file with all Process Name and Threads Count

Capture

 

dynamic keyword example in CSharp – Demo1

Inside Console Application we have an Employee class defined with FirstName property and a method called Display().

public class Employee
{
public string FirstName { get; set; }
public void Display()
{
Console.WriteLine("Hi, my name is {0}",FirstName);
}
}

Inside the Program imagine I am calling a method called GetName() which return an object

class Program
{
static void Main(string[] args)
{
}
public static object GetName()
{
return new Employee {FirstName = "Jameel"};
}
}

Then I am going to assign this method to an object in the main method

static void Main(string[] args)
{
object o = GetName();
}

How can I invoke the Display () method?
One way is call like below

Employee employee = GetName() as Employee;
employee.Display();

What we do when we don’t know the type of Display() method?
Ofcourse we can use reflection

object o = GetName();
o.GetType().GetMethod("Display").Invoke(o, null);

Dynamic typed variable could give the same result with less code.Note that C# and Visual Studio doesn’t give the intellisense.In compile time Compiler doesn’t know about the Display() method only runtime can understand it.

dynamic o = GetName();
o.Display();

Create one more class library by right clicking the solution and create a new class library project named Animals and add a new class named Animal with an method called Display()

public class Animal
{
public void Display()
{
Console.WriteLine("Elephant");
}
}

Our previous Console mode application don’t know about this because we not add the reference to this project. So that compiler doesn’t know about this assembly.
We can also the Display() method by dynamically loading this assembly.

Type animalType = Assembly.Load("Animals").GetType("Animal");
dynamic animal = Activator.CreateInstance(animalType);
animal.Display();

dynamic keyword help us to remove type casting from our code, reflection codes GetMember(),GetType() and GetProperty() and the Invoke method that try to set and get things. All of these things clean up with the dynamic keyword.

Enjoy Reading…

dynamic keyword in CSharp

Many of us like static type checking in C# because compiler can find early. But static type checking does for strict the way of write some code .You have to have type definition and metadata available at compile time in order to get work done. Before C# 4.0 it is impossible to interact with the dynamic languages such as Ruby and Python . There are also difficult in some scenarios like to work with COM objects. Anyone who trying to interop from C# code to legacy code In COM often pain . Perhaps you have felt some issues while interacting with Microsoft Office COM components to automate Word or Excel. In C# 4.0 Microsoft introduces a new keyword called dynamic. A dynamic variable is a statically typed variable is a dynamic variable. When C# compiler see the dynamically typed variable it turns off compile time check. Any operation to perform on a dynamic object reference by that variable like calling a method , setting up a property all will resolve at runtime.
dynamic person=new Person();
person.Name=”Jameel”;