Archive for the 'C#' Category

21
May
09

Generating an Unique Number and String in C#

i had a trouble with one my client wantz a unique chars

in .NET we often use System.GUID to generate a unique key, but it is very long. you know when it comes to web(scenario) where it is part of the URL we need to use its string representation which is 36 characters long. It’s utterly very pathetic isn’t so ugly.

is it possible to shorten the it without loosing some of the uniqueness of the GUID, but we can come a long way if we can accept a 16 character string instead. here the magic

We can change the standard GUID string representation:

21726045-e8f7-4b09-abd8-4bcc926e9e28

Into a shorter string:

3c4ebc5f5f2c4edc

private string GenerateId()
{
     long i = 1;
     foreach (byte b in Guid.NewGuid().ToByteArray())
     {
          i *= ((int)b + 1);
     }
     return string.Format("{0:x}", i - DateTime.Now.Ticks);
}

the above method creates the shorter string and it is actually very unique. which is an iteration of 10 million, make a guess man. It won’t  duplicate. It uses the uniqueness of a GUID to create the string.

If you want numbers instead of a string, you can do that to but then you need to go up to 19 characters. The following method converts a GUID to an Int64.

private long GenerateId()
{
        byte[] buffer = Guid.NewGuid().ToByteArray();
        return BitConverter.ToInt64(buffer, 0);
}

The standard GUID is still the best way to ensure the uniqueness even though it isn’t 100% unique.

Check it, Happy Coding…

03
Feb
09

Free online courses for developers – MSDN Ramp Up

myrampup.com

Ramp Up is a free, online, community-based learning program that will help you build professional development skills. Join Ramp Up (it’s free!) and help advance your career – click on a track now to start!

Review the available tracks and pick one (or more) to start now!

