Click here to Skip to main content
Click here to Skip to main content

Custom Control for User Alias Validator in ASP.NET

, 19 Mar 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
Custom control to check v-id or email ID in a domain.

Introduction

This article is for the developer who has no experience with web custom controls and who wants to develop a custom control and wants to use it in ASP.NET web pages by drag drop from the Toolbar like a simple ASP.NET button control. This custom control is not only a simple custom control it also works to check the user ID like v-Id of the user in a domain whether the user exists in the domain or not.

Background

In my experience with user controls we can do the work but it is not very flexible. You cannot get the flavor of Toolbox drag and drop control easily and what I feel after using this custom control the performance is faster with respect to any other process and in a custom control you can give your own design own concept and make whatever you want of your choice. Here also you do not have to register the control like:

<%@ Register Assembly="CustomEMailControl" NameSpace="YourCustomNameSpace" TagPrefix="MyControl"%>

You just add the DLL and the custom control will get added to your tool box and just drag and drop the custom control. Like other controls it will be auto registered to that page and you can use it now.

Note: The main work while creating a custom control is you you have to add references of System, like System.Web etc... and you have to inherit from CompositeControl in your class to get the properties of predefined controls like TextBox and ImageButton if you want to add these flavours into your control easily.

Using the code

For using: Just download dll.zip and add to your ASP.NET Tool Box by browsing from the toolbar, right click in the Tool Box then Choose Items. After that add this DLL by browsing and after that it will be added to the ToolBox then you can drag and drop into your .aspx page and you can work on it.

For creating from scratch: Download the CustomControl.zip and you will get a class. Just copy the class and you create a Class Library and create your own class, or use this class by adding an existing item and check the Namespace and Assembly name. Then build the class library. Now you will get a DLL in the bin folder in your project where you have created a class library. Now just do the same in the above mentioned para.

Class Code

I have added comments so you can understand each line by its comments and you can do any changes to the name, property name, ID according to your wish.

//

// Created By : Fayaz Date :15-3-2013
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Web;
using System.Security.Permissions;
using System.ComponentModel;
using System.DirectoryServices.AccountManagement;
using System.Configuration;

namespace CustomEMailControl
{
    [
        // This is for registering the Control while drag and drop on the UI        
        ToolboxData("<{0}:EMailChecker ID='AliasID' runat="\""server\"> </{0}:EMailChecker>")
      ]

    // Here I am ingeriting the CompositeControl for getting all the effects of Controls
    public partial class EMailChecker : CompositeControl
    {
        // Text Box object is Declared which is used to create a TextBox Control
        TextBox _txtBoxAlias;
        // Image Button Object is Declared which is used to create a an Image Control
        ImageButton _imgButton;
        // This is used to hold the domainnames of the Domain like Redmond,Fareast,...
        string _domainNames;

        // This is used to hold the adConnection like ".corp.microsoft.com"
        string _adConnection;
        
        [Category("Appreance")]
        [Description("Set The Check Name Icon")]
        
        // This property is to give the URL to the Image Button
        public string ImageButtonURL
        {
            get
            {
                // It checks if the child controls are created/not
                EnsureChildControls();
                return _imgButton.ImageUrl != null ? _imgButton.ImageUrl : string.Empty;
            }
            set
            {
                // It checks if the child controls are created/not
                EnsureChildControls();
                _imgButton.ImageUrl = value;
            }
        }

        // This property is to give the Height to the Image of the Button
        public Unit ImageButtonHeight
        {
            get
            {
                // It checks if the child controls are created/not
                EnsureChildControls();
                return _imgButton.Height != null ? _imgButton.Height : Unit.Empty;
            }
            set
            {
                // It checks if the child controls are created/not
                EnsureChildControls();
                _imgButton.Height = value;
            }
        }

        // This property is to give the Width to the Image of the Button
        public Unit ImageButtonWidth
        {
            get
            {
                // It checks if the child controls are created/not
                EnsureChildControls();
                return _imgButton.Width != null ? _imgButton.Width : Unit.Empty;
            }
            set
            {
                // It checks if the child controls are created/not
                EnsureChildControls();
                _imgButton.Width = value;
            }
        }

        // This property is set the table width 
        public Unit TextBoxWidth
        {
            get
            {
                // It checks if the child controls are created/not
                EnsureChildControls();
                return _txtBoxAlias.Width != null ? _txtBoxAlias.Width : Unit.Empty;
            }
            set
            {
                // It checks if the child controls are created/not
                EnsureChildControls();
                _txtBoxAlias.Width = value;
            }
        }

