HashTable in C#.net


The Hashtable class implement the IDictionary interface. Therefore, each element in this collection is a key-and-value pair.
it is a collection class like an arraylist but stores the value in name,value or key,value based. arraylist also stores values in key,value pairs only where index is the key which is predefined.

hashtable
in case of hashtable these keys can be userdefined which can be specified by us explicitely as per our requirement…
A Hashtable object consists of buckets that contain the elements of the collection. A bucket is a virtual subgroup of elements within the Hashtable, which makes searching and retrieving easier and faster than in most collections. Each bucket is associated with a hash code, which is generated using a hash function and is based on the key of the element.

Hashtable should not allow Duplicate Keys, but allows Duplicate Values

Examples in Console Application:

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

namespace HashtableExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable ht_Employee = new Hashtable();
            
            //Adding Elements To HashTable
            ht_Employee.Add("EmpId", 100);
            ht_Employee.Add("EmpName", "Scott");
            ht_Employee.Add("Job", "programmer");
            ht_Employee.Add("Sal", 5000.00);
            ht_Employee.Add("Dept", "IT");
            ht_Employee.Add("Loc", "Hyderabad");

            //Displaying values in hashtable ht_employee
            Console.WriteLine("We Can display Hashtable Data in different Types of Logics");
            Console.WriteLine();
            Console.WriteLine("================================");
            Console.WriteLine("Logic Type:1 If u don't know keys");
            Console.WriteLine("================================");
            foreach (DictionaryEntry de in ht_Employee)
            {
                Console.Write(de.Key + "\t:");
                Console.WriteLine(de.Value);
            }
            
            Console.WriteLine("================================");
            Console.WriteLine("Logic Type:3 If u know keys");
            Console.WriteLine("================================");
            Console.Write("EmpId" + "\t:");
            Console.WriteLine(ht_Employee["EmpId"]);
            Console.Write("EmpName" + "\t:");
            Console.WriteLine(ht_Employee["EmpName"]);
            Console.Write("Job" + "\t:");
            Console.WriteLine(ht_Employee["Job"]);
            Console.Write("Sal" + "\t:");
            Console.WriteLine(ht_Employee["Sal"]);
            Console.Write("Dept" + "\t:");
            Console.WriteLine(ht_Employee["Dept"]);
            Console.Write("Loc" + "\t:");
            Console.WriteLine(ht_Employee["Loc"]);

            Console.WriteLine("================================");
            Console.WriteLine("Logic Type:2 If u don't know keys");
            Console.WriteLine("================================");
            foreach (DictionaryEntry de in ht_Employee)
            {
                Console.Write(de.Key + "\t:");
                Console.WriteLine(ht_Employee[de.Key]);
            }
            Console.Read();
        }
    }
}

Output:

HashTableConsole

 

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

namespace Hashtable1
{
    class HashTableExtentions
    {
        static void Main(string[] args)
        {
            Hashtable ht_Employee = new Hashtable();

            //Adding Elements To HashTable
            ht_Employee.Add("EmpId", 100);
            ht_Employee.Add("EmpName", "Scott");
            ht_Employee.Add("Job", "programmer");
            ht_Employee.Add("Sal", 5000.00);
            ht_Employee.Add("Dept", "IT");
            ht_Employee.Add("Loc", "Hyderabad");

            //If We add Existed key to hashtable it raises exception
            Console.WriteLine("==============================================================");
            Console.WriteLine("Add method Raise exception if new key is already in Hashtable");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            try
            {
                ht_Employee.Add("EmpId", 1000);
            }
            catch
            {
                Console.WriteLine("An element with Key = \"EmpId\" already exists.");
            }
            Console.WriteLine();

            //If we want to display values in discriptive manner
            Console.WriteLine("==============================================================");
            Console.WriteLine("If we want to display values in discriptive manner");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            Console.WriteLine("For key = \"EmpId\", value = {0}.", ht_Employee["EmpId"]);
            Console.WriteLine();

            //How to change values associated with keys in hashtable
            Console.WriteLine("==============================================================");
            Console.WriteLine("If we want to display values in discriptive manner");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            Console.WriteLine("For key = \"EmpId\", Oldvalue = {0}.", ht_Employee["EmpId"]);
            ht_Employee["EmpId"] = 101;
            Console.WriteLine("For key = \"EmpId\", Newvalue = {0}.", ht_Employee["EmpId"]);
            Console.WriteLine();
            Console.Read();

        }
    }
}

 

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