Check out the Ramp Up program (http://www.myrampup.com/) if you have not done already. It has interesting tracks including SharePoint provided by Microsoft…

15
Sep
08

Active Directory User Selective Inductive Field Control

My project manager ask me to do the Active Directory User Selective inductive method to seperate out the active directory users from the telephone extension list users who were binded in their Display Name with the Active Directory, the following is a small module for our companies sharepoint protal management server to maintain all the resources in a centeral station as repository for that we have developed a list contains the extension list of all employees…
the list does has two field types, column named <Employee Name> and <Extension Number>

Note : <Employee Name> Field maps with the Display Name of the Active Directory Users List…

the following xCode.GetADUser.Field.cs

namespace xCode.GetADUser
{
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Security;

    [CLSCompliant(false)]
    [Guid("d3fee3ce-4e3a-4990-8bde-3b52d3596be4")]
    public class ADUserField : SPFieldText
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="fields"></param>
        /// <param name="fieldName"></param>
        public GetADUserField(SPFieldCollection fields, string fieldName)
            : base(fields, fieldName)
        {
        }
       
        /// <summary>
        ///
        /// </summary>
        /// <param name="fields"></param>
        /// <param name="typeName"></param>
        /// <param name="displayName"></param>
        public GetADUserField(SPFieldCollection fields, string typeName, string displayName)
            : base(fields, typeName, displayName)
        {
        }

        /// <summary>
        ///
        /// </summary>
        public override BaseFieldControl FieldRenderingControl
        {
            [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
            get
            {
                BaseFieldControl fieldControl = new GetADUserFieldControl();
                fieldControl.FieldName = this.InternalName;

                return fieldControl;
            }
        }
    }
}

the below code describes the functionality for the get Active directory Users…

lets take two asp.net controls for the following functionality, where the dropdownlist list up all the users from the active directory irregardless any condition except the object.filter by user…

 // Golbal variables for the Get Active Directory Userfield control.
        private DropDownList ddlRemainADUsers;
        private Label lblADUser;

the above DropDownList list will visible only on the Newform.aspx and Editform.aspx whereas the Label control will visible only for an alternate form (Dispform.aspx)

 /// <summary>
        /// CreateChildControls() will be called by the PreRender stage
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            //Filtering the ControlMode for field in both Newform.aspx as well as Editform.aspx
            if (this.ControlMode == SPControlMode.Edit ||
                this.ControlMode == SPControlMode.New) 
            {
                // Initialize the ddlRemainADUsers DropDownList with new instance
                this.ddlRemainADUsers = new DropDownList();

                // Gets the current site from the SPContext
                SPSite objSite = SPContext.GetContext(this.Context).Site;

                // Binding all Active directory Users into the AdUsersList ArrayList Control.
                // return all users from the Active Directory.
                ArrayList AdUsersList = getADUsers();

                // ArrayList to be subtracted to the AdUsersList ArrayList...
                ArrayList UserList = new ArrayList();

                // Remained Users after the Seperation done...
                ArrayList RemainList = new ArrayList();
                SPWeb objWeb = objSite.OpenWeb();

                // validating the List Item Count not set to be 0 or less than that...
                if (web.Lists[<listName>].ItemCount > 0) {                   
                    SPListItemCollection objListItemColl = objWeb.Lists[<listName>].Items;
                    // Iterating through each ListItem from the respective list <listName>
                    foreach (SPListItem objListItem in objListItemColl) {
                        if (objListItem[<EmployeeNameField>] == null) {
                            UserList.Add(""); // Adding the empty string.Empty when the field value set to be null...
                        }
                        else {
                            UserList.Add(_Item[<EmployeeNameField>].ToString()); // else addnig the field value
                        }
                    }

                    // Here the Magic code.
                    int Count = AdUsersList.Count;
                    if (!(UserList.Count <= 0)) {
                        for (int inr = 0; inr < Count; inr++) {
                            // if Active Directory Users were not found to be in the UserList ArrayList then add those users into the RemainList ArrayList
                            if (!UserList.Contains(AdUsersList[inr]))
                                RemainList.Add(AdUsersList[inr].ToString());
                        }
                    }
                    else {
                        for (int inr = 0; inr < Count; inr++) {
                            RemainList.Add(AdUsersList[inr].ToString());
                        }
                    }
                }
                else {
                    int Count = AdUsersList.Count;
                    for (int inr = 0; inr < Count; inr++) {
                        RemainList.Add(AdUsersList[inr].ToString());
                    }
                }

                // Sorting the ArrayList if needed
                RemainList.Sort();

                // Binds the RemainList Users to the ddlRemainADUsers DropDownList         
                this.ddlRemainADUsers.DataSource = RemainList;
                this.ddlRemainADUsers.DataBind(); // Call a Simple DataBind()

                // Get the current value of the field.
                string currentValue = (string)this.ItemFieldValue;

                if (!string.IsNullOrEmpty(currentValue)) { // Checks or Validates the currentValue
                    this.ddlRemainADUsers.SelectedValue = currentValue;
                }
                else if (this.ddlRemainADUsers.Items.Count > 0) {
                    this.ddlRemainADUsers.SelectedIndex = 0;
                }

                // Add an Attributes for "onchange" event for the ddlRemainADUsers DropDownList
                this.ddlRemainADUsers.Attributes["onchange"] = "this.options[this.selectedIndex].value;";
                base.Controls.Add(ddlRemainADUsers);
            }         

            string text = null;
            object textObject = this.ItemFieldValue;

            if (textObject != null) {
                // ReBinds the textObject Value to the textbox for the View Mode
                text = (string)textObject;
            }

            if (text == null || text == string.Empty) {
                text = this.ddlRemainADUsers.SelectedValue;
            }

            //Filtering the ControlMode for field in both Dispform.aspx
            if (this.ControlMode == SPControlMode.Display) {
                lblADUser = new Label();
                lblADUser.Text = text.ToString();
                base.Controls.Add(lblADUser);
            }           
        }

        /// <summary>
        /// Updates the Field Value with from the ddlRemainADUsers.SelectedValue to the ItemFieldValue.Value
        /// from where we rebind the ItemFieldValue to the textObject Value
        /// </summary>
        public override void UpdateFieldValueInItem()
        {

            this.EnsureChildControls();
            try {
                this.Value = this.ddlRemainADUsers.SelectedValue;
                this.ItemFieldValue = this.Value;
            }
            catch {
                ;
            }
        }

        /// <summary>
        /// Render the xCode.GetADUser
        /// </summary>
        /// <param name="output"></param>
        protected override void Render(HtmlTextWriter output)
        {
            if (this.ControlMode == SPControlMode.Edit ||
                this.ControlMode == SPControlMode.New) {               
                this.ddlRemainADUsers.RenderControl(output);
            }
            if (this.ControlMode == SPControlMode.Display) {
                this.lblADUser.RenderControl(output);
            }
        }

}