        // This property is to set the TextBox Text
        public string TextBoxText
        {
            get
            {
                // It checks if the child controls are created/not
                EnsureChildControls();
                return _txtBoxAlias.Text != null ? _txtBoxAlias.Text : string.Empty;
            }
            set
            {
                // It checks if the child controls are created/not
                EnsureChildControls();
                _txtBoxAlias.Text = value;
            }
        }

        // This property is set the CssClass to the TextBox
        // These Properties are exposed to the UI
        public string TextBoxCssClass
        {
            get
            {
                // It checks if the child controls are created/not
                EnsureChildControls();
                return _txtBoxAlias.CssClass != null ? _txtBoxAlias.CssClass : string.Empty;
            }
            set
            {
                // It checks if the child controls are created/not
                EnsureChildControls();
                _txtBoxAlias.CssClass = value;
            }
        }

        // This property is set the Domain names by Comma separated
        public string DomainNames
        {
            get
            {
                // It checks if the child controls are created/not
                EnsureChildControls();
                return _domainNames != null ? _domainNames : string.Empty;
            }
            set
            {
                // It checks if the child controls are created/not
                EnsureChildControls();
                _domainNames = value;
            }
        }

        // This property is to the Domain ADCONNECTION like .corp.microsoft.com
        public string ADCONNECTION
        {
            get
            {
                // It checks if the child controls are created/not
                EnsureChildControls();
                return _adConnection != null ? _adConnection : string.Empty;
            }
            set
            {
                // It checks if the child controls are created/not
                EnsureChildControls();
                _adConnection = value;
            }
        }
    
        /// <summary>
        /// Creates the Child Controls
        /// </summary>
        protected override void CreateChildControls()
        {
            // Clears the Controls
            Controls.Clear();
            // create the TextBox Control object
            _txtBoxAlias = new TextBox();
            // added an Id to the textBox not compulsory
            _txtBoxAlias.ID = "txtAlias";

            // Text box width is assigned to the Textbox from the Property
            // from UI like <asp:TextBox Width="200"/>
            _txtBoxAlias.Width = TextBoxWidth;

            // Text box CssClass is assigned to the Textbox from the Property
            // from UI like <asp:TextBox CssClass="abc"/>
            _txtBoxAlias.CssClass = TextBoxCssClass;

            // Text box Text is assigned to the Textbox from the Property
            // from UI like <asp:TextBox Text="Hello"/>
            _txtBoxAlias.Text = TextBoxText;

            // create the ImageButton Control object
            _imgButton = new ImageButton();

            // added an Id to the ImageButton not compulsory
            _imgButton.ID = "imgBtnCheckAlias";

            // ImageButton Height is assigned to the ImageButton from the 
            // Property from UI like <asp:ImageButton  height="20"/>
            _imgButton.Height = ImageButtonHeight;

            // ImageButton Height is assigned to the ImageButton from the 
            // Property from UI like <asp:ImageButton  width="200"/>
            _imgButton.Width = ImageButtonWidth;

            // Here I am manually aligning the Image of Image Button to AbsMiddle
            _imgButton.ImageAlign = ImageAlign.AbsMiddle;

            // ImageButton URL is assigned to the ImageButton from the 
            // Property from UI like <asp:ImageButton  ImageURL="Image/CheckName.png"/>
            _imgButton.ImageUrl=ImageButtonURL;

            // On Click event of image button all the Domain Checking and Validation is done
            _imgButton.Click += new ImageClickEventHandler(_imgButton_Click);
            
            // here the text box and Image button Controls are added on the Main for work
            this.Controls.Add(_txtBoxAlias);
            this.Controls.Add(_imgButton);
        }