namespace Hashtable1
{
    class HashTableExtentions2
    {
        static void Main(string[] args)
        {
            Hashtable ht_Employee = new Hashtable();

            //Adding Elements To HashTable
            ht_Employee.Add("EmpId", 100);
            ht_Employee.Add("EmpName", "Scott");
            ht_Employee.Add("Job", "programmer");
            ht_Employee.Add("Sal", 5000.00);
            ht_Employee.Add("Dept", "IT");
            ht_Employee.Add("Loc", "Hyderabad");

            //if we don't know wether the key is exist or not… we need to check and use that key
            //for this
            Console.WriteLine("==============================================================");
            Console.WriteLine("Checking wether key is exist or not");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            if (ht_Employee.ContainsKey("EmpName"))
            {
                Console.WriteLine("Value Exist for key = \"EmpName\": {0}", ht_Employee["EmpName"]);
            }
            Console.WriteLine();
            if(!ht_Employee.ContainsKey("SomeName"))
            {
                Console.WriteLine("Value Doesn't Exist for key = \"SomeName\"");
            }
            Console.WriteLine();
            Console.WriteLine("==============================================================");
            Console.WriteLine("Adding Value for SomeName key");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            if (!ht_Employee.ContainsKey("SomeName"))
            {
                ht_Employee.Add("SomeName", "Raju");
                Console.WriteLine("Value Exist for key = \"SomeName\": {0}", ht_Employee["SomeName"]);
            }
            Console.WriteLine();

            //To get the values only, use the Values property.
            ICollection valueColl = ht_Employee.Values;

            //Print values in valueColl using foreach loop
            Console.WriteLine();
            Console.WriteLine("==============================================================");
            Console.WriteLine("Print values in valueColl using foreach loop");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            foreach (object s in valueColl)
            {
                Console.WriteLine("Value = {0}", s);
            }

            //To get the keys only, use the Keys property.
            ICollection keyColl = ht_Employee.Keys;

            //Print keys in keyColl using foreach loop
            Console.WriteLine();
            Console.WriteLine("==============================================================");
            Console.WriteLine("Print keys in keyColl using foreach loop");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            foreach (object s in keyColl)
            {
                Console.WriteLine("Key = {0}", ht_Employee[s]);
            }

            // Use the Remove method to remove a key/value pair.
            Console.WriteLine("\nRemove(\"SomeName\")");
            ht_Employee.Remove("SomeName");

            if (!ht_Employee.ContainsKey("SomeName"))
            {
                Console.WriteLine("Key \"SomeName\" is not found.");
            }
                
            Console.Read();
        }
    }
}

Asp.net TextBox post-back on each character entry


In This post I am going to Explain How to send a Request to asp.net server on every character entry in textbox control…

for this i am preparing a custom control with above functionality… named as PostBackTextBox..

First Take a Class Library Project and Delete Existing Classes then Add one class with name PostBackTextBox

Add System.Web Reference

Add System.Web Reference

