Which group(s) am I in?
If you are working in an Active Directory environment and you do utilize it for authentication in your project, this snippet might come handy. It lists the group(s) that current authenticated user belongs to, so you can expand on this to do whatever you need to.
using System.Security.Principal; //do this to save time in typing foreach (IdentityReference ref in WindowsIdentity.GetCurrent().Groups) //get current user group(s) Console.WriteLine(ref.Translate(typeof(NTAccount)).ToString()); //translate it to meaningful value
C# Generic Comparer
This morning I ran into a situation where i need to sort an array of ServiceController before binding into a combobox. So I looked around and I found Array.Sort (or List
private class ServiceControllerSort : IComparer<ServiceController> { public int Compare(ServiceController x, ServiceController y) { return string.Compare(x.DisplayName, y.DisplayName, true); } }
Now what? What if next time I want to sort on my ExtendedServiceController class (as if there is necessity to do one)? I will have more and more IComparer implementations. I decided to explore further and this page says it all. Took the code, clean it up and woots, I have a generic comparison class that is usable for almost all types.
/// <summary> /// Custom sorter based on property /// </summary> /// <typeparam name="T">Target Type</typeparam> public class ExtSortComparer<T>: IComparer<T> { private ListSortDirection _sortDirection = ListSortDirection.Ascending; private PropertyDescriptor _targetPropDescriptor; /// <summary> /// Constructor /// </summary> public ExtSortComparer() { } /// <summary> /// Constructor /// </summary> /// <param name="PropertyName">Name of property to sort on. Case sensitive.</param> public ExtSortComparer(string PropertyName) { _targetPropDescriptor = TypeDescriptor.GetProperties(typeof(T))[PropertyName]; } /// <summary> /// Constructor /// </summary> /// <param name="PropertyName">Name of property to sort on. Case sensitive.</param> /// <param name="SortDirection">Sort direction</param> public ExtSortComparer(string PropertyName, ListSortDirection SortDirection) : this(PropertyName) { _sortDirection = SortDirection; } /// <summary> /// Constructor /// </summary> /// <param name="TargetProperty">Descriptor of property to sort on</param> public ExtSortComparer(PropertyDescriptor TargetProperty) { _targetPropDescriptor = TargetProperty; } /// <summary> /// Constructor /// </summary> /// <param name="TargetProperty">Descriptor of property to sort on</param> /// <param name="SortDirection">Sort direction</param> public ExtSortComparer(PropertyDescriptor TargetProperty, ListSortDirection SortDirection) { _targetPropDescriptor = TargetProperty; _sortDirection = SortDirection; } /// <summary> /// Compare two given object /// </summary> /// <param name="x">Object A</param> /// <param name="y">Object B</param> /// <returns>Result of comparison</returns> public int Compare(T x, T y) { //ensure there is proper property description if (_targetPropDescriptor != null) { int intRetValue = _CompareValues(_targetPropDescriptor.GetValue(x), _targetPropDescriptor.GetValue(y)); //reverse the sorting if descending if (_sortDirection == ListSortDirection.Descending) return intRetValue * -1; return intRetValue; //return the result } return 0; //return neutral if insufficient information to sort } /// <summary> /// Compare values of target property /// </summary> /// <param name="ValueX">Value of property (Object A)</param> /// <param name="ValueY">Value of property (Object B)</param> /// <returns>Result of comparison</returns> private int _CompareValues(object ValueX, object ValueY) { if (ValueX is IComparable) //if X can be compared return ((IComparable)ValueX).CompareTo(ValueY); if (ValueY is IComparable) //else if Y can be compared return ((IComparable)ValueY).CompareTo(ValueX); //when both can't be compared, resort to string value. return ValueX.ToString().CompareTo(ValueY.ToString()); } }
The comments should explain what is happening internally. Another good addition to my common library! If you have any thoughts, shoot!
C# Generic Constraints
Generic is a new wonder in .NET with the flexiblity it introduces to coders. But when you wish to explore further, you might face the limitation of only able to work with Object capabilities. This is because generic doesn't know your type details, and since all types are Object, so you only have Object to play with. To overcome this, we have Where keyword in C# (VB.net has As, i think). Apart from be able to constraint the types that generic accept, it also allows you to use the constraints capabilities.
Generics support few types of constraints:
- Interface: Allow only types that implement specific interfaces to use your generic.
- Class/Base class: Allow only types that match or inherit from a specific base class to use your generic.
- Constructor: Require types that use your generic to implement a parameterless constructor.
Say you have a custom Interface as below
public interface IMyCustomOne
{
string WhatsMyName();
}
and a generic method
public bool CheckNameEqualJohn<T>()
{
return (T.WhatsMyName == "John");
}
Compiler will throw you at the instant you try to build.
To solve this, we add Where at the end
public bool CheckNameEqualJohn<T>() where T : IMyCustomOne
{
return (T.WhatsMyName == "John");
}
Woots, compiler is now happy! The obstacle has been removed and off you go to maximize your creativity. If you need 2 constraints, how to go about it?
public class MyClass<T,U>
where T : IMyCustomT
where U : IMyCustomU
{
//....
}
Some additional jargons about this constraint that will make you look cooler in front of your peers
Unbound Type Parameter
Basically this refers to the most basic way of us using generic
public class MyClass<T>
{
//....
}
Naked Type Constraint
When a generic type parameter is used as constraint
public class MyClass<T>
{
public void MethodOne<U>(U param) where U : T
{
//....
}
}
Happy Generic'ing!
Better comparison with enumeration
Suppose you have an enum list and a variable which value comes from external source. What do you usually do to compare against the enum list?
If (MyValue == "3") { //3 means ok, do some stuff }
What if one day you decide that you don't like 3 (for whatever reason) and change it to 30? You will have to find and replace the repeated value all over your project. Yes, you have the FindAndReplace function with most IDE, but holy cow, you only realize that the last couple of 3 meant something else!
So a safer way is to cast the value into appropriate enum for comparison or any other operation.
'VB.NET
dim myEnumValue as TheEnum = CType([Enum].Parse(GetType(TheEnum), _
tempValue.ToString()), TheEnum)
If myEnumValue = TheEnum.NumberThree Then
'..
End If
//C#
TheEnum myEnumValue = (TheEnum)Enum.Parse(typeof(TheEnum), tempValue);
if (myEnumValue == TheEnum.NumberThree) { //.. }
"Hey, that looks useful. I want it in my SuperCoolReusable library" you might say. With the power of Generic, we can put it into a common call.
'VB.NET
Public Shared Function ParseEnum(Of T)(ByVal Value As Object) As T
Return CType([Enum].Parse(GetType(T), Value.ToString()), T)
End Function
//C#
public static ReturnType ConvertStringToEnum<ReturnType>(string Value)
{
return (ReturnType)Enum.Parse(typeof(ReturnType), Value);
}
Another simple yet useful tip!
I Learned and Applied RegularExpression Today
Scenario: I have a number of patterns that I need to check and replace in a string. I don't want to transverse the string and play with characters and length. What other option I have?
I want the library FAST!
My MSDN 2008 Library didn't install a direct link to launch help like the 2005 version. So i tweaked the 2005 shortcut and hoila, i have the shortcut for 2008 version. You like the F1, but i prefer this so i can easily answer people's query without opening the IDE
Create a new Shortcut and put this in the shortcut path (single line):
"%YOUR PROGRAM FILES%\Common Files\Microsoft Shared\Help 9\dexplore.exe"
/helpcol ms-help://MS.MSDNQTR.v90.en /LaunchNamedUrlTopic DefaultPage
coalescing null yield return
Ok the title means nothing at all, and they are not related too, except that they both are of C# family. As requested by Klaw, i am going to blog about it so that we all learn
Coalescing Null Operator
You are probably thinking what's that. Maybe it is just me, but it is one of the cool subtle features in C# that I just discovered today. Shame on me ya. Basically you all are familiar with this:
string myStrVarB = (myStrVarA == null) ? "null string" : myStrVarA
So with coalescing null operator (??), you can shortened it to:
string myStrVarB = myStrVarA ?? "null string"
Let's see, that is saving of 17 characters. Your boss sure will praise you for that
On a side note, in case you don't know, you can allow a scalar type to be null by using the nullable operator:
int? myInteger = null
yield return
Definition from MSDN: "Used in an iterator block to provide a value to the enumerator object or to signal the end of iteration". I assume you have previous knowledge with IEnumerable (or iterator), so i am not going into detail with it. The yield statement appears only inside an iterator block and returns the value that is expected by the calling foreach statement. Cut the theory and show me the example.
public static IEnumerable Power(int number, int exponent)
{
int counter = 0;
int result = 1;
while (counter++ < exponent)
{
result = result * number;
yield return result;
}
}
static void Main()
{
// Display powers of 2 up to the exponent 8:
foreach (int i in Power(2, 8))
{
Console.Write("{0} ", i);
}
}
There you go, another simple bit of my learning
Begin Invoke..End Invoke
First post in the category
This group is mainly to share coding stuff that is out of layman term. If you are not programmer, stay away at all cost!
Found this very easy to read yet informative post on Asynchronous Method Invocation. I admit that what i know about .NET is merely the tiny tip of what the iceberg can offer. Oh hell, life is long and learning is life long, ain't it?
Here's a summary of what i learnt:
- MethodInvoke - built in delegate in .NET that allow you to call a method that takes in no parameter
- BeginInvoke - execute the target function and return to caller instantly
- ThreadPool in .NET has a limit of 25. Avoid 'starving' the pool else be fined by performance loss
- EndInvoke - return proper values/parameters from the previous function call
- IAsyncResult - log of all datas (exceptions, return value, output parameters, etc) after execution is completed
- AsyncCallBack - used when you don't wish to wait for completion of the execution (that's the purpose of asynchronous call bah)
- Command Pattern (ICommand interface) - rather than BeginInvoke, EndInvoke, CallBack everywhere in your Main(), apply this pattern to group calls together.
That's all folks. I might not have explained everything properly, so best for you to read it yourself.