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

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……….

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 Bind Combobox with values retrived from database in windows forms


Create DataBaseTable as follows:\

then take windows forms application and place a combobox and button

the write the following code under button click event

Namespaces:

using System.Data.SqlClient;

Code:

DataSet ds = new DataSet();
            SqlConnection con = new SqlConnection("Data Source=server2;Initial Catalog=MySampleDB;User ID=sa;password=123");
            SqlCommand cmd = new SqlCommand("select * from UserDetails", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            comboBox1.DataSource = ds.Tables[0];
            comboBox1.DisplayMember = "UserName";

Result:

How to show progressbar while some process is in progress in windows forms application


Sometimes we are processing long time at that time user need to wait for process to complete

If we don’t show any progress user might feel something uncomfortable. To give relax from that feel we have to show some progress about that process.

How to show that progress:

First design the form as follows:

Controls to place in form:

1.Progressbar

2.timer

3.button

4.label

After adding these controls to form set the following properties:

For Progressbar:

Set value property = 10

Set maximum property  = 1000

Minimum = 10

Step = 1

Then write following code under button click event

timer1.Enabled = true;

 

then write following  code under timer tick event

if (progressBar1.Value < progressBar1.Maximum)

{

progressBar1.PerformStep();

}

else

{

this.Hide();

timer1.Enabled = false;

MessageBox.Show(“your data send…”);

}