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();
        }
    }
}

Advertisements

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 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);

How to create Dynamic Openfiledialog to select image and bind it to image control in wpf


First take a WPF new project application

and design form as follows:

XAML Code:
<Window x:Class="DynamicFileUpLoad.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
Title="MainWindow" Height="350" Width="525">
    <Grid>
        <GroupBox Header="OpenfileDialog" Height="287" HorizontalAlignment="Left" Margin="12,12,0,0" Name="groupBox1" VerticalAlignment="Top" Width="479" FontWeight="Bold" FontSize="15">
            <Grid>
                <Image Height="251" HorizontalAlignment="Left" Margin="6,6,2,2" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="249" />
                <Button Content="BrowseImage" Height="35" HorizontalAlignment="Left" Margin="304,97,0,0" Name="BtnBrowse" VerticalAlignment="Top" Width="121" Click="BtnBrowse_Click" />
            </Grid>
        </GroupBox>
    </Grid>
</Window>

NameSpace:
using Microsoft.Win32;

CodeBehind(Under ButtonClick Event):
private void BtnBrowse_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OpenFileDialog opnfdl = new OpenFileDialog();
                opnfdl.InitialDirectory = "My Documents";
                opnfdl.Title = "SelectFile";
                opnfdl.DefaultExt = ".jpg";
                opnfdl.Filter = "All Image files|*.jpg";
                if (opnfdl.ShowDialog() == true)
                {
                    image1.Source = new BitmapImage(new Uri(opnfdl.FileName));
                }
            }
            catch (Exception errorMsg)
            {
                MessageBox.Show(errorMsg.Message);
            }
        }

You Can Get Output like this:

DownloadSampleCode

How to call wcf service from wpf client


DataBaseDesign:

First create database with name MySampleDB and create table as follows with name UserDetails

then add data to table as follows:

WCFService Creation:

First go to file newproject–>wcfservicelibrary

Then add required service files as follows

1. interface class

2.Class Implementing InterFace

3.UserDefinedClasses(if any used)

Write following code in Userdefined Class:

Write this code in Interface Class:

Then Write Following Code in Class implementing Interface

After Completion of creating service run the application

now service will hosted check service is hosted of no as follows

After completion of service hosting you can get the following window

To check wether your service is running or not call the service methods in

wcftestclient window as follows

Now your service is Hosted successfully.

Now prepare client as follows

WPFClient:

Open new visualstudio go to file–> new Project–>wpfclient

Design wpfclient as follows