        /// <summary>
        /// It takes the textbox data and get the Alias by validating from Active Directory
        /// </summary>
        void _imgButton_Click(object sender, ImageClickEventArgs e)
        {
            if (_txtBoxAlias.Text.Trim().Length > 0)
            {
                // It holds all the Domain Name one by one from the Asp.net 
                // page where this Custom control is used for by adding the 
                // all the domain with comma separated and finally adding to its 
                // AlaisID.DomainNames property in .aspx or in .cs
                string[] domains;
                string[] allFullDomains;
                string strDomainNames = DomainNames;
                string userAlais;

                try
                {
                    // It checks if user has added the Domain or not or wrong domain
                    if (strDomainNames != string.Empty)
                    {
                        //splitting domains names by comma.
                        domains = DomainNames.Split(',');

                        // Keeps the Counts of no of domains
                        allFullDomains = new string[domains.Count()];

                        // takes the user v-Id or email id from UI
                        string userAlaisTrimed = _txtBoxAlias.Text.Trim();

                        // It checks if the user id have @ then it takes the left part 
                        // i.e the main id and assign to userAlais else simple assign it 
                        if (userAlaisTrimed.Contains('@'))
                        {
                            userAlais = userAlaisTrimed.Substring(0, userAlaisTrimed.IndexOf('@'));
                        }
                        else
                        {
                            userAlais = userAlaisTrimed;
                        }

                        // It checks holds the information whether the user id 
                        // is found in the doamin or not
                        bool isFoundUser = false;

                        // It checks if the domains are added or not
                        if (domains.ToString() != null)
                        {
                            // Travering or searching in each domain
                            for (int i = 0; i < domains.Count(); i++)
                            {
                                // combine the Domain name with the ADCONNECTION by getting from the 
                                // UI which is assigned by user to the DomainNames and ADCONNECTION properties
                                string domainName = domains[i] + "." + ADCONNECTION;

                                // domainContext holds the value whether domain is true or exist or not
                                using (var domainContext = new PrincipalContext(ContextType.Domain, domainName))
                                {
                                    // foundUser holds the user Information whether exist or not in that domain
                                    using (var foundUser = UserPrincipal.FindByIdentity(
                                      domainContext, IdentityType.SamAccountName, userAlais))
                                    {
                                        // If the User is exist then adding SamAccountName like 
                                        // "v-skfa@microfot.com" with Under line to the TextBox 
                                        // of UI and breaks and come out from the Loop 
                                        if (foundUser != null)
                                        {
                                            _txtBoxAlias.Text = string.Empty;
                                            _txtBoxAlias.Text = foundUser.EmailAddress;
                                            _txtBoxAlias.Font.Underline = true;
                                            isFoundUser = true;
                                            break;
                                        }
                                    }
                                }
                            }

                            // If user is not found in the Domain Then a message is 
                            // displayed in the same textbox with Red Underline that
                            // user doesnot exist in the Domain
                            if (isFoundUser == false)
                            {
                                _txtBoxAlias.Text = string.Empty;
                                _txtBoxAlias.Text = ".................";
                                _txtBoxAlias.ForeColor = System.Drawing.Color.Red;
                            }
                        }
                    }

                    // If the Domain is wrong or not not added with , or null
                    // then Shows a message in the TextBox that No Domain Exist
                    else
                    {
                        _txtBoxAlias.Text = "No Domain Exist";
                    }
                }
                catch (Exception)
                {
                    _txtBoxAlias.Text = "Wrong Domain Name";
                }
            }
        }

        /// <summary>
        /// It is to show the Changes on the Design window if user adds 
        /// any properties to that control
        /// </summary>
        protected override void RecreateChildControls()
        {
            EnsureChildControls();
        }

        /// <summary>
        /// It it to html Rendering of the Controls on the UI
        /// </summary>
        /// <param name="writer"></param>
        protected override void Render(HtmlTextWriter writer)
        {
            // to render the object on ui
            AddAttributesToRender(writer);

            // for spacing in table
            writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "1");

           // Begins the Render of Table
            writer.RenderBeginTag(HtmlTextWriterTag.Table);

            // Begins the Rendering to tr of the Table
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);

            // Begins the Rendering to td of the Table
            writer.RenderBeginTag(HtmlTextWriterTag.Td);

            // added control to the first td to render 
            _txtBoxAlias.RenderControl(writer);

            // Closing the Rendering of td
            writer.RenderEndTag();

            // Begins 2nd the Rendering to td of the Table
            writer.RenderBeginTag(HtmlTextWriterTag.Td);

            // added image control to the 2nd td to render 
            _imgButton.RenderControl(writer);

            // Closing the Rendering of 2nd td
            writer.RenderEndTag();

            // Closing the Rendering of tr
            writer.RenderEndTag();

            // Closing the Rendering of Table
            writer.RenderEndTag();
        }
    }
}

After creating a DLL you can use it. But those who want to a create a custom control can remove the below part from the main code. This part deals with checking the user in the Active Directory when the system is in the domain and does the work of user validation.

Remove the whole method of the image click:

void_imgButton_click(Object sender,ImageClickEventArgs e)
{
  //Body
}

Points of Interest

If you see the comments for each line you can definitely understand how to create a custom control and how it works and how to render the control on the browser using HTML rendering and you can do any mix of controls using this way.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Fayaz7Wonders
Software Developer
India India
No Biography provided
Group type: Organisation (No members)



Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.1411023.1 | Last Updated 19 Mar 2013
Article Copyright 2013 by Fayaz7Wonders
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid