Converting C# object to Json and Json object to C#


For this we need to add newtonsoft.json.net20

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Web.Script.Serialization;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Credentials c = new Credentials();
            c.UserName = "Chikkanti";
            c.PassWord = "Venki";
            string ans = JsonConvert.SerializeObject(c, Formatting.Indented);
            textBox1.Text = ans;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            JavaScriptSerializer json_serializer = new JavaScriptSerializer();
            Dictionary<string, object> credentials =
                   (Dictionary<string, object>)json_serializer.DeserializeObject(textBox3.Text);//TextBox3 Contains Json Text
            List<Credentials> obj = new List<Credentials>();
            foreach (var item in credentials)
            {
                if (item.Key == "UserName")
                    obj.Add(new Credentials { UserName = item.Value.ToString() });
                else if (item.Key == "PassWord")
                    obj.Add(new Credentials { PassWord = item.Value.ToString() });
            }
            string s = string.Empty;
            foreach (Credentials c in obj)
            {
                s += c.UserName + "  " + c.PassWord;
            }
            textBox2.Text = s;
        }
    }
    public class Credentials
    {
        public string UserName;
        public string PassWord;
        public void setTest(String prUserName) { UserName = prUserName; }
    }
}

Converting C# object to json viceversa

DownLoadSampleCode

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

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