might thing this helps a lot for the comparing as well as subtracting the Active Directory Users with the Desired List Column…
Cheers !!!
Happy Coding…

15
Sep
08

LightWeight Active Directory – Change User’s Password Webpart

AD Password Changer allows users to change their Active Directory password. AD Password Changer has a simple user interface and provides descriptive responses to users whose new passwords may not meet minimum requirements.
Here i have exposed the logical part of my code, instead not the complete solution pack… i would rather arrange for that in future as a downloadable code in *.zip format…

One of the most common functions to perform in Active Directory from a SharePoint application or C# ASP .NET application is resetting user passwords.
However, by following a few important logical webpart redesign, you can have your webpart easily resetting user passwords in Active Directory not more with rendering the controls and bind to the page control…

By remembering the security rules of .NET, Windows, and IIS, manipulating passwords can be a straight forward process. Always remember to enclose all Active Directory functions within a try catch block in order to handle errors.

namespace xCode.ChangeMyPassword
{

 [DefaultProperty("LabelLoggedOn"), ToolboxData("<{0}:ChangeMyPassword runat=server></{0}:ChangeMyPassword>"), XmlRoot(Namespace="xCode.ChangeMyPassword")]
 public class ChangeMyPassword : WebPart, IDesignTimeHtmlProvider
 {

       /// Reduced code for complete explanation
        private TextBox _txtNewPw;
        private TextBox _txtNewRPw;
        private TextBox _txtOldPw;

