IEnumerator or IEnumerator

IEnumerator or IEnumerator<T> :
If you call the GetEnumerator method of IEnumerable or IEnumerable<T> interface, you get an iterator object as an IEnumerator reference.
An IEnumerator has the MoveNext, Current, and Reset methods

IEnumerator.Reset() – Sets the enumerator to its initial position, which is before the first element in the collection.
IEnumerator.Current – Gets the current element in the collection.
IEnumerator.MoveNext() – Move the enumerator to the next element of the collection.

Enumerators can be used to read the data in the collection/list, but they cannot be used to modify the underlying collection.
Each instance of an Enumerator is a a certain position and can give you that element,an enumerator remains valid as long as the collection remains unchanged.If changes are made to the collection, such as add, edit,delete of elements, the enumerator is invalidated and the next call to the MoveNext or Reset method throws an InvalidOperationException.

Example :

class Program1
{
public static IEnumerable<int> GetEvenNumbers(int[] numbers)
{
foreach (int item in numbers)
{
if (item % 2 == 0)
yield return (item);
}
}

public static void Main()
{
// Static collection.
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };

// Return IEnumerable with help of Yield
var evenNumbersCol = GetEvenNumbers(numbers);

// Get IEnumerator from IEnumerable
IEnumerator<int> testNumerator = evenNumbersCol.GetEnumerator();

int sampleNumerator = testNumerator.Current;

Console.WriteLine(“Get first value for Numerator ” + sampleNumerator);

// To advance/get the next value using MoveNext()
if (testNumerator.MoveNext())
{
sampleNumerator = testNumerator.Current;
Console.WriteLine(“Next Even Number = ” + sampleNumerator);
}
// Reset() – Sets the enumerator to its initial position, which is before the first element in the collection.
// testNumerator.Reset();

Console.WriteLine(“After Reset of Numerator ” + testNumerator.Current);

Console.ReadLine();
}
}

Output : -
Get first value for Numerator 0
Next Even Number = 2
After Reset of Numerator 2

As per MSDN
The Reset method is provided for COM interoperability. It does not necessarily need to be implemented; instead, the implementer can simply throw a NotSupportedException.
To verify this please uncomment the 3rd last statement testNumerator.Reset();

Ref – System.Collections.IEnumerator
IEnumerator

The Yield Statement

Yield , one of the most powerfull, most ignored feature by developers.I was one of them until I used it. First ,yield is not an operator. yield return and yield break are statements.

In C#, when we are returning an IEnumerable collection from a method, we are allowed to use the yield keyword to transform method into an “iterator block”.

As per MSDN

The yield keyword signals to the compiler that the method in which it appears is an iterator block.  The compiler generates a class to implement the behavior that is expressed in the iterator block.  In the iterator block, the yield keyword is used together with the return keyword to provide a value to the enumerator object.  This is the value that is returned, for example, in each loop of a foreach statement.  The yield keyword is also used with break to signal the end of iteration.

In other words
The yield keyword is used in an iterator block to provide value of enumerator object or to signal the end of the iteration.

yield keyword can be used as:

1)yield return <expression>;
2)yield break;

When used as the expression is evaluated and returned as a value to the enumerator object.Also the expression has to be implicitebly convertible to yield type of the iterator.

When used as break,Yield break control is unconditionally returned to the caller of the iterator in two cases.
One as specified above is MoveNext method of iterator &  Other can be dispose method of enumerator (iterator) object.

public class Program
{
public static IEnumerable GetEvenNumbers(int[] numbers)
{
foreach (int item in numbers)
{
if (item % 2 == 0)
yield return (item);
}
}
public static IEnumerableGetFirstEvenNumber(int[] numbers)
{
foreach (int item in numbers)
{
if (item % 2 == 0)
{
yield return (item);
yield break;
}
}
//This Loop , will not get called.
foreach (int item in numbers)
{
if (item % 2 == 1)
yield return item;}
}


public static void Main()
{
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };


// Yield Return  – Example Call Start
var evenNumbersCol = GetEvenNumbers(numbers);
foreach (int x in evenNumbersCol)
{
Console.WriteLine(x);
}
// Yield Return  – Example Call End


// Yield Break – Example Call Start
var firstEvenNumber = GetFirstEvenNumber(numbers);
foreach (int x in firstEvenNumber)
{
Console.WriteLine(“First Even Number = ” + x.ToString());
}
// Yield Break – Example Call End
Console.ReadLine();
}

In the Program sample above , I mentioned the example call for both Yield Return & Yield Break

The program will return Even numbers.
The Collection evenNumbersCol/firstEvenNumber is empty before it is been accessed in foreach.The methods are getting called actuallly when any of iterator methods getting called or when looped through in other words when used to return items from a loop within a method ( return type IEnumerable) and retain the state of the method through multiple calls.This saves the memory by preventing fully populating large collection of items