and write the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
[assembly: WebResource("PostBackTextBox.Scripts.PostBackTextBox.js", "text/javascript")]
namespace PostBackTextBox
{
    [Description("PostBackTextbox")]
    [ToolboxData(@"<{0}:PostBackTextBox Text="""" AutoPostBack=""true"" runat=""server""></{0}:PostBackTextBox>")]
     public class PostBackTextBox : System.Web.UI.WebControls.TextBox
    {
            public override string Text
            {
                get
                {
                    return base.Text;
                }
                set
                {
                    base.Text = value;

                    Attributes["value"] = value;
                }
            }
            public override bool AutoPostBack
            {
                get
                {
                    return true;
                }
                set
                {
                    base.AutoPostBack = true;
                }
            }
            protected override void AddAttributesToRender(HtmlTextWriter writer)
            {
                writer.AddAttribute("onkeyup", "Refresh(this.id);");
                writer.AddAttribute("onfocus", "SetCursorToTextEnd(this.id);");
                base.AddAttributesToRender(writer);
            }

            protected override void OnPreRender(EventArgs e)
            {
                base.OnPreRender(e);
                Attributes["value"] = Text;
                ClientScriptManager cs = this.Page.ClientScript;
                cs.RegisterClientScriptInclude("PBTBScript", cs.GetWebResourceUrl(this.GetType(), "PostBackTextBox.Scripts.PostBackTextBox.js"));
            }
        }
    }

and add one Folder with name Scripts and add one script file and set the script file properties as Build action is Embedded Resource

GoTo Script File Properties

Select Build Action As Embedded Resource

and add following code in script file

function Refresh(textControlID1) {
    __doPostBack(textControlID1, '');
};
function SetCursorToTextEnd(textControlID) {
    var text = document.getElementById(textControlID);
    if (text != null && text.value.length > 0) {
        if (text.createTextRange) {
            var range = text.createTextRange();
            range.moveStart('character', text.value.length);
            range.collapse();
            range.select();
        }
        else if (text.setSelectionRange) {
            var textLength = text.value.length;
            text.setSelectionRange(textLength, textLength);
        }
    }
}

DownLoadSampleCode

How to create DataTable and add primary key to DataTable in asp.net


Creating DataTable:
//create inatance of datatable
DataTable dt = new DataTable();
//give datatable name to dt
dt.TableName = "MyTable";
//add columns to datatable dt
dt.Columns.Add("ImgPath", typeof(string));
//creating primary key column
DataColumn[] Key = new DataColumn[1];
DataColumn col = new DataColumn();
//setting datatype to column
col.DataType = System.Type.GetType("System.String");
//giving column name
col.ColumnName = "Name";
//adding column to datatable dt
dt.Columns.Add(col);
Key[0] = col;
// adding other columns to datatable directly
dt.Columns.Add("Desc", typeof(string));
dt.Columns.Add("Price", typeof(string));
//setting primary key to datatable
dt.PrimaryKey = Key;

 

Adding Data to Created DataTable:

//creating new data row
DataRow dr = dt.NewRow();
//adding data to the above created datarow
dr[0] = "ImgPath";
dr[1] = "Name";
dr[2] = "Desc";
dr[3] = "123.45";
//adding datarow to datatable
dt.Rows.Add(dr);

How to apply distinct Method on particular column in LINQ


Sometimes we need to select two or more columns based on one column distinct
in this situation if we have one primary column and one columns allows duplicates so now we want to read these two columns based on column which allow duplicates… in this situation if we apply Distinct method it will takes records based on primary key column, it won’t read based on other column…
To do that….follows these steps…

first create one method for DistinctBy

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector)
        {
            var set = new HashSet<TKey>();
            return source.Where(element => set.Add(selector(element)));
        }

and use this method to do Distinct based on Particular column…

var x = (from n in context.tblEmployees.Where(i => i.EMPLOYEE_ID == EmployeeId) select n).DistinctBy(i => i.EmployeeName).ToList();

Thanks…

……………HappyCoding……….

LINQ: Sequence Contains No Elements:First()


LINQ: Sequence Contains No Elements:

The InvalidOperationException:Sequence contains no lelments exception will occur whenever we will try to retrive data from table in database doesn’t contain no elements… so whenever we are trying to get data it does not match our query, this error will occur.

 What is First() in Linq:

Whenever we want to select first record only from list of records we will use this first() method as follows

Var x = (from n in Contextorentity.TableName select n).first();

If we want to select last record only from list of records we will use Last() method as follows

Var x = (from n in Contextorentity.TableName select n).first();

Without where Condition:

 var x = (from n in Contextorentity.TableName select n).first();

if the above select query contains no records in it it will return error like sequence contain no elements

with where condition:

if we are using any where condition in our query as follows

var x = (from n in Contextorentity.Employee where n.EmpId == 100  select n).first();

if no record matches with this query it returns error because the first method should select single record from list only, so if no list founds it will returns error.

Remidy:

We have solution for this error in linq only that is,

Instead of using First() method we can use FirstOrDefault() method.

What is FirstOrDefault() Method:

Firstordefault() method will also select single record from list of records, if no records found it will returns null value, so error won’t come…

 

Thanks

………………..Happy Coding………………….

How to call WCF Services in AJAX


JavaScript can communicate with services in JSON(JavaScript Object Notation) format. JSON is the best serialization format in performance and preferred wherever possible because of this fact. WCF supports JSON format because of which its services can be accessed by any AJAX clients.

To make a WCF service AJAX-enabled, we can use the WebServiceHostFactory class in ServiceHost directive of the .svc file or else create an ajax endpoint with WebHttpBinding and configure it accordingly.

In VS.NET, creating AJAX-enabled WCF Service is really made easy by providing a separate template for the purpose. When we use this template VS.NET takes care of configuring the right endpoints and behaviours. It creates a new system.serviceModel tag in web.config for this purpose. Moreover, all the parameters and results are serialized in JSON format when this template is used.

Demo:

In this demo we create an Ajax-enabled WCF service and consume it from ASP.NET AJAX.

Our aim in this program is to show that when we input a country name in the text box and press the html button, it should fetch the details of that country from the WCF service and display them to the user. For this we need to create a AJAX-enabled WCF service as we are interacting with the service through JavaScript. The steps for our demo are as follows:

First Create DataBase and add table as follows

Then Enter Data into table as follows:

1. Start a website normally and create the forms and databases as required.

Here we design a form with a html texbox and button to input the Player name. The results will be displayed in the provided label and image html controls.

The form looks as given below:

2. For our service we’ll use EDM for accessing data from SQL Database. We have a database called Countries from which we need to get details from Images table. To create an Entity Data Model right click the project in Solution Explorer and select Add New Item ADO.NET Entity Data Model and give name as CountriesModel. Then select Generate from Database option and choose the required database. In the final step choose the tables you want the data from. In

our demo we have selected Images from Countries database. This step will create an object of our table in the program. The advantage of usingentities here is that they are automatically serialized and there is no need of using [DataContract] attribute for them.

3. Now we’ll create a WCF service which retrieves the data and provides to the clients. For this again from Add New Item, choose AJAX-enabled WCF Service and name it as CountriesService.

This step will create a .svc file which is needed for our service get hosted in IIS. It will also create endpoints for the service with WebHttpBinding and its behaviours. This can be seen in web.config file as follows:

4. Along with .svc file, by default a .cs file with the same is created in App_Code folder to write the code. In this file we write methods necessary to get data from the Entities.

Whatever methods need to be exposed to the client should be decorated with [OperationContract] attributes.

We write the following method in our service:

[OperationContract]
    public List<string> GetData(string name)
    {
        MySampleDBModel.MySampleDBEntities obj = new MySampleDBModel.MySampleDBEntities();
        var x = (from n in obj.Images where n.PlayerName == name select n).FirstOrDefault();
        List<string> str = new List<string>();
        if (x != null)
        {
            str.Add(x.PlayerName);
            str.Add(x.CountryName);
            str.Add(x.Play);
            str.Add(x.ImagePath);
            return str;
        }
        else
            return null;
    }

This method gets the details of a given country from the created entities and returns in the form of a list.

Now the WCF service is ready and all that is remaining is to consume it from our web form using JavaScript which can interact with the service asynchronously.

5. For consuming, write the following code in the page source:

function Button1_onclick() {
            Service.GetData($get("Text1").value, f1, f2);
        }
        function f1(res) {
            if (res != null) {
                $get("Label1").innerHTML = res[0];
                $get("Label2").innerHTML = res[1];
                $get("Label3").innerHTML = res[2];
                var img = document.getElementById("image1");
                img.src = res[3];
            }
            else {
                alert("Details for this Player don't exist in our database");
            }
        }
        function f2() {
            alert("Error in processing.. Please try again!!");
        }

Now let’s try to understand this script. For this we should know what controls are placed in the form. Removing table formatting, the source view of the controls is shown below:

  1. <div>
  2. <asp:ScriptManager ID="ScriptManager1" runat="server">
  3. <Services>
  4. <asp:ServiceReference Path="~/Service.svc" />
  5. </Services>
  6. </asp:ScriptManager>
  7. </div>
  8. </form>
  9. <table>
  10. <tr>
  11. <td>
  12. &nbsp;</td>
  13. <td style="background-color: #99CCFF; font-weight: bold;">
  14. <input id="Text1" type="text" /><input id="Button1" type="button"
  15. value="Submit" onclick="return Button1_onclick()" /></td>
  16. <td>
  17. &nbsp;</td>
  18. </tr>
  19. <tr>
  20. <td>
  21. &nbsp;</td>
  22. <td style="background-color: #99CCFF; font-weight: bold;">
  23. PlayerName:<label id="Label1" ></label></td>
  24. <td>
  25. &nbsp;</td>
  26. </tr>
  27. <tr>
  28. <td>
  29. &nbsp;</td>
  30. <td style="background-color: #99CCFF; font-weight: bold;">
  31. PlayerCountry:<label id="Label2"></label></td>
  32. <td>
  33. &nbsp;</td>
  34. </tr>
  35. <tr>
  36. <td>
  37. &nbsp;</td>
  38. <td style="background-color: #99CCFF; font-weight: bold;">
  39. Play:<label id="Label3"></label></td>
  40. <td>
  41. &nbsp;</td>
  42. </tr>
  43. <tr>
  44. <td>
  45. &nbsp;</td>
  46. <td style="background-color: #99CCFF; font-weight: bold;">
  47. Image:<img alt="" src="" id="image1" /></td>
  48. <td>
  49. &nbsp;</td>
  50. </tr>
  51. </table>

When the button is clicked the code in function Btn_Click() is executed. The WCF service is called in that function. To call a service, a ScriptManager is needed which creates the needed proxy to interact with the service. The Service Reference should be provided in ScriptManager as follows:

  1. <asp:ScriptManager ID="ScriptManager1" runat="server">
  2. <Services>
  3. <asp:ServiceReference Path="~/Service.svc" />
  4. </Services>
  5. </asp:ScriptManager>

 

When the service reference is assigned and the program is compiled, it will create a proxy in JavaScript, through which the function interacts with the service. The following line in Btn_Click function is mainly responsible for providing the result.

  1. Service.GetData($get("Text1").value, f1, f2);

Country.value is the parameter i.e. country name that we are passing to the method. Success and failure are the parameters which represent the functions that are called respectively when the method is executed successfully or failed.

The parameter x passed in the function success(x) is the result obtained from the method GetDetails(). This result is assigned to relevant controls in this function. When the method fails to execute properly, the function failure() is called.

The final result is as shown in the screenshot below:

DOWNLOADSAMPLECODE

How to crate datatable and add primary key to datatable in asp.net


Creating DataTable:

//create inatance of datatable
DataTable dt = new DataTable();
//give datatable name to dt
dt.TableName = “MyTable”;
//add columns to datatable dt
dt.Columns.Add(“ImgPath”, typeof(string));
//creating primary key column
DataColumn[] Key = new DataColumn[1];
DataColumn col = new DataColumn();
//setting datatype to column
col.DataType = System.Type.GetType(“System.String”);
//giving column name
col.ColumnName = “Name”;
//adding column to datatable dt
dt.Columns.Add(col);
Key[0] = col;
// adding other columns to datatable directly
dt.Columns.Add(“Desc”, typeof(string));
dt.Columns.Add(“Price”, typeof(string));
//setting primary key to datatable
dt.PrimaryKey = Key;

Adding Data to Created DataTable:

//creating new data row
DataRow dr = dt.NewRow();
//adding data to the above created datarow
dr[0] = “ImgPath”;
dr[1] = “Name”;
dr[2] = “Desc”;
dr[3] = “123.45”;
//adding datarow to datatable
dt.Rows.Add(dr);