Pages

Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Friday, May 18, 2012

Get details from Active Directory


The System.DirectoryServices namespace provided classes for access to Active Directory (AD) and allowed us to perform different operations on AD. But it required the knowledge of the AD structure and Principal Store.

In .Net framework 3.5, Microsoft introduced the System.DirectoryServices.AccountManagement namespace that provides uniform access and manipulation of user, computer, and group security principals across the multiple principal stores: Active Directory Domain Services (AD DS), Active Directory Lightweight Directory Services (AD LDS), and Machine SAM (MSAM).

System.DirectoryServices.AccountManagement manages directory objects independent of the System.DirectoryServices namespace and does not require knowledge of Principal Store.

Managed directory services applications can take advantage of the AccountManagement API to simplify management of user, computer and group principals. Solutions that previously required intricate knowledge of the store or lengthy code, such as finding all groups to which a user belongs, are accomplished in a few lines of code with theAccountManagement API.

Sample code to get the details of Group and Users is shown below:




 public class ADUtility
 {
    private string domain = string.Empty;
    public ADUtility(string domain)
    {
       this.domain = domain;
    }
    
    private PrincipalContext GetPrincipalContext()
    {
       PrincipalContext oPrincipalContext = 
                        new PrincipalContext(ContextType.Domain, domain);

       return oPrincipalContext;
    }

    public GroupPrincipal GetGroup(string groupName)
    {
       PrincipalContext oPrincipalContext = GetPrincipalContext();
       GroupPrincipal groupPrincipal = 
                      GroupPrincipal.FindByIdentity(oPrincipalContext, groupName);
       
       return groupPrincipal;
    }

    public UserPrincipal GetUser(string userName)
    {
        PrincipalContext oPrincipalContext = GetPrincipalContext();
        UserPrincipal oUserPrincipal = 
                      UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);

        return oUserPrincipal;
    }
 }

Thursday, March 15, 2012

DescriptionAttribute for Enums in C#

Enums provides an efficient way to define a set of named constants that may be assigned to a variable. In C# they can be only number based and have usual naming limitation of not allowing special characters or spaces. Many times we have a requirement where we need to have display user friendly name for Enum value on screen.
public enum ProjectPhase
{
    RequirementsGathering = 1,
    AnalysisDesign = 2,
}
In the above example we need to display more meaningful values on screen. This can be achieved by using the System.ComponentModel and System.Reflection namespace.

Step 1: Use the DescriptionAttribute class to provide the friendly name for enum values.
using System.ComponentModel;
public enum ProjectPhase
{
    [Description("Requirements Gathering")]
     RequirementsGathering = 1,
    [Description("Analysis and Design")]
     AnalysisDesign = 1,
}

Step 2: Create an static class which contains an extension method that extends the Enum type. This extension method GetDecription returns the description of the provided enum value. If there is no description attribute applied on the enum value then the string representation of the enum value is returned.
public static class EnumExtensions
{
    public static string GetDescription(this Enum value)
    {
        string description = string.Empty;
        FieldInfo field = value.GetType().GetField(value.ToString());
        DescriptionAttribute[] attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false);
        if (attributes.Length > 0)
            description = attributes[0].Description;
        else
             description = value.ToString();
        return description;
     }
}

Step 3: Accessing the Description of enum value
Console.WriteLine(ProjectPhase.Code.GetDescription());

Friday, November 11, 2011

How to calculate the Linest of given numbers


Linest function in excel returns a table of statistics for a straight line that best fits a data set.

The C# code for getting the linest of numbers is given below:

public static double CalculateLinest(double[] y, double[] x)
{
   double linest = 0;
   if (y.Length == x.Length)
   {
      double avgY = y.Average();
      double avgX = x.Average();
      double[] dividend = new double[y.Length];
      double[] divisor = new double[y.Length];
      for (int i = 0; i < y.Length; i++)
      {
         dividend[i] = (x[i] - avgX) * (y[i] - avgY);
         divisor[i] = Math.Pow((x[i] - avgX), 2);
      }
      linest = dividend.Sum() / divisor.Sum();
   }
   return linest;
}

Wednesday, May 25, 2011

How to calculate standard deviation of given numbers

The standard deviation of numbers is calculated as below:





The C# code to calculate the standard deviation is given below:

public double CalculateStandardDeviation(double?[] numbers)
{
   // select only non null numbers from the input array
   numbers = numbers.Where(n => n.HasValue).ToArray(); 

   // square of sum of numbers
   double sqrOfSum = Math.Pow(numbers.Sum().Value,2); 

   // sum of squares of numbers
   double sumOfSqrs = numbers.Sum(n => Math.Pow(n.Value, 2));

   // number of values in set
   double count = (double)numbers.Length; 

   // calculates the dividend part of formula
   double dividend = (count * sumOfSqrs) - sqrOfSum; 

   // returns standard deviation
   return Math.Sqrt(dividend / (count * (count - 1)));
}