This is the code for above window design

  1. <Window x:Class="WpfClient.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
  4. Title="MainWindow" Height="500" Width="800">
  5.     <Grid>
  6.         <GroupBox Header="Details" Height="361" HorizontalAlignment="Left" Margin="500,27,0,0" Name="groupBox1" VerticalAlignment="Top" Width="266">
  7.             <Grid>
  8.                 <Label Content="EnterID:" Height="28" HorizontalAlignment="Left" Margin="16,17,0,0" Name="label1" VerticalAlignment="Top" FontWeight="Bold" FontSize="16" />
  9.                 <Label Content="UserID:" FontSize="16" FontWeight="Bold" Height="28" HorizontalAlignment="Left" Margin="16,122,0,0" Name="label2" VerticalAlignment="Top" />
  10.                 <Label Content="UserName:" FontSize="16" FontWeight="Bold" Height="28" HorizontalAlignment="Left" Margin="16,162,0,0" Name="label3" VerticalAlignment="Top" />
  11.                 <Label Content="LastName:" FontSize="16" FontWeight="Bold" Height="28" HorizontalAlignment="Left" Margin="16,204,0,0" Name="label4" VerticalAlignment="Top" />
  12.                 <Label Content="Location:" FontSize="16" FontWeight="Bold" Height="28" HorizontalAlignment="Left" Margin="16,244,0,0" Name="label5" VerticalAlignment="Top" />
  13.                 <TextBox Height="23" HorizontalAlignment="Left" Margin="101,22,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
  14.                 <TextBox Height="23" HorizontalAlignment="Left" Margin="118,167,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" />
  15.                 <TextBox Height="23" HorizontalAlignment="Left" Margin="118,127,0,0" Name="textBox3" VerticalAlignment="Top" Width="120" />
  16.                 <TextBox Height="23" HorizontalAlignment="Left" Margin="118,209,0,0" Name="textBox4" VerticalAlignment="Top" Width="120" />
  17.                 <TextBox Height="23" HorizontalAlignment="Left" Margin="118,249,0,0" Name="textBox5" VerticalAlignment="Top" Width="120" />
  18.                 <Button Content="GetSingleRecord" Height="36" HorizontalAlignment="Left" Margin="25,66,0,0" Name="button1" VerticalAlignment="Top" Width="196" Click="button1_Click_1" />
  19.             </Grid>
  20.         </GroupBox>
  21.         <GroupBox Header="AllDetails" Height="361" HorizontalAlignment="Left" Margin="22,27,0,0" Name="groupBox2" VerticalAlignment="Top" Width="453">
  22.             <Grid>
  23.                 <DataGrid AutoGenerateColumns="False" Height="263" HorizontalAlignment="Left" Margin="14,73,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="413" AlternatingRowBackground="#FFDEA5DE" RowBackground="#FFFFBEA5" FontSize="18" FontWeight="Bold">
  24.                     <DataGrid.Columns>
  25.                         <DataGridTemplateColumn Header="UserId" Width="SizeToCells" IsReadOnly="True">
  26.                             <DataGridTemplateColumn.CellTemplate>
  27.                                 <DataTemplate>
  28.                                     <TextBlock Text="{Binding Path=UserId}"></TextBlock>
  29.                                 </DataTemplate>
  30.                             </DataGridTemplateColumn.CellTemplate>
  31.                         </DataGridTemplateColumn>
  32.                         <DataGridTemplateColumn Header="UserId" Width="SizeToCells" IsReadOnly="True">
  33.                             <DataGridTemplateColumn.CellTemplate>
  34.                                 <DataTemplate>
  35.                                     <TextBlock Text="{Binding Path=UserName}"></TextBlock>
  36.                                 </DataTemplate>
  37.                             </DataGridTemplateColumn.CellTemplate>
  38.                         </DataGridTemplateColumn>
  39.                         <DataGridTemplateColumn Header="UserId" Width="SizeToCells" IsReadOnly="True">
  40.                             <DataGridTemplateColumn.CellTemplate>
  41.                                 <DataTemplate>
  42.                                     <TextBlock Text="{Binding Path=LastName}"></TextBlock>
  43.                                 </DataTemplate>
  44.                             </DataGridTemplateColumn.CellTemplate>
  45.                         </DataGridTemplateColumn>
  46.                         <DataGridTemplateColumn Header="UserId" Width="SizeToCells" IsReadOnly="True">
  47.                             <DataGridTemplateColumn.CellTemplate>
  48.                                 <DataTemplate>
  49.                                     <TextBlock Text="{Binding Path=Location}"></TextBlock>
  50.                                 </DataTemplate>
  51.                             </DataGridTemplateColumn.CellTemplate>
  52.                         </DataGridTemplateColumn>
  53.                     </DataGrid.Columns>
  54.                 </DataGrid>
  55.                 <Button Content="GetDataFromDataSet" Height="37" HorizontalAlignment="Left" Margin="14,22,0,0" Name="button2" VerticalAlignment="Top" Width="183" Click="button2_Click_1" />
  56.                 <Button Content="GetDataFromUserDefinedType" Height="39" HorizontalAlignment="Left" Margin="241,20,0,0" Name="button3" VerticalAlignment="Top" Width="186" Click="button3_Click_2" />
  57.             </Grid>
  58.         </GroupBox>
  59.     </Grid>
  60. </Window>

After Completion of designing we need to Create Proxy for service to consume service:

To create Proxy Do the following:

First Copy The Address Of  Service:

Then Add System.ServiceModel  dll file from .net tab of add reference

Then RightClick on your Project select Add ServiceReference:

After Adding this proxy if you want to see things added to servicereference

first select project the click on showhidden files as shown in below diagram

Then Write Following Code In CodeBehind:

Then Satart Calling From Client:

DownloadSampleCode