        /// <summary>
        ///  Method handles the Change Password button click event...
        /// </summary> 
        private void btnChangePw_Click(object sender, EventArgs e)
        {
            Label label;
            if (this._txtNewPw.Text.Length >= 0)
            {
                if (this._txtNewPw.Text.Equals(this._txtNewRPw.Text))
                {
                    DirectoryEntry entry;
                    string[] strArray = this.Context.User.Identity.Name.Split(new char[] { '\\' });
                    if (this.isLocalAccount())
                    {
                        try
                        {
       // Connect to Active Directory and get the DirectoryEntry object.
       // Note, ADPath is an Active Directory path pointing to a user.

                            entry = new DirectoryEntry("WinNT://" + strArray[0] + "/" + strArray[1], this.Context.User.Identity.Name, this._txtOldPw.Text, AuthenticationTypes.Secure);
                        }
                        catch (Exception exception1)
                        {
                            Exception ex1 = exception1;
                            label = this._lblError;
                            label.Text = label.Text + this.ex1.Message.ToString();
       return;
                        }
                        try
                        {
                            object objectValue = RuntimeHelpers.GetObjectValue(entry.Invoke("ChangePassword", new object[] { this._txtOldPw.Text, this._txtNewPw.Text }));
                        }
                        catch (Exception exception5)
                        {
                            Exception ex2 = exception5;
                            label = this._lblError;
                            label.Text = label.Text + this.ex2.Message.ToString();
       return;
                        }
                    }
                    else
                    {
                        try
                        {
                            string[] propertiesToLoad = new string[] { "sAMAccountName", "cn" };
                            DirectorySearcher searcher = new DirectorySearcher("(sAMAccountName=" + strArray[1] + ")", propertiesToLoad);
                            searcher.SearchRoot.Username = this.Context.User.Identity.Name;
                            searcher.SearchRoot.Password = this._txtOldPw.Text;

       // You would have created this which searches AD for the specified user
       // and returns its DirectoryEntry object or path. See here.
                            SearchResult result = searcher.FindOne();
                            if (result == null)
                            {
                                label = this._lblError;
                                label.Text = label.Text + "The User was not found in the Active Directory";
                            }
                            entry = new DirectoryEntry(result.Path, this.Context.User.Identity.Name, this._txtOldPw.Text);
                            entry.RefreshCache();
                        }
                        catch (Exception exception6)
                        {
                            Exception ex3 = exception6;
                            label = this._lblError;
                            label.Text = label.Text + this.ex3.Message.ToString();
                            return;
                        }
                        try
                        {
       // Impersonate a user with administrative rights.
       // Reset the password.

                            entry.Invoke("ChangePassword", new object[] { this._txtOldPw.Text, this._txtNewPw.Text });
                        }
                        catch (Exception exception7)
                        {
                            Exception ex4 = exception7;
                            label = this._lblError;
                            label.Text = label.Text  + this.ex4.Message.ToString();
                            return;
                        }
                    }
                    label = this._lblError;
                    label.Text = label.Text + this.SuccessMessage;
                }
                else
                {
                    label = this._lblError;
                    label.Text = label.Text + this.ErrorMessagePasswordMatch;
                }
            }
            else
            {
                label = this._lblError;
                label.Text = label.Text + "Password doesn't match requirements.";
            }
        }

 /// <summary>
 ///  Boolean method returns the Account of the User previliage as local or gobal...
 /// </summary> 
 /// <return>bool</return>
 private bool isLocalAccount()
        {
            return (this.Context.Server.MachineName.ToUpper() == this.Context.User.Identity.Name.Split(new char[] { '\\' })[0]);
        }
   }
}

Cheers !!!

Happy Coding…

15
Sep
08

Programmatically adding the SPField through XML node…

here i’m back with adding the SPField programmatically through object model… to do that we should know some xml nodes of the scheme.xml for the respective SPList Definition, if so <field> tag helps us to add the unique field as we create…
First we should read the list fields as xml node using the field method “AddFieldAsXml(string xmlwriter)” write the desired code to get the field over in the List programmatically. while declaring the xml string node onto the AddFieldAsXml() method we can specify or says the field to show in new form or we could filter in the edit form for the respective users as your wish…

/// <summary>
///  Ensuring the use of the respective field in List.
/// </summary>
/// <param name="List"></param>
/// <returns></returns>
public static SPField EnsureUseListItemWorkspaceField(SPList List)
{
   SPField field = null;
     try
     {
        field = List.Fields.GetFieldByInternalName(PMO.ListItemWorkspace.Event.EventReceiver.UseListItemWorkspaceName);
     }
     catch (Exception)
     {
        string strNewFieldName = List.Fields.AddFieldAsXml(
                    "<Field Name=\"" + PMO.ListItemWorkspace.Event.EventReceiver.UseListItemWorkspaceName + "\" DisplayName=\"" + PMO.ListItemWorkspace.Event.EventReceiver.UseListItemWorkspaceName + "\" Type=\"Boolean\" FromBaseType=\"TRUE\" ShowInEditForm=\"FALSE\" ShowInNewForm=\"FALSE\">" +
                    "    <Default>TRUE</Default>" +
                    "</Field>");
        field = List.Fields.GetField(strNewFieldName);
        field.Title = "Use List Item Workspace";
        field.Update();
     }

   return field;
}

Cheers…
Happy Coding…




Calendar

June 2012
M T W T F S S
« Feb    
 123
45678910
11121314151617
18192021222324
252627282930  

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 1 other follower


Follow

Get every new post delivered to your Inbox.