Search This Blog

Monday, September 26, 2011

DataView RowFilter

DataView RowFilter Syntax [C#]

This example describes syntax of DataView.RowFil¬ter expression.
It shows how to correctly build expression string (without „SQL injection“)
using
methods to escape values.

Column names

If a column name contains any of these special characters ~ ( ) # \ / = > < + - * % & | ^ ' " [ ],
you must enclose the column name within square brackets [ ]. If a column name
contains right bracket ] or backslash \, escape it with backslash (\] or \\).

[C#]

dataView.RowFilter = "id = 10";      // no special character in column name "id"

dataView.RowFilter = "$id = 10";     // no special character in column name "$id"

dataView.RowFilter = "[#id] = 10";   // special character "#" in column name "#id"

dataView.RowFilter = "[[id\]] = 10"; // special characters in column name "[id]"

 

Literals

String values are enclosed within single quotes ' '. If the string contains single
quote '
, the quote must be doubled.

[C#]

dataView.RowFilter = "Name = 'John'"        // string value

dataView.RowFilter = "Name = 'John ''A'''"  // string with single quotes "John 'A'"

 

dataView.RowFilter = String.Format("Name = '{0}'", "John 'A'".Replace("'", "''"));

 

Number values are not enclosed within any characters. The values should be the same 
as
is the result of int.ToString() or float.ToString() method for invariant or
English culture.

[C#]

dataView.RowFilter = "Year = 2008"          // integer value

dataView.RowFilter = "Price = 1199.9"       // float value

 

dataView.RowFilter = String.Format(CultureInfo.InvariantCulture.NumberFormat,

                     "Price = {0}", 1199.9f);

 

Date values are enclosed within sharp characters # #. The date format is the
same as is the result of DateTime.ToString() method for invariant or English
culture.

[C#]

dataView.RowFilter = "Date = #12/31/2008#"          // date value (time is 00:00:00)

dataView.RowFilter = "Date = #2008-12-31#"          // also this format is supported

dataView.RowFilter = "Date = #12/31/2008 16:44:58#" // date and time value

 

dataView.RowFilter = String.Format(CultureInfo.InvariantCulture.DateTimeFormat,

                     "Date = #{0}#", new DateTime(2008, 12, 31, 16, 44, 58));

 

Alternatively you can enclose all values within single quotes ' '. It means you
can use string values for numbers or date time values. In this case the current
culture is used to convert the string to the specific value.

[C#]

dataView.RowFilter = "Date = '12/31/2008 16:44:58'" // if current culture is English

dataView.RowFilter = "Date = '31.12.2008 16:44:58'" // if current culture is German

 

dataView.RowFilter = "Price = '1199.90'"            // if current culture is English

dataView.RowFilter = "Price = '1199,90'"            // if current culture is German

 

Comparison operators

Equal, not equal, less, greater operators are used to include only values that suit
to a comparison expression. You can use these operators = <> < <= >
>=.

Note: String comparison is culture-sensitive, it uses CultureInfo from
DataTable.Locale property of related table (dataView.Table.Locale). If the property
is not explicitly set, its default value is DataSet.Locale (and its default value
is current system culture Thread.Curren¬tThread.Curren¬tCulture).

[C#]

dataView.RowFilter = "Num = 10"             // number is equal to 10

dataView.RowFilter = "Date < #1/1/2008#"    // date is less than 1/1/2008

dataView.RowFilter = "Name <> 'John'"       // string is not equal to 'John'

dataView.RowFilter = "Name >= 'Jo'"         // string comparison

 

Operator IN is used to include only values from the list. You can use the operator
for all data types, such as numbers or strings.

[C#]

dataView.RowFilter = "Id IN (1, 2, 3)"                    // integer values

dataView.RowFilter = "Price IN (1.0, 9.9, 11.5)"          // float values

dataView.RowFilter = "Name IN ('John', 'Jim', 'Tom')"     // string values

dataView.RowFilter = "Date IN (#12/31/2008#, #1/1/2009#)" // date time values

 

dataView.RowFilter = "Id NOT IN (1, 2, 3)"  // values not from the list

 

Operator LIKE is used to include only values that match a pattern with wildcards.
Wildcard character is * or %, it can be at the beginning of a pattern '*value',
at the end 'value*', or at both '*value*'. Wildcard in the middle of a
patern 'va*lue' is not allowed.

[C#]

dataView.RowFilter = "Name LIKE 'j*'"       // values that start with 'j'

dataView.RowFilter = "Name LIKE '%jo%'"     // values that contain 'jo'

 

dataView.RowFilter = "Name NOT LIKE 'j*'"   // values that don't start with 'j'

 

If a pattern in a LIKE clause contains any of these special characters * % [ ],
those characters must be escaped in brackets [ ] like this [*], [%], [[] or []].

[C#]

dataView.RowFilter = "Name LIKE '[*]*'"     // values that starts with '*'

dataView.RowFilter = "Name LIKE '[[]*'"     // values that starts with '['

 

The following method escapes a text value for usage in a LIKE clause.

[C#]

public static string EscapeLikeValue(string valueWithoutWildcards)

{

  StringBuilder sb = new StringBuilder();

  for (int i = 0; i < valueWithoutWildcards.Length; i++)

  {

    char c = valueWithoutWildcards[i];

    if (c == '*' || c == '%' || c == '[' || c == ']')

      sb.Append("[").Append(c).Append("]");

    else if (c == '\'')

      sb.Append("''");

    else

      sb.Append(c);

  }

  return sb.ToString();

}

 

[C#]

// select all that starts with the value string (in this case with "*")

string value = "*";

// the dataView.RowFilter will be: "Name LIKE '[*]*'"

dataView.RowFilter = String.Format("Name LIKE '{0}*'", EscapeLikeValue(value));

 

Boolean operators

Boolean operators AND, OR and NOT are used to concatenate expressions.
Operator NOT has precedence over AND operator and it has precedence over
OR operator.

[C#]

// operator AND has precedence over OR operator, parenthesis are needed

dataView.RowFilter = "City = 'Tokyo' AND (Age < 20 OR Age > 60)";

 

// following examples do the same

dataView.RowFilter = "City <> 'Tokyo' AND City <> 'Paris'";

dataView.RowFilter = "NOT City = 'Tokyo' AND NOT City = 'Paris'";

dataView.RowFilter = "NOT (City = 'Tokyo' OR City = 'Paris')";

dataView.RowFilter = "City NOT IN ('Tokyo', 'Paris')";

 

Arithmetic and string operators

Arithmetic operators are addition +, subtraction -, multiplication *,
division / and modulus %.

[C#]

dataView.RowFilter = "MotherAge - Age < 20";   // people with young mother

dataView.RowFilter = "Age % 10 = 0";           // people with decennial birthday

 

There is also one string operator concatenation +.

Parent-Child Relation Referencing

A parent table can be referenced in an expression using parent column name with
Parent. prefix. A column in a child table can be referenced using child column
name with Child. prefix.

The reference to the child column must be in an aggregate function because child
relationships may return multiple rows. For example expression SUM(Child.Price)
returns sum of all prices in child table related to the row in parent table.

If a table has more than one child relation, the prefix must contain relation name.
For example expression Child(OrdersToItemsRelation).Price references to column
Price in child table using relation named OrdersToItemsRe¬lation.

Aggregate Functions

There are supported following aggregate functions SUM, COUNT, MIN, MAX,
AVG (average), STDEV (statistical standard deviation) and VAR (statistical variance).


This example shows aggregate function performed on a single table.

[C#]

// select people with above-average salary

dataView.RowFilter = "Salary > AVG(Salary)";

 

Following example shows aggregate functions performed on two tables which have
parent-child relation. Suppose there are tables Orders and Items with the
parent-child relation.

[C#]

// select orders which have more than 5 items

dataView.RowFilter = "COUNT(Child.IdOrder) > 5";

 

// select orders which total price (sum of items prices) is greater or equal $500

dataView.RowFilter = "SUM(Child.Price) >= 500";

 

Functions

There are also supported following functions. Detailed description can be found here DataColumn.Ex¬pression.

•    CONVERT – converts particular expression to a specified .NET Framework type

•    LEN – gets the length of a string

•    ISNULL – checks an expression and either returns the checked expression or
a replacement value

•    IIF – gets one of two values depending on the result of a logical expression

•    TRIM – removes all leading and trailing blank characters like \r, \n, \t, ‚ ‘

•    SUBSTRING – gets a sub-string of a specified length, starting at a specified
point in the string

How To Check user exist or not by using Client CallBack

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Asp.net 2 Client Callback and AJAX Patterns</title>

<script type="text/ecmascript">
function lookupValue()
{
var control = document.getElementById("UserNameTextBox");
var value = control.getAttribute("value");
CallServer(value, "");
}

function displayResult(rValue)
{
document.getElementById("result").innerHTML = rValue;
}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="UserNameTextBox" style="width: 200px" />
<input type="button" id="ValidateButton" value="Check Availability" onclick="javascript:lookupValue()" />
<br />
<span id="result" style="color: Red;"></span>
</div>
</form>
</body>
</html>


using System;
using System.Web.Security;
using System.Web.UI;

public partial class _Default : Page, ICallbackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
string cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "displayResult", "", true);

string CallbackScript = "function CallServer(arg, context){" + cbReference + "; }";

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallBack", CallbackScript, true);
}

protected string IsUserExist;
public void RaiseCallbackEvent(string eventArgument)
{
try
{
if (GetUser(eventArgument) != "")
IsUserExist = "User name not available";
else
IsUserExist = "User name available";
}
catch (Exception ex)
{
IsUserExist = ex.Message;
}
}

public string GetCallbackResult()
{
return IsUserExist;
}
protected string GetUser(string s)
{
//I have used here a dummy method that returns user you
// can used return user from database here.
string strTemp;

System.Collections.Hashtable ht = new System.Collections.Hashtable();
ht.Add("santosh", "santosh");
ht.Add("test", "test");
if (ht.Contains(s))
{
strTemp = ht[s].ToString();
}
else
{
strTemp = "";
}
return strTemp;
}
}

How To Clear Browser Session In Asp.net

In this post i will show how to clear Browser history in asp.net.just write down following code in Logout button.


protected void LogOut()
{
Session.Abandon();
string nextpage = "Logoutt.aspx";
Response.Write("<script language=javascript>");

Response.Write("{");
Response.Write(" var Backlen=history.length;");

Response.Write(" history.go(-Backlen);");
Response.Write(" window.location.href='" + nextpage + "'; ");

Response.Write("}");
Response.Write("</script>");

}

Making a small Popup picture on mouse over event

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>

<script type="text/javascript">
function get_(div_)
{
div_=div_.id+"1";
document.getElementById(div_).style.display="block";
}
function get_1(div_)
{
div_=div_.id+"1";
document.getElementById(div_).style.display="none";
}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="Server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:LinkButton ID="lnk" runat="server" Text="Details" onmouseover="get_(this);"
onmouseout="get_1(this);" />
<div id="lnk1" runat="server" style="display: none; position: absolute; background-color: #FEFFB3;
width: 150px"
>
<p>
<strong>Image Name</strong></p>
<p>
<img src='<%#Eval("ImagePath")%>' runat="Server" id="A" /></p>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>








using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class MouseOverGrid : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetData();
GridView1.DataBind();

}
}
public DataSet GetData()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("Movie");
DataRow dr;
dt.Columns.Add(new DataColumn("Id", typeof(Int32)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));

dt.Columns.Add(new DataColumn("ImagePath", typeof(string)));
for (int i = 1; i <= 5; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Name" + i.ToString();
dr[2] = "~/images/sa2.jpeg";
dt.Rows.Add(dr);
}
for (int i = 1; i <= 5; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Name" + i.ToString();
dr[2] = "~/images/pdf-icon.jpg";
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
Session["dt"] = dt;
return ds;
}
}

Saturday, September 3, 2011

ACTIVE DIRECTORY HELPER

Everything in Active Directory via C#.Net 3.5 (Using System.DirectoryServices.AccountManagement)




Before .Net managing Active Directory objects is a bit lengthy and you need a good knowledge on the principal store to have your head around on what you want to do.  We ususally use the System.DirectoryServices namespace but with .Net 3.5 they introduced System.DirectoryServices.AccountManagement which is manages directory objects independent of the System.DirectoryServices namespace.


So what are the advantages of using this if I have already a library created for the whole AD Methods that System.DirectoryServices exposed?  Because everything is really simple in terms of managing a user, computer or group principal and performing queries on the stores are much faster thanks to the Fast Concurrent Bind (FSB) feature which caches the connection which decreases the number of ports used in the process.


I remember I had posted a while back Active Directory Objects and C# which is basically everything regarding AD Methods in terms of Users and Group management and if you see the codebase is a bit lengthy and you need a bit of understanding on setting and getting hex values thats why I ennumerated it.  Now I had rewritten it using the System.DirectoryServices.AccountManagement namespace, fucntionalities remain the same but its easier to understand and there are fewer lines.|



The code is divided into several regions but here are the 5 key regions with their methods explained


Validate Methods



  • ValidateCredentials – This Method will validate the users credentials.

  • IsUserExpired – Checks if the User Account is Expired.

  • IsUserExisiting – Checks if user exsists on AD.

  • IsAccountLocked  – Checks if user account is locked



Search Methods



  • GetUser – This will return a UserPrincipal Object if the User Exists


User Account Methods



  • SetUserPassword – This Method will set the Users Password

  • EnableUserAccount – This Method will Enable a User Account

  • DisableUserAccount – This Methoid will Disable the User Account

  • ExpireUserPassword – This Method will Force Expire a Users Password


  • UnlockUserAccount – This Method will unlocks a User Account

  • CreateNewUser – This Method will Create a new User Directory Object

  • DeleteUser – This Method will Delete an AD User based on Username.


Group Methods



  • CreateNewGroup – This Method will create a New Active Directory Group

  • AddUserToGroup – This Method will add a User to a group

  • RemoveUserFromGroup – This Method will remove a User from a Group

  • IsUserGroupMember – This Method will Validate whether the User is a Memeber of a Group


  • GetUserGroups – This Method will return an ArrayList of a User Group Memberships


Helper Methods



  • GetPrincipalContext – Gets the base principal context



Now here are the codes


using System;

using System.Collections;
using System.Text;

using System.DirectoryServices.AccountManagement;
using System.Data;
using System.Configuration;

public class ADMethodsAccountManagement
{

#region Variables

private string sDomain = "test.com";

private string sDefaultOU = "OU=Test Users,OU=Test,DC=test,DC=com";
private string sDefaultRootOU = "DC=test,DC=com";
private string sServiceUser = @"ServiceUser";

private string sServicePassword = "ServicePassword";

#endregion
#region Validate Methods

/// <summary>
/// Validates the username and password of a given user

/// </summary>
/// <param name="sUserName">The username to validate</param>
/// <param name="sPassword">The password of the username to validate</param>

/// <returns>Returns True of user is valid</returns>
public bool ValidateCredentials(string sUserName, string sPassword)
{

    PrincipalContext oPrincipalContext = GetPrincipalContext();
    return oPrincipalContext.ValidateCredentials(sUserName, sPassword);

}

/// <summary>
/// Checks if the User Account is Expired

/// </summary>
/// <param name="sUserName">The username to check</param>
/// <returns>Returns true if Expired</returns>

public bool IsUserExpired(string sUserName)
{
    UserPrincipal oUserPrincipal = GetUser(sUserName);
    if (oUserPrincipal.AccountExpirationDate != null)
    {
        return false;

    }
    else
    {
        return true;
    }
}

/// <summary>
/// Checks if user exsists on AD

/// </summary>
/// <param name="sUserName">The username to check</param>
/// <returns>Returns true if username Exists</returns>

public bool IsUserExisiting(string sUserName)
{
    if (GetUser(sUserName) == null)
    {
        return false;
    }
    else

    {
        return true;
    }
}

/// <summary>
/// Checks if user accoung is locked
/// </summary>

/// <param name="sUserName">The username to check</param>
/// <returns>Retruns true of Account is locked</returns>

public bool IsAccountLocked(string sUserName)
{
    UserPrincipal oUserPrincipal = GetUser(sUserName);
    return oUserPrincipal.IsAccountLockedOut();
}
#endregion

#region Search Methods


/// <summary>
/// Gets a certain user on Active Directory
/// </summary>
/// <param name="sUserName">The username to get</param>

/// <returns>Returns the UserPrincipal Object</returns>
public UserPrincipal GetUser(string sUserName)
{
    PrincipalContext oPrincipalContext = GetPrincipalContext();


    UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);
    return oUserPrincipal;
}

/// <summary>
/// Gets a certain group on Active Directory

/// </summary>
/// <param name="sGroupName">The group to get</param>
/// <returns>Returns the GroupPrincipal Object</returns>

public GroupPrincipal GetGroup(string sGroupName)
{
    PrincipalContext oPrincipalContext = GetPrincipalContext();

    GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, sGroupName);
    return oGroupPrincipal;
}


#endregion

#region User Account Methods

/// <summary>
/// Sets the user password
/// </summary>

/// <param name="sUserName">The username to set</param>
/// <param name="sNewPassword">The new password to use</param>

/// <param name="sMessage">Any output messages</param>
public void SetUserPassword(string sUserName, string sNewPassword, out string sMessage)
{

    try
    {
        UserPrincipal oUserPrincipal = GetUser(sUserName);
        oUserPrincipal.SetPassword(sNewPassword);
        sMessage = "";
    }
    catch (Exception ex)

    {
        sMessage = ex.Message;
    }

}

/// <summary>
/// Enables a disabled user account
/// </summary>

/// <param name="sUserName">The username to enable</param>
public void EnableUserAccount(string sUserName)
{
    UserPrincipal oUserPrincipal = GetUser(sUserName);

    oUserPrincipal.Enabled = true;
    oUserPrincipal.Save();
}

/// <summary>
/// Force disbaling of a user account
/// </summary>

/// <param name="sUserName">The username to disable</param>
public void DisableUserAccount(string sUserName)
{
    UserPrincipal oUserPrincipal = GetUser(sUserName);

    oUserPrincipal.Enabled = false;
    oUserPrincipal.Save();
}

/// <summary>
/// Force expire password of a user
/// </summary>

/// <param name="sUserName">The username to expire the password</param>
public void ExpireUserPassword(string sUserName)
{
    UserPrincipal oUserPrincipal = GetUser(sUserName);

    oUserPrincipal.ExpirePasswordNow();
    oUserPrincipal.Save();

}

/// <summary>
/// Unlocks a locked user account
/// </summary>
/// <param name="sUserName">The username to unlock</param>

public void UnlockUserAccount(string sUserName)
{
    UserPrincipal oUserPrincipal = GetUser(sUserName);
    oUserPrincipal.UnlockAccount();
    oUserPrincipal.Save();
}

/// <summary>
/// Creates a new user on Active Directory

/// </summary>
/// <param name="sOU">The OU location you want to save your user</param>

/// <param name="sUserName">The username of the new user</param>
/// <param name="sPassword">The password of the new user</param>

/// <param name="sGivenName">The given name of the new user</param>
/// <param name="sSurname">The surname of the new user</param>

/// <returns>returns the UserPrincipal object</returns>
public UserPrincipal CreateNewUser(string sOU, string sUserName, string sPassword, string sGivenName, string sSurname)
{

    if (!IsUserExisiting(sUserName))
    {
        PrincipalContext oPrincipalContext = GetPrincipalContext(sOU);

        UserPrincipal oUserPrincipal = new UserPrincipal(oPrincipalContext, sUserName, sPassword, true /*Enabled or not*/);


        //User Log on Name
        oUserPrincipal.UserPrincipalName = sUserName;
        oUserPrincipal.GivenName = sGivenName;
        oUserPrincipal.Surname = sSurname;
        oUserPrincipal.Save();

        return oUserPrincipal;

    }
    else
    {
        return GetUser(sUserName);
    }
}

/// <summary>
/// Deletes a user in Active Directory

/// </summary>
/// <param name="sUserName">The username you want to delete</param>
/// <returns>Returns true if successfully deleted</returns>

public bool DeleteUser(string sUserName)
{
    try
    {
        UserPrincipal oUserPrincipal = GetUser(sUserName);

        oUserPrincipal.Delete();
        return true;
    }

    catch
    {
        return false;
    }
}

#endregion

#region Group Methods

/// <summary>
/// Creates a new group in Active Directory

/// </summary>
/// <param name="sOU">The OU location you want to save your new Group</param>

/// <param name="sGroupName">The name of the new group</param>
/// <param name="sDescription">The description of the new group</param>

/// <param name="oGroupScope">The scope of the new group</param>
/// <param name="bSecurityGroup">True is you want this group to be a security group, false if you want this as a distribution group</param>

/// <returns>Retruns the GroupPrincipal object</returns>
public GroupPrincipal CreateNewGroup(string sOU, string sGroupName, string sDescription, GroupScope oGroupScope, bool bSecurityGroup)
{

    PrincipalContext oPrincipalContext = GetPrincipalContext(sOU);

    GroupPrincipal oGroupPrincipal = new GroupPrincipal(oPrincipalContext, sGroupName);
    oGroupPrincipal.Description = sDescription;
    oGroupPrincipal.GroupScope = oGroupScope;

    oGroupPrincipal.IsSecurityGroup = bSecurityGroup;
    oGroupPrincipal.Save();

    return oGroupPrincipal;
}

/// <summary>
/// Adds the user for a given group

/// </summary>
/// <param name="sUserName">The user you want to add to a group</param>

/// <param name="sGroupName">The group you want the user to be added in</param>
/// <returns>Returns true if successful</returns>

public bool AddUserToGroup(string sUserName, string sGroupName)
{
    try
    {
        UserPrincipal oUserPrincipal = GetUser(sUserName);
        GroupPrincipal oGroupPrincipal = GetGroup(sGroupName);

        if (oUserPrincipal != null && oGroupPrincipal != null)
        {
            if (!IsUserGroupMember(sUserName, sGroupName))
            {
                oGroupPrincipal.Members.Add(oUserPrincipal);
                oGroupPrincipal.Save();
            }
        }

        return true;
    }
    catch
    {
        return false;
    }
}

/// <summary>
/// Removes user from a given group

/// </summary>
/// <param name="sUserName">The user you want to remove from a group</param>

/// <param name="sGroupName">The group you want the user to be removed from</param>
/// <returns>Returns true if successful</returns>

public bool RemoveUserFromGroup(string sUserName, string sGroupName)
{
    try
    {
        UserPrincipal oUserPrincipal = GetUser(sUserName);
        GroupPrincipal oGroupPrincipal = GetGroup(sGroupName);

        if (oUserPrincipal != null && oGroupPrincipal != null)
        {
            if (IsUserGroupMember(sUserName, sGroupName))
            {
                oGroupPrincipal.Members.Remove(oUserPrincipal);
                oGroupPrincipal.Save();
            }
        }

        return true;
    }
    catch
    {
        return false;
    }
}

/// <summary>
/// Checks if user is a member of a given group

/// </summary>
/// <param name="sUserName">The user you want to validate</param>
/// <param name="sGroupName">The group you want to check the membership of the user</param>

/// <returns>Returns true if user is a group member</returns>
public bool IsUserGroupMember(string sUserName, string sGroupName)
{

    UserPrincipal oUserPrincipal = GetUser(sUserName);
    GroupPrincipal oGroupPrincipal = GetGroup(sGroupName);

    if (oUserPrincipal != null && oGroupPrincipal != null)
    {

        return oGroupPrincipal.Members.Contains(oUserPrincipal);
    }
    else
    {
        return false;
    }
}

/// <summary>
/// Gets a list of the users group memberships

/// </summary>
/// <param name="sUserName">The user you want to get the group memberships</param>

/// <returns>Returns an arraylist of group memberships</returns>
public ArrayList GetUserGroups(string sUserName)
{
    ArrayList myItems = new ArrayList();

    UserPrincipal oUserPrincipal = GetUser(sUserName);

    PrincipalSearchResult<Principal> oPrincipalSearchResult = oUserPrincipal.GetGroups();

    foreach (Principal oResult in oPrincipalSearchResult)
    {
        myItems.Add(oResult.Name);

    }
    return myItems;
}

/// <summary>
/// Gets a list of the users authorization groups
/// </summary>

/// <param name="sUserName">The user you want to get authorization groups</param>
/// <returns>Returns an arraylist of group authorization memberships</returns>

public ArrayList GetUserAuthorizationGroups(string sUserName)
{
    ArrayList myItems = new ArrayList();
    UserPrincipal oUserPrincipal = GetUser(sUserName);

    PrincipalSearchResult<Principal> oPrincipalSearchResult = oUserPrincipal.GetAuthorizationGroups();


    foreach (Principal oResult in oPrincipalSearchResult)
    {
        myItems.Add(oResult.Name);
    }
    return myItems;
}

#endregion

#region Helper Methods


/// <summary>
/// Gets the base principal context
/// </summary>
/// <returns>Retruns the PrincipalContext object</returns>

public PrincipalContext GetPrincipalContext()
{
    PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, sDomain, sDefaultOU, ContextOptions.SimpleBind, sServiceUser, sServicePassword);

    return oPrincipalContext;
}

/// <summary>
/// Gets the principal context on specified OU
/// </summary>

/// <param name="sOU">The OU you want your Principal Context to run on</param>
/// <returns>Retruns the PrincipalContext object</returns>

public PrincipalContext GetPrincipalContext(string sOU)
{
    PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, sDomain, sOU, ContextOptions.SimpleBind, sServiceUser, sServicePassword);

    return oPrincipalContext;
}

#endregion

}