Friday, July 31, 2009

Check the login user's windowsprincipal(For example whether role is administrator)

using System;
using System.Security.Principal;


WindowsIdentity wi = WindowsIdentity.GetCurrent();
WindowsPrincipal wp = new WindowsPrincipal(wi);
if (wp.IsInRole(WindowsBuiltInRole.Administrator))
{
//Console.WriteLine("Admin");
Console.WriteLine(WindowsBuiltInRole.Administrator.ToString());
}

Tuesday, July 14, 2009

Understand foreach statement

In order an class support foreach statement, it should support GetEnumerator(), MoveNext(), Reset(), Current() Method.
The interface IEnumerator has the method of MoveNext(), Reset(), Current(), and the interface IEnumerable has the method GetEnumerator().
The ICollection, IList interface are derived from IEnumerable and support GetEnumerator() method.

so,

public class MyClass: ICollection, IEnumerator
{}

MyClass A=new MyClass()

foreach(object a in A)....

So ICollection, IList only will not ensure that your collection class support foreach iteration.

We can write MoveNext(), Reset(), Current() in our custom class to support foreach:

class MyIterator
{
int _count;
public MyIterator(int count)
{
_count=count;
}
public string Current { get { return "Hello World!"; } }
public bool MoveNext()
{
if(_count-- > 0)
return true;
return false;
}
}

Class MyCollection
{
public MyIterator GetEnumerator() { return new MyIterator(3); }
}

class Program
{
static void Main(string[] args)
{
foreach (string value in new MyCollection())
Console.WriteLine(value);
}
}