Yield Return:
When used as the expression is evaluated and returned as a value to the enumerator object.”The expression has to be implicitebly convertible to yield type of the iterator.” means return type of yield must match to IEnumerable, in our above case int

Yield Break:
When used as break,Yield break control is unconditionally returned to the caller of the iterator in two cases. One as specified above is Move next method of iterator ( i.e. Looping through as we discussed above) &  Other can be dispose method of enumerator (iterator) object.Also yield break can be seen as return statement which does not return value.
If you are inside this loop want to abort the iteration and return as soon as first even number found , you can do this with help of the yield break. The yield break will return from the method directly instead of the current loop in other words second loop will never get executed here

As per MSDN Yield have following restrictions

The yield statement can only appear inside an iterator block, which can be implemented as the body of a method, operator, or accessor. The body of such methods, operators, or accessors is controlled by the following restrictions:


1) Unsafe blocks are not allowed.
2) Parameters to the method, operator, or accessor cannot be ref or out.
3) A yield return statement cannot be located anywhere inside a try-catch block.
It can be located in a try block if the try block is followed by a finally block.
4) A yield break statement may be located in a try block or a catch block but not a finally block.
5) A yield statement cannot appear in an anonymous method.
6) When used with expression, a yield return statement cannot appear in a catch block or in a try block that has one or more catch clauses.

Jquery – Getting QueryString Parameters’ Value

Getting Values from Querystring parameter is quite easy using Jquery

e.g if the below mentioned is url with querystring

http://localhost/CreateQryString.aspx?Node1=9000%20&Node2=3000

var url = window.location.href;
var Node1= null;
var Node2= null;

if (url.indexOf(‘?Node1=’) != -1)
{

Node1= $.query.get(‘Node1’);
 Node2= $.query.get(‘Node2′);

}

In the above code window.location.href  is Javascript property of DOM window object allows us to get or set the current URL. We can access the href property through location.href or window.location.href

For $.query.get()  function  You need to add following Jquery script references

<script type=”text/javascript” src=”jquery.query-2.1.7.js”></script>

<script type=”text/javascript” src=”jquery.rc4.js”></script>

Jquery : Create Expandable text box/ DIV areas

Recently I had one requirement, where I wanted to create the following functionality on an asp.net page.  If a block of text is too long I want to truncate the text at 300 characters and display a “more” link.  When the “more” link is clicked the original block of text should be displayed.

For Example my criteria was as followed

After clicking on more link/button:

I used JQuery Component for this, using 2 functions involved.

My code modules as follows

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js”></script>

<script src=”http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js”></script>

<script type=”text/javascript”

src=”http://ajax.googleapis.com/02 ajax/libs/jquery/1.4.2/jquery.min.js”></script>

<script type=”text/javascript”>

