Saturday, December 25, 2010

AJAX - AutoComplete Extender

AutoComplete is an ASP.NET AJAX extender that can be attached to any TextBox control, and will associate that control with a popup panel to display words that begin with the prefix typed into the textbox.

Let See how to apply AutoCompleteExtender to the textbox control in asp.net.In this example i will bind the list of country name to AutoComplete Extender for getting suggestion country name.

Step 1
Create a Country Table in Database,it is look like this









Step 2
Insert Data in country table,it is look like this


























Step 3
Add a new Website in the solution.

Step 4
Add a ToolkitScriptManager control from Ajax toolkit inside the Div Tag,it is look like this


<div>

         <asp:ToolkitScriptManager ID="ToolKitScriptManager1" runat="server">
         </asp:ToolkitScriptManager>
</div>

This control allows you to replace the default <asp:scriptmanager> control behavior, and supports the ability to dynamically merge multiple client-side Javascript scripts into a single file that is downloaded to the client at runtime. 

Step 5
Add a textbox control from toolbox and AutoComplete Extender from AjaxToolKit,it is look like this

<asp:TextBox ID="txtCountry" runat="server" ></asp:TextBox>
                
                <asp:AutoCompleteExtender ID="ACECountry" runat="server" 
                    TargetControlID="txtCountry" ServiceMethod="GetCompletionList" UseContextKey="True" 
                    MinimumPrefixLength="1" CompletionInterval="1" CompletionSetCount="20"  EnableCaching="true">
                    
                    </asp:AutoCompleteExtender>

There are the following basic properties of AutoComplete Extender:

1. TargetControlID
     The TextBox control where the user types content to be automatically completed.

2. ServiceMethod
     The name of the service method.

3. UseContextKey
     Whether or not the ContextKey property should be used. This will be automatically enabled if the ContextKey property is ever set (on either the client or the server). If the context key is used, it should have the same signature with an additional parameter named contextKey of type string (as described above). 

4. MinimumPrefixLength
     Minimum number of characters that must be entered before getting suggestions from the service method.

5. CompletionInterval
    Time in milliseconds when the timer will kick in to get suggestions from the service method.

6. CompletionSetCount
    Number of suggestions to be retrieved from the service method.

7. EnableCaching
    Whether client side caching is enabled.


Step 6
Add a Service method in code behind.Expanding the textbox control smart tag,select the add AutoComplete page method option from the provided menu.This action create a service method in code behind for your page,it is look like this














Click on image for better view.


Step 7
Add a ConnectionString in web.config file,it is look like this

<connectionStrings>
        <add name="ConStr" connectionString="Data Source=SHREE\SHREE;Initial Catalog=ABC;Integrated Security=True" providerName="System.Data.SqlClient"/>
    </connectionStrings>

Step 8
Get a country list from database,it is look like this

[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static string[] GetCompletionList(string prefixText, int count, string contextKey)
    {
        List<String> ListCountryName = new List<String>(); // List Object

        try
        {
            // Open the connection
            SqlConnection SqlCon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);
            SqlCon.Open();

            // Create a Command
            SqlCommand SqlComm = new SqlCommand();
            SqlComm.Connection = SqlCon;

            // Add a CountryName SQl Parameter
            SqlComm.Parameters.Add("@CountryName", SqlDbType.VarChar).Value = prefixText; // retrievable throught prefixText parameter

            // Query for get country name from database 
            SqlComm.CommandType = CommandType.Text;
            SqlComm.CommandText = "SELECT Country.CountryName FROM Country WHERE CountryName LIKE ''+@CountryName+'%' ";

            // Read the data and add in List object.
            SqlDataReader SqlDr = SqlComm.ExecuteReader(); 

            if (SqlDr != null)
            {
                while (SqlDr.Read())
                {
                    ListCountryName.Add(SqlDr["CountryName"].ToString());
                }
            } 
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }

        return ListCountryName.ToArray<String>();
    }

Run the project.





















Click on image for better view.


Download
Download Source Code

Monday, December 20, 2010