$(function() {

var finalText = $(‘#divBlock’).text();

// Pass control of the text block for limiting the number of chars

LimidDivText(‘#divBlock’,300);

// Expand on click of more link, pass both text block and link here

LinkExpand(‘#divBlock’,'#lnkMore’,finalText);

function LinkExpand(divBlock,lnkControl,finalText) {

$(lnkControl).live(“click”, function() {

$(divBlock).slideDown(“fast”);

$(divBlock).html(finalText);

});

};

function LimidDivText(divBlock,maxLimit) {

var validLength = $(divBlock).text().length – maxLimit;

if(validLength > 0)

{

$(divBlock).html($(divBlock).text().substring(0,maxLimit)).

append(‘ <a id=”lnkMore” href=”#”>more</a>’);

}

};

});

</script>

Jquery : Getting RadioButtonlist value using Jquery

We can get value of checked RadioButtonlist item using Jquery as mentioned below.

$(‘input[type=radio][id*=radioButtonList]:checked’).val()

Jquery : Setting Dropdownlist value using Jquery

We can set Dropdownlist Value using Jquery as mentioned below.

if we are having dropdownlist as follows

<asp:DropDownList runat=”server” ID=”ddlDropDownList“>
<asp:ListItem Text=”<– Select –>” Value=”0″></asp:ListItem>
<asp:ListItem Text=”TEST1″ Value=”1″></asp:ListItem>
<asp:ListItem Text=”TEST2″ Value=”2″></asp:ListItem>
<asp:ListItem Text=”TEST3″ Value=”3″></asp:ListItem>
</asp:DropDownList>

THEN ,we can set selection of the dropdown list to “<– Select –>”  when we required or after processing done as below.

$(“select[id$=ddlDropDownList]“).val(“0″);

Set Selected Value for DropdownList on Clientside using Javascript

Sometimes we need show the dropdownlist control with some selected value after some activity ( without server postback ) on the web page.
we can do that on clientside with the help of javascript.

function SetSelectedIndex(dropdownlist,sVal)
{
var a = document.getElementById(dropdownlist);

for(i=0;i<a.length;i++)
{
if(a.options[i].value == sVal)
{
a.selectedIndex = i;
}

}

}

Call the above function on your required event i.e. onclick,onblur etc… from code behind.

SetSelectedIndex(‘<%=ddldropdownlistName.ClientID %>’,”ValueToBeSelected”)

The handle is invalid. (Exception from HRESULT: 0×80070006 (E_HANDLE))

Recently while working on asp.net application , I got following exception

Server Error in ‘/’ Application.
——————————————————————————–

The handle is invalid. (Exception from HRESULT: 0×80070006 (E_HANDLE))
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Runtime.InteropServices.COMException: The handle is invalid. (Exception from HRESULT: 0×80070006 (E_HANDLE))

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[COMException (0x80070006): The handle is invalid. (Exception from HRESULT: 0x80070006 (E_HANDLE))]

[FileLoadException: Could not load file or assembly 'SMDiagnostics, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The handle is invalid. (Exception from HRESULT: 0x80070006 (E_HANDLE))]

System.ServiceModel.Activation.HttpModule.ProcessRequest(Object sender, EventArgs e) +0
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +60
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +86

After much much of the time , I came to conclusion that following steps can able to solve the problem fast , at least it done the same for me.

First of all check –
Check if the assembly reference added under <assemblies> of Web.config
<add assembly=”SMDiagnostics, Version=3.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089″ />

Then

Verify if the file  SMDiagnostics.dll exists in the folder at location:
C:\windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation

Also Verify if the assembly is registered into the GAC :
C:\Windows\Assembly

If the file is there in GAC you can able to see                                                                                                                                   ‘SMDiagnostics, Version=3.0.0.0, Culture=neutral,  PublicKeyToken=b77a5c561934e089′ in the list

If the answer for any of the two questions is no, then .Net framework WCF component may not be installed successfully on the machine. Please try reinstalling it.

If still you are not able to solve the exception,Check if your solution is referring to the any External Dll ,
which is not getting loaded due to some reason and eventually raising the exception.

This was exactly the same case with me.

I was using one COM component funcationality which was placed in dll , which is placed under BIN folder and
was using/accessing  the functions from COM in App_code  business code files. and path was mentioned in Web.config as Key like
<add key=”FuncPath” value=”C:\Inetpub\wwwroot\XYZ\APPLICATION\Bin\”></add>
and as the files in the BIN are not getting loaded , it was giving me the error.

After some following the issue for more than 3-4 hours of try and error  I found the reason that Under IIS , for Virtual Directory Properties Execution Permissions were marked as “Scripts and Executables” the dll is not being loaded and I was getting “System.Runtime.InteropServices.COMException”

After changing Execution Permissions to “Scripts Only” and applying it. it was started working fine.

I dont know the any special difference other than

Scripts only Run only scripts,such as ASP applications  and
Scripts and Executables Run both scripts, such as ASP applications, and executables

Although my problem is solved, I am still searching for difference… Anyone Please ……

DataBinding: ‘System.Data.DataRowView’ does not contain a property with the name due to “.” / Period in ColumnName

Recently I met up with error “DataBinding: ‘System.Data.DataRowView’ does not contain a property with the name”,  on page with dynamically generated Gridview on it.Error was coming at the runtime at timing of binding  the data.

I first checked for the columns in the dataset before binding to Gridview , all the columns are properly generated. then I started looking for the code which is generating gridview on fly. I was using following event to bind the data dynamically

protected void ValueDataBinding(object sender, EventArgs e)
{
object bound_value_obj = null;
Control ctrl = (Control)sender;
IDataItemContainer data_item_container = (IDataItemContainer)ctrl.NamingContainer;

bound_value_obj = DataBinder.Eval(data_item_container.DataItem, ColumnName); ( Exception was thown from above line while binding to column)

}

after much of debugging I found that ColumnName is  “Others…” and error was coming due to “.” / Period in ColumnName , the reason behind is  DataBinder.Eval Method Uses reflection to parse and evaluate a data-binding expression against an object at run time , so “.” can be treated with different , I havnt tried but I am sure it will throw the exception for other special chars also i.e. ;  , : ” ‘  etc.

This was solved by using

bound_value_obj =  DataBinder.GetPropertyValue(data_item_container.DataItem, ColumnName).ToString();


Setting css style programmatically in Asp.Net/C#

Sometimes we have requirements such a way that we need to change the elements and accordingly style dynamically under  div.

Suppose in one case  we need our div to be of width-size 800px and and can scroll if goes beyond.

for that on the front-end side (aspx) create <div id=”dvDStyle” runat=”server”>  </div>

then in code-behind  ( cs file) mention style using either of the way

1st one is mention it as Attribute for dvDStyle

2nd is mention style as separate property like Key,Value pair.

dvDStyle.Attributes.Add(“style”, “width:800px; overflow:scroll;”);

or

dvDStyle.Style["width"] = “800px”;
dvDStyle.Style["overflow"] =”scroll”;