ASP.net - Count Online Visitor

In this article i will show you how to count online visitor in you'r website.

Step 1
Create a web application.

Step 2
Add a Global.asax file in a web project.Right click on the web application from solution explorer and select Add New Item,select Global.asax file from  installed Visual Studio templates.  

Step 3
In the Application_Start subroutine, we have to set the user count to 0, when the server starts the application,it is look like this



 void Application_Start(object sender, EventArgs e) 
    {
        try
        {
            // Set user count to 0 when start the web application. 
            Application["OnlineUsersCount"] = 0; 
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }

    }

Step 4
In the Session_Start subroutine, we have to increament the OnlineUsers by 1,it is look like this

 void Session_Start(object sender, EventArgs e) 
    {
        try
        {
            Application.Lock();
            Application["OnlineUsersCount"] = Convert.ToInt64(Application["OnlineUsersCount"]) + 1; // Increment online users by 1
            Application.UnLock(); 
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }

    }

This will allow us that whenever some distant web visitor opens our website in his browser, and new session is created for him, our  "OnlineUsersCount" variable in the global HttpApplicationState class instance is increased.

Step 5
we must decrement the number of Active Users on the basis of online sessions in the Session_End subroutine,it is look like this

void Session_End(object sender, EventArgs e) 
    {
        try
        {
            Application.Lock();
            Application["OnlineUsersCount"] = Convert.ToInt64(Application["OnlineUsersCount"]) - 1; // Decrement online users by 1
            Application.UnLock();  
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

when user closes his browser or does not click on any links in our website, session expires,and our "OnlineUsersCount" global variable is decreased.

Application.Lock() and Application.Unlock()
we are using Application.Lock() and Application.Unlock() methods to prevent multiple threads from changing this variable at the same time.

By calling Application.Lock() we are receiving exclusive right to change the values in Application state.But we must not forget to call Application.Unlock() afterwards.


Step 6
we need to enable sessionstate and configure its mode to InProc value in our web.config file,it is look like this


<system.web>
    <sessionState mode="InProc" cookieless="false" timeout="20"></sessionState>
</system.web>

In-process mode stores session state values and variables in memory on the local Web server.It is the only mode that supports the Session_OnEnd event that we used previously.

Timeout value configures how long our sessions are kept alive in other words
here we set how long our users can be inactive before considered Offline.

In this example timeout is set to 20 minutes, so while our visitors click on some links in our website at least once in a 20 minutes, they are considered online.


If they do not open any pages on our website longer than 20 minutes, they are considered Offline, and their session is destroyed, so our online visitor counter is decreased by 1.

The default Timeout is 20 minutes, so you can change it depending on the needs of your particular application.

Step 7
Add the following code in .aspx page for display online user count,it is look like this

<div>
        <%
            
            long OnlineUserCount = Convert.ToInt64(Application["OnlineUsersCount"]);
            Response.Write("Online Visitor Count : " + OnlineUserCount);     
            
         %>
    </div>

Run the project.

Download
Download Source Code

Sunday, December 19, 2010

LINQ - Retrive data from XML using Linq to XML

LINQ to XML provides an in-memory XML programming interface that leverages the .NET Language-Integrated Query (LINQ) Framework. LINQ to XML uses the latest .NET Framework language capabilities and is comparable to an updated, redesigned Document Object Model (DOM) XML programming interface.

LINQ to XML is a built-in LINQ data provider available in .NET 3.5. It is offered via the System.Xml.Linq namespace. LINQ to XML allows you to create, read, and write XML-based data. The XML data source may be a file, in-memory XML, or a remote resource accessed via protocols like HTTP.

Let see how to retrive data from xml.

Step 1
Create a web application and give the solution name as SolLinqToXMLRetriveData.

Step 2
In App_Data folder insert a XML file and give the file name as Student.xml.

Step 3
The XML in the following example defines an XML document with a root node called Students. This root node contains one or more nodes called Student that include elements called ID,FirstName,LastName and Location.


<?xml version="1.0" encoding="utf-8"?>
<Students>

  <Student>
    <ID>1</ID>
    <FirstName>Bhushan</FirstName>
    <LastName>Pawar</LastName>
    <Location>Thane</Location>
  </Student>

  <Student>
    <ID>2</ID>
    <FirstName>Ramdas</FirstName>
    <LastName>Bhosale</LastName>
    <Location>Thane</Location>
  </Student>
  
 <Student>
  <ID>3</ID>
  <FirstName>Kishor</FirstName>
  <LastName>Naik</LastName>
  <Location>Thane</Location>
 </Student>

  <Student>
    <ID>4</ID>
    <FirstName>Koste</FirstName>
    <LastName>Budinoski</LastName>
    <Location>Skopje</Location>
  </Student>

  <Student>
    <ID>5</ID>
    <FirstName>Bhavesh</FirstName>
    <LastName>Pisat</LastName>
    <Location>Thane</Location>
  </Student>


  <Student>
  <ID>6</ID>
  <FirstName>Kedar</FirstName>
  <LastName>Despande</LastName>
  <Location>Thane</Location>
 </Student>
 
</Students>

Step 4
Add a gridview on page for view the content of XML data,it is look like this

<asp:ScriptManager ID="ScriptManger1" runat="server">
        </asp:ScriptManager> 
    
        <asp:UpdatePanel ID="UpdatePanel" runat="server">
            <ContentTemplate>
                
                <asp:GridView ID="gvStudent" runat="server" BackColor="White" 
                    BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" 
                    EnableModelValidation="True" ForeColor="Black" GridLines="Vertical">
                    <AlternatingRowStyle BackColor="#CCCCCC" />
                    <FooterStyle BackColor="#CCCCCC" />
                    <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
                    <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
                </asp:GridView>

            </ContentTemplate>
        </asp:UpdatePanel>

Step 5
Create a StudentModel  class in App_Code folder.it is an entity class,it is look like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


public class StudentModel
{
    #region Constructor
    public StudentModel()
    {
    }
    #endregion

    #region Property

    public int ID
    {
        get;
        set;
    }

    public String FirstName
    {
        get;
        set;
    }

    public String LastName
    {
        get;
        set;
    }

    public String Location
    {
        get;
        set;
    }

    #endregion
}

Step 6
Create a StudentDAL static class in App_Code folder for retriving an Student data from XML,it is look like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;

/// <summary>
/// Retrive Data from XML file
/// </summary>
public static class StudentDAL
{
    #region Methods


    /// <summary>
    /// Get all Student Data from XML
    /// </summary>
    /// <returns>List</returns>
    public static List<StudentModel> GetAllStudentData()
    {
        try
        {
            // Load Xml Document
            XDocument XDoc = XDocument.Load(HttpContext.Current.Server.MapPath("~/App_Data/Student.xml"));

            // Query for retriving all Studnet data from XML
            var Query = (from Q in XDoc.Descendants("Student")
                         select new StudentModel
                         {
                             ID = Convert.ToInt32(Q.Element("ID").Value),
                             FirstName = Convert.ToString(Q.Element("FirstName").Value),
                             LastName = Convert.ToString(Q.Element("LastName").Value),
                             Location = Convert.ToString(Q.Element("Location").Value)
                         }
                           ).ToList<StudentModel>();

            return Query; 
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    /// <summary>
    /// Get Student data by FirstName
    /// </summary>
    /// <param name="FirstName">Specify First Name</param>
    /// <returns>List</returns>
    public static List<StudentModel> GetStudentDataByName(String FirstName)
    {
        try
        {
            // Load Xml Document
            XDocument XDoc = XDocument.Load(HttpContext.Current.Server.MapPath("~/App_Data/Student.xml"));

            // Query for retriving Student data from XML by given first name
            var Query = (from Q in XDoc.Descendants("Student")
                         where Q.Element("FirstName").Value == FirstName
                         select new StudentModel
                         {
                             ID = Convert.ToInt32(Q.Element("ID").Value),
                             FirstName = Convert.ToString(Q.Element("FirstName").Value),
                             LastName = Convert.ToString(Q.Element("LastName").Value),
                             Location = Convert.ToString(Q.Element("Location").Value)
                         }
                           ).ToList<StudentModel>();

            return Query;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    #endregion
}

Step 7
Bind the student data in gridview.it is look like this

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (IsPostBack == false)
            {
                BindAllStudentData(); // Bind All Student data in gridview

                //BindStudentDataByName("Kedar"); // Bind a Single Data.
            }
        }
        catch (Exception)
        { 
        }
    }

    #region Methods

    /// <summary>
    /// Bind All Student data in GridView
    /// </summary>
    private void BindAllStudentData()
    {
        try
        {
            List<StudentModel> ListStudentObj = StudentDAL.GetAllStudentData();

            if (ListStudentObj != null)
            {
                if (ListStudentObj.Count > 0)
                {
                    gvStudent.DataSource = ListStudentObj;
                    gvStudent.DataBind(); 
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    /// <summary>
    /// Bind Student data in grid view by given first name
    /// </summary>
    /// <param name="FirstName">Specify the First Name</param>
    private void BindStudentDataByName(String FirstName)
    {
        try
        {
            List<StudentModel> ListStudentObj = StudentDAL.GetStudentDataByName(FirstName);

            if (ListStudentObj != null)
            {
                if (ListStudentObj.Count > 0)
                {
                    gvStudent.DataSource = ListStudentObj;
                    gvStudent.DataBind(); 
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }
    #endregion
}

Run the project.

Download
Download Source Code

Many developers using LINQ to SQL over regular ADO.NET to work with backend databases; however, there are also a lot of developers who seem happy with the LINQ alternative to working with XML. LINQ to XML is a much simpler and often intuitive approach to XML data, and it is more efficient than using the DOM API via the XmlDocument object. It also brings a database-type approach to XML with the select,insert,update,delete, where, and from clauses for operation on data.

Friday, December 17, 2010

WPF - Text to Speech in WPF

In this article i will show you how to convert text into speech.

Let see the example.

Step 1
Create a WPF Application.

Step 2
Desing the application,it is look like this


<Window x:Class="TextToSpeech.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Text to Speech" Height="350" Width="525" Background="Gray" WindowStartupLocation="CenterScreen">
    
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="393*" />
            <ColumnDefinition Width="110*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="10*" />
            <RowDefinition Height="51*" />
            <RowDefinition Height="201*" />
            <RowDefinition Height="39*" />
            <RowDefinition Height="10*" />
        </Grid.RowDefinitions>
        
        <TextBox x:Name="txtFileName" IsReadOnly="True" Grid.Column="0" Grid.Row="1" Height="23" Margin="5,0"></TextBox>
        <Button x:Name="btnOpenFile" Content="Open" Grid.Column="1" Grid.Row="1" Height="40" Margin="5,0" Click="btnOpenFile_Click"></Button>
        
        <RichTextBox x:Name="rtxtContent" Grid.Column="0" Grid.Row="2" Grid.ColumnSpan="2" Margin="5,0" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"></RichTextBox>

        <Button x:Name="btnSpeech" Grid.Column="1" Grid.Row="3" Content="Voice"  Margin="5,5,5,0" Click="btnSpeech_Click"></Button>
    </Grid>
</Window>

Step 3

Add two assembly reference to the project.
  1. System.Window.Forms
  2. System.Speech
Right click on the project name in Solution Explorer, select Add Reference and select System.Window.Forms and System.Speech on the .NET Tab and select OK button.




Click on image for better view

Step 4
Create a FileHandling static class for open a file dialog box and you can open browse a text file. After that it reads the text file and opens it in the RichTextBox control,it is look like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace TextToSpeech
{
    public static class FileHandling
    {
        #region Methods

        /// <summary>
        /// Open file dialog box and open a file
        /// </summary>
        /// <returns>String</returns>
        public static String OpenFile()
        {
            String FileName = String.Empty;
            try
            {
                System.Windows.Forms.OpenFileDialog OFDObj = new System.Windows.Forms.OpenFileDialog();

                OFDObj.Filter = "Text files (*.txt)|*.txt";
                OFDObj.RestoreDirectory = true;

                if (OFDObj.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    FileName = OFDObj.FileName; // return full file path
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }

            return FileName;
        }

        /// <summary>
        ///  Load Contents of file into RichText Box control
        /// </summary>
        /// <param name="FilePath">Specify the File Path</param>
        /// <param name="RichTextBoxObj">Specify RichTextBox Control Object</param>
        public static void LoadFile(String FilePath,System.Windows.Controls.RichTextBox RichTextBoxObj)
        {
            try
            {

                System.Windows.Documents.TextRange Range=null;

                System.IO.FileStream fStream = null; ;

                if (System.IO.File.Exists(FilePath))
                {

                    Range = new System.Windows.Documents.TextRange(RichTextBoxObj.Document.ContentStart, RichTextBoxObj.Document.ContentEnd);

                    fStream = new System.IO.FileStream(FilePath, System.IO.FileMode.OpenOrCreate);

                    Range.Load(fStream, System.Windows.DataFormats.Text);

                    fStream.Close();

                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

        /// <summary>
        ///  Convert Rich text box contents into String
        /// </summary>
        /// <param name="RichTextBoxObj">Specify RichTextBox Control Object</param>
        /// <returns>String</returns>
        public static String ConvertRichTextBoxToString(System.Windows.Controls.RichTextBox RichTextBoxObj)
        {
            try
            {
                System.Windows.Documents.TextRange Range = new System.Windows.Documents.TextRange(RichTextBoxObj.Document.ContentStart,RichTextBoxObj.Document.ContentEnd);

                return Range.Text;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

        #endregion

        
    }
}


Step 5
Create a TextToSpeechLib static class for convert text into speech,it is look like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Speech.Synthesis;

namespace TextToSpeech
{
    public static class TextToSpeechLib
    {
        #region Declaration

        private static SpeechSynthesizer Speech = null;

        #endregion

        #region Methods

        /// <summary>
        ///  Speak the Specified Text
        /// </summary>
        /// <param name="Text">Specify the Contents</param>
        public static void Voice(String Text)
        {
            try
            {
                Speech = new SpeechSynthesizer();
                Speech.SpeakAsync(Text); 
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

        /// <summary>
        /// Pause the voice
        /// </summary>
        public static void VoicePause()
        {
            try
            {
                Speech.Pause(); 
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

        /// <summary>
        /// Resume the voice
        /// </summary>
        public static void VoiceResume()
        {
            try
            {
                Speech.Resume(); 
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

        #endregion
    }
}

Step 6
Add the below code in btnOpen button click event handler.it is look like this

private void btnOpenFile_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                txtFileName.Text = FileHandling.OpenFile(); // open a file.
 
                if(txtFileName.Text !=String.Empty)
                {
                    FileHandling.LoadFile(txtFileName.Text, rtxtContent); // load the file contents into RichTextBox Control
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);   
            }
        }

Step 7
Add the below code in btnSpeech button click event handler.it is look like this

 private void btnSpeech_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                String Text = FileHandling.ConvertRichTextBoxToString(rtxtContent);

                if (Text.Trim()!=String.Empty ) 
                {
                    switch (btnSpeech.Content.ToString())
                    {
                        case "Voice": // Speak the specified text

                            TextToSpeechLib.Voice(Text);
                            btnSpeech.Content = "Pause";

                            break;

                        case "Pause": // Pause the voice

                            TextToSpeechLib.VoicePause();
                            btnSpeech.Content = "Resume";
                            break;

                        case "Resume": // Resume the voice

                            TextToSpeechLib.VoiceResume();
                            btnSpeech.Content = "Pause";

                            break;
                    }
                }
                else
                {
                    MessageBox.Show("Content is blank");  
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);  
            }
        }


Run the project.

Download
Download Source Code

Wednesday, December 15, 2010

C#.net - Generic in C#.net

What is Generic?

C# Generics is feature of the runtime. They are basically the capacity to have type parameters lying on your type. Generics refer to classes and methods that work homogeneously on values of different types. They are a type of data structure that contains code that remains the same; though, the data type of the parameters can change with each use. We can also call them parameterized types or parametric polymorphism.

The usage of generics within the data structure adjusts to the different data type of the passed variables. Briefly, a generic is a code template that can be applied to use the same code over and over again. Whenever the generic is used, it can be adapted for different data types without require to rewrite any of the internal code.

Why Generics?
  • Generics let us to specify our Type at runtime. you can create a collection that is type-safe at compile-time.
  • Gives no boxing, no casting advantage.
  • Both the casting and the boxing and unboxing operations degrade performance.
  • Use of list collection as their new type not as objects.
  • Binary code reuse
  • Code clearness with generics is another advantage.
Let us take an example of creating Generic collection using the simple example below. Requirement is to create the collection of Teaching Staff and NonTeaching Staff.

Step 1
Create a Console Application and give the name as ConGenericClass.

Step 2
Create a TeachingStaff class in the solution,it is look like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConGenericClass
{
    public class TeachingStaff
    {
        #region Constructor

        /// <summary>
        /// Blank Constructor
        /// </summary>
        public TeachingStaff()
        { 
        
        }

        /// <summary>
        /// Add Teaching Staff Data
        /// </summary>
        /// <param name="FirstName">Specify First Name</param>
        /// <param name="LastName">Specify Last Name</param>
        /// <param name="Age">Specify Age</param>
        public TeachingStaff(String FirstName,String LastName,int Age)
        {
            try
            {
                this.FirstName = FirstName;
                this.LastName = LastName;
                this.Age = Age;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

        #endregion

        #region Property

        public String FirstName
        {
            get;
            set;
        }

        public String LastName
        {
            get;
            set;
        }

        public int Age
        {
            get;
            set;
        }
        #endregion
    }
}

Step 3
Create a NonTeachingStaff class in solution,it is look like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConGenericClass
{
    public class NonTeachingStaff
    {
        #region Constructor

        /// <summary>
        /// Blank constructor
        /// </summary>
        public NonTeachingStaff()
        { 
        }

        /// <summary>
        /// Add Non Teaching Staff Data
        /// </summary>
        /// <param name="FirstName">Specify First Name</param>
        /// <param name="LastName">Specify Last Name</param>
        /// <param name="Age">Specify Age</param>
        public NonTeachingStaff(String FirstName, String LastName, int Age)
        {
            try
            {
                this.FirstName = FirstName;
                this.LastName = LastName;
                this.Age = Age;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }
        #endregion

        #region Property

        public String FirstName
        {
            get;
            set;
        }

        public String LastName
        {
            get;
            set;
        }

        public int Age
        {
            get;
            set;
        }

        #endregion
    }
}

Step 4
Now create a Generic teacher class which can hold the collection of either Teaching staff data or Non Teaching Staff Data.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConGenericClass
{
    public class Teacher<T>:IEnumerable<T>
    {
      
        #region Declaration

        private List<T> ListObj = new List<T>(); // Create a object List Class

        #endregion

        #region Methods

        /// <summary>
        /// Add Data in List Object
        /// </summary>
        /// <param name="TObj"></param>
        public void Add(T TObj)
        {
            try
            {
                ListObj.Add(TObj); // Add data in List  
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

      

        #endregion


        #region IEnumerable Methods

        public IEnumerator<T> GetEnumerator()
        {
                foreach (T TObj in ListObj)
                {
                    yield return TObj; 
                }
           
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            try
            {
                return GetEnumerator(); 
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

        #endregion
    }
}

Naming Guideline
  • Generic type name should be prefixed with letter T.
  • If the generic type can be replaced by any class because there no special requirement and only one generic type is used,the character T is good as generic type name:
    • public class List<T>
Implement IEnumerable<T> interface
Exposes the enumerator, which supports a simple iteration over a collection of a specified type.
Enumerates through a collection using a foreach statement.

Step 5
Now we can use the Generic teacher collection to hold either the teaching staff data or non teaching staff data collections.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConGenericClass
{

    class Program
    {
        static void Main(string[] args)
        {
            #region Add Data

                #region Teaching Staff Data
            
                    Teacher<TeachingStaff> TeachingStaffObj = new Teacher<TeachingStaff>();
            
                    TeachingStaffObj.Add(new TeachingStaff("Kishor", "Naik", 24));
                    TeachingStaffObj.Add(new TeachingStaff("Bhavesh", "Pisat", 24));

                #endregion

                #region Non Teaching Staff Data

                    Teacher<NonTeachingStaff> NonTeachingStaff = new Teacher<NonTeachingStaff>();

                    NonTeachingStaff.Add(new NonTeachingStaff("Ramdas", "Bhosale", 25));
                    NonTeachingStaff.Add(new NonTeachingStaff("Bhushan", "Pawar", 27));

                #endregion

            #endregion

            #region Print Data

                #region Print Teaching Staff Data

                        System.Console.WriteLine("Teaching Staff Data");

                        System.Console.WriteLine("FirstName\t LastName\t Age");
                        System.Console.WriteLine();
 
                        foreach (TeachingStaff TS in TeachingStaffObj)
                        {
                            System.Console.Write(TS.FirstName+"\t\t "+TS.LastName+"\t\t "+TS.Age);
                            System.Console.WriteLine(); 
                        }
                        System.Console.WriteLine("\n\n");  

                #endregion

                #region Print Non Teaching Staff Data

                        System.Console.WriteLine("Non Teaching Staff Data");

                        System.Console.WriteLine("FirstName\t LastName\t Age");
                        System.Console.WriteLine();

                        foreach (NonTeachingStaff NTS in NonTeachingStaff)
                        {
                            System.Console.Write(NTS.FirstName + "\t\t " + NTS.LastName + "\t\t " + NTS.Age);
                            System.Console.WriteLine(); 
                        }
                        

                #endregion

            #endregion


        }
    }
}


Run the project.

Download
Download Source Code

Thursday, December 9, 2010

MS-SQL - Get the first character in each word

The below function will get the string as input and will give each and every character in starting of the words.

Step 1
Create a user defined GetFirstCharacter function,it is look like this
 

CREATE FUNCTION dbo.GetFirstCharacter(@StringValue nvarchar(max))
RETURNS nvarchar(max)
AS
    BEGIN
    
        DECLARE @FirstChar nvarchar(10) -- get the first character
        DECLARE @StringValueLength int -- length of given string
        DECLARE @Index int  -- Set Start Index of while loop
        DECLARE @Flag bit  -- Check for Blank Space
    
    
        SET @StringValueLength=LEN(@StringValue) -- get lenght of given string
        SET @Index=1 
        SET @Flag=0  
    
        IF ((@StringValue IS NOT NULL) AND (@StringValue<>''))
            BEGIN
                    -- get the first charcter of the first word
                    SET @FirstChar=LEFT(@StringValue,1) 
                    
                    -- get each character by using while loop
                    WHILE (@Index<=@StringValueLength)
                        BEGIN
                            
                            -- Check the blank space 
                            IF(SUBSTRING(@StringValue,@Index,1) = ' ')
                                BEGIN
                                    SET @Flag=1
                                END
                            ELSE
                                BEGIN 
                                    SET @Flag=0
                                END
                            
                            
                            IF(@Flag=1)
                                BEGIN
                                             -- increment the index after the blank space
                                            SET @Index=@Index+1
                                            
                                            -- Get the each character from each word
                                            SET @FirstChar = @FirstChar + SUBSTRING(@StringValue,@Index,1)
                                        
                                        
                                END
                            
                            SET @Index=@Index+1  -- While Counter
                        END
            END 
    
        RETURN @FirstChar -- return the value
    
    END

Step 2
Call a user defined GetFirstCharacter function,it is look like this

SELECT dbo.GetFirstCharacter('Yogesh Naik') AS 'First character of the each word'


Download
Download Sql Script