Friday, October 4, 2019

VSCode USing GOLang

VSCode installation for GO.

before installing,  unintall vscode delete all the related vscode files in programs,appadata folders if it is already installed and.

creating the workspace
file->openworkspace


1. install go using extensions and restart VSCode

2. go to view->commandpalette->go_install/update, select all and ok.

 3. npm install -g yo generator-code

instal c#, c#extensions
test the example
package main

import "fmt"

func main() {
    fmt.Println("Hello")
}

Monday, May 6, 2019

how to disable and enable the triggers in SQL to increase the SQL execution time

//Disable
Declare @SQLTrigger varchar(max)
 set @SQLTrigger=  'dbo.sp_MSforeachtable @command1='+'"'+'DISABLE TRIGGER ALL ON ?'+'" '
 exec(@SQLTrigger)


//Enable
 Declare @SQLTrigger varchar(max)
 set @SQLTrigger=  'dbo.sp_MSforeachtable @command1='+'"'+'Enable TRIGGER ALL ON ?'+'" '
 exec(@SQLTrigger)

To disable and enable all constraints on a database

//DIsable

EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"


//ENable
EXEC sp_msforeachtable "ALTER TABLE ? CHECK CONSTRAINT all"

To know reference tables(foreign key) for a table, SQLSERVer

SELECT CONSTRAINT_NAME = name,
       FOREIGN_SCHEMA = OBJECT_SCHEMA_NAME(parent_object_id),
       FOREIGN_TABLE = OBJECT_NAME(parent_object_id),
       REFERENCED_SCHEMA = OBJECT_SCHEMA_NAME(referenced_object_id),
       REFERENCED_TABLE = OBJECT_NAME(referenced_object_id)
FROM sys.foreign_keys
WHERE OBJECT_NAME(referenced_object_id) = 'TableName';
GO

Tuesday, December 4, 2018

CSV file replace with a datatble functionality


        private int CSVReplace(DataTable dtDictionary, string path, bool chkCase)
        {
            int totalcount = 0;
            try
            {
                string[] input = File.ReadAllLines(path);
                string inputLine = "";
                for (int i = 0; i < dtDictionary.Rows.Count; i++)
                {
                    if (dtDictionary.Rows[i].ItemArray[0].ToString().Trim() != "")
                    {
                        for (int k = 0; k < input.Count(); k++)
                        {
                            StringReader reader = new StringReader(input[k]);
                            List<List<string>> data = new List<List<string>>();
                            string[] inputArray = { };
                            while ((inputLine = reader.ReadLine()) != null)
                            {
                                if (inputLine.Trim().Length > 0)
                                {
                                    inputArray = inputLine.Split(new char[] { '|' });
                                    for (int j = 0; j < inputArray.Count(); j++)
                                    {
                                        int count = 0;
                                        if (chkCase)
                                        {
                                            if (inputArray[j] == dtDictionary.Rows[i].ItemArray[0].ToString().Trim())
                                            {
                                                count = count + 1;
                                                totalcount = totalcount + count;
                                                if (input[k].Contains(dtDictionary.Rows[i].ItemArray[0].ToString().Trim()))
                                                {
                                                    input[k] = input[k].Replace(dtDictionary.Rows[i].ItemArray[0].ToString().Trim(), dtDictionary.Rows[i].ItemArray[1].ToString().Trim() + ".");
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if (inputArray[j].ToLower() == dtDictionary.Rows[i].ItemArray[0].ToString().Trim().ToLower())
                                            {
                                                count = count + 1;
                                                totalcount = totalcount + count;
                                                if (input[k].Contains(dtDictionary.Rows[i].ItemArray[0].ToString().Trim()))
                                                {
                                                    input[k] = Regex.Replace(input[k], dtDictionary.Rows[i].ItemArray[0].ToString().Trim(), dtDictionary.Rows[i].ItemArray[1].ToString().Trim() + ".", RegexOptions.IgnoreCase);
                                                }
                                            }
                                        }
                                        if (count > 0)
                                        {
                                            File.WriteAllLines(path, input);
                                            Log.WriteLog(Path.GetFileName(txtTarget.Text) + " target file replaced with " + Path.GetFileName(txtDictionary.Text) + " : Replaced " + count + " entries from " + dtDictionary.Rows[i].ItemArray[0].ToString() + " to " + dtDictionary.Rows[i].ItemArray[1].ToString());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog("CSVReplace at Replace" + ex.Message);
            }
            return totalcount;
        }

Excel file replace with a datatable

 #region if target file is excel then the replace method
        /// <summary>
        /// ExcelReplace
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="boolCase"></param>
        /// <returns></returns>
        private double ExcelReplace(System.Data.DataTable dt, string path, bool boolCase)
        {
            double inttotalCount = 0;
            try
            {
                Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
                Workbook wb = excelApp.Workbooks.Open(path, Type.Missing, Type.Missing,
                                                       Type.Missing, Type.Missing,
                                                       Type.Missing, Type.Missing,
                                                       Type.Missing, Type.Missing,
                                                       Type.Missing, Type.Missing,
                                                       Type.Missing, Type.Missing,
                                                       Type.Missing, Type.Missing);
                excelApp.DisplayAlerts = false;

                Sheets ws = wb.Worksheets;
                Worksheet worksheet = (Worksheet)ws.get_Item(1);//1st sheet in workbook

                Range range = worksheet.UsedRange;//Used cells range

                int rows = range.Rows.Count;
                int cols = range.Columns.Count;

                Range startCell = worksheet.Cells[1, 1];
                Range endCell = worksheet.Cells[rows, cols];

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    double cnt = 0;
                    //matching words count based on case sensitive

                    if (dt.Rows[i].ItemArray[0].ToString().Trim() != "")
                    {

                        if (boolCase == true)
                        {

                            //excelApp.WorksheetFunction.SumProduct(range , pattern);
                            cnt = worksheet.Evaluate(excelApp.WorksheetFunction.CountIf(range, dt.Rows[i].ItemArray[0].ToString().Trim()));
                            // cnt = Regex.Matches(worksheet.Range[startCell, endCell].ToString(), dt.Rows[i].ItemArray[0].ToString().Trim()).Count;
                            //worksheet.Range[startCell, endCell].Replace(pattern, dt.Rows[i].ItemArray[1].ToString());

                            //cnt = excelApp.WorksheetFunction.SumIf(range, dt.Rows[i].ItemArray[0].ToString().Trim());//Case sensitive
                            //  cnt = Regex.Matches(File.ReadAllText(txtTarget.Text),pattern).Count;
                            //cnt = excelApp.WorksheetFunction.SumProduct("(--Exact("+range , dt.Rows[i].ItemArray[0].ToString().Trim()+"))"+);//Case sensitive

                            //cnt= worksheet.Evaluate("excelApp.WorksheetFunction.SumProduct(--Exact(range, dt.Rows[i].ItemArray[0].ToString().Trim()))");
                            //cnt = excelApp.WorksheetFunction.CountIfs(range, dt.Rows[i].ItemArray[0].ToString().Trim(), " --MatchCase: boolCase"); //"*"+dt.Rows[i].ItemArray[0].ToString()+"*"

                        }
                        else
                        {
                            cnt = excelApp.WorksheetFunction.CountIf(range, dt.Rows[i].ItemArray[0].ToString().Trim()); //"*"+dt.Rows[i].ItemArray[0].ToString()+"*"
                                                                                                                        //  cnt = Regex.Matches(File.ReadAllText(txtTarget.Text), Regex.Escape(dt.Rows[i].ItemArray[0].ToString().Trim()), RegexOptions.IgnoreCase).Count;
                        }

                    }
                    if (cnt != 0)
                    {
                        try
                        {
                            //replace the words based on case sensitive
                            worksheet.Range[startCell, endCell].Replace(dt.Rows[i].ItemArray[0].ToString(), dt.Rows[i].ItemArray[1].ToString(), MatchCase: boolCase);
                            // MessageBox.Show("Replaced " + cnt + " entries from " + dt.Rows[i].ItemArray[0].ToString() + " to " + dt.Rows[i].ItemArray[1].ToString());
                            Log.WriteLog(Path.GetFileName(path) + " target file replaced with " + Path.GetFileName(txtDictionary.Text) + " : Replaced " + cnt + " entries from " + dt.Rows[i].ItemArray[0].ToString() + " to " + dt.Rows[i].ItemArray[1].ToString());
                        }
                        catch (Exception ex)
                        {
                            cnt = 0;
                            Log.WriteLog("ExcelReplace at Replace" + ex.Message);
                            MessageBox.Show(ex.Message);
                        }
                    }
                    //for total matched words in the file
                    inttotalCount = inttotalCount + cnt;
                }
                wb.Close(true);
                excelApp.Quit();
            }
            catch (Exception ex)
            {
                Log.WriteLog("ExcelReplace" + ex.Message);
                MessageBox.Show(ex.Message);
            }
            if (inttotalCount == 0)
            {
                File.Delete(path);
            }

            return inttotalCount;
        }

        #endregion

Replace a file with a datatable

 private void BtnExecute_Click(object sender, EventArgs e)
        {
            if (txtDictionary.Text != "" && txtTarget.Text != "")
            {
                string newPath = Path.GetFullPath(Path.Combine(txtTarget.Text, @"..\"));//to go back from current directory
                string filename = Path.GetFileName(txtTarget.Text); //to get the filename
                try
                {
                    System.Data.DataTable dtDictionary = new System.Data.DataTable();
                    dtDictionary = ReadExcel(txtDictionary.Text);

                    if (dtDictionary.Columns.Count == 2)
                    {
                        System.IO.Directory.CreateDirectory(newPath + "ReplacedTarget"); // To create folder if it doesn't exists                     
                        string fileExt = Path.GetExtension(txtTarget.Text); //get the file extension 
                        double totalCount = 0;
                        File.Copy(txtTarget.Text, newPath + "\\ReplacedTarget\\" + filename); //copying target file

                     
                            for (int i = 0; i < dtDictionary.Rows.Count; i++)
                            {
                                if (dtDictionary.Rows[i].ItemArray[0].ToString().Trim() != "")
                                {
                                    int cnt = 0;
                                    try
                                    {
                                        string pattern = string.Format(@"\b{0}\b", dtDictionary.Rows[i].ItemArray[0].ToString().Trim());//to replace the whole word instead of part of a word

                                        if (chkCase.Checked == true)
                                        {
                                            //To get the matched words count in dictionary and target
                                            cnt = Regex.Matches(File.ReadAllText(txtTarget.Text), pattern).Count;
                                            if (cnt > 0)
                                            {
                                                //To replace matched words
                                                File.WriteAllText(newPath + "ReplacedTarget\\" + filename, File.ReadAllText(newPath + "ReplacedTarget\\" + filename).Replace(pattern, dtDictionary.Rows[i].ItemArray[1].ToString()));
                                            }
                                        }
                                        else
                                        {
                                            //To get the matched words count in dictionary and target irrespective of case
                                            cnt = Regex.Matches(File.ReadAllText(txtTarget.Text), pattern, RegexOptions.IgnoreCase).Count;

                                            if (cnt > 0)
                                            {
                                                //To replace matched words irrespective of case
                                                File.WriteAllText(newPath + "ReplacedTarget\\" + filename, Regex.Replace(File.ReadAllText(newPath + "ReplacedTarget\\" + filename), pattern, dtDictionary.Rows[i].ItemArray[1].ToString(), RegexOptions.IgnoreCase));
                                                Log.WriteLog(Path.GetFileName(txtTarget.Text) + " target file replaced with " + Path.GetFileName(txtDictionary.Text) + " : Replaced " + cnt + " entries from " + dtDictionary.Rows[i].ItemArray[0].ToString() + " to " + dtDictionary.Rows[i].ItemArray[1].ToString());
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        cnt = 0;
                                        Log.WriteLog("BtnExecute_Click at WriteAllText" + ex.Message);
                                        MessageBox.Show(ex.Message);
                                    }
                                    //for total matched words in the file
                                    totalCount = totalCount + cnt;
                                }
                            }
                   
                        btnExecute.Enabled = false;
                        if (totalCount == 0)
                        {
                            File.Delete(newPath + "\\ReplacedTarget\\" + filename);
                        }

                        MessageBox.Show(totalCount + " total replacements completed");
                        Log.WriteLog(Path.GetFileName(txtTarget.Text) + " target file replaced with " + Path.GetFileName(txtDictionary.Text) + " : " + totalCount + " total replacements completed.\n");
                    }
                    else
                    {
                        MessageBox.Show("The excel sheet columns are not 2, Please select exact one.");
                        Log.WriteLog(Path.GetFileName(txtDictionary.Text) + " excel sheet columns are not 2, Please select exact one.");
                    }
                }
                catch (Exception ex)
                {
                    Log.WriteLog("BtnExecute_Click" + ex.Message);
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    foreach (Process process in Process.GetProcesses())
                    {
                        if (process.MainWindowTitle.Contains(txtDictionary.Text) || process.MainWindowTitle.Contains(txtTarget.Text))
                        {
                            process.Kill();
                            break;
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("please select Dictionary/Target files to proceed");
                Log.WriteLog("please select Dictionary/Target files to proceed");
            }
        }

Dialogbox

 private string GetFilePath()
        {
            string filePath = string.Empty;
            string fileExt = string.Empty;
            OpenFileDialog file = new OpenFileDialog(); //open dialog to choose file 
            try
            {
                if (file.ShowDialog() == System.Windows.Forms.DialogResult.OK) //if there is a file choosen by the user 
                {
                    filePath = file.FileName; //get the path of the file 
                    btnExecute.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
                file.Dispose();
            }
            return filePath;
        }

Read the Excel file into datatable conversion

 public System.Data.DataTable ReadExcel(string filePath)
        {
            System.Data.DataTable dtexcel = new System.Data.DataTable();
            try
            {
                bool hasHeaders = false;
                string HDR = hasHeaders ? "Yes" : "No";
                string strConn;
                if (filePath.Substring(filePath.LastIndexOf('.')).ToLower() == ".xlsx")
                {
                    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
                }
                else
                {
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=0\"";
                }
                OleDbConnection conn = new OleDbConnection(strConn);
                conn.Open();
                System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                DataRow schemaRow = schemaTable.Rows[0];
                string sheet = schemaRow["TABLE_NAME"].ToString();
                if (!sheet.EndsWith("_"))
                {
                    string query = "SELECT  * FROM [" + sheet + "]";
                    OleDbDataAdapter daexcel = new OleDbDataAdapter(query, conn);
                    daexcel.Fill(dtexcel);
                }
                conn.Close();
            }
            catch (Exception ex)
            {
                Log.WriteLog("ReadExcel" + ex.Message);
                MessageBox.Show(ex.Message);

            }
            return dtexcel;
        }

to restoret he data without taking care of current db

USE [master]
ALTER DATABASE ForeSite_LS_s6 SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
RESTORE DATABASE ForeSite_LS_s6 FROM DISK = 'E:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Backup\ForeSite_LS_s6.bak'
WITH REPLACE
GO

Saturday, August 20, 2016

to send the request and get the response from a URL

//request formation with URL
httpRequest = System.Net.WebRequest.Create(new Uri(Url)) as System.Net.HttpWebRequest;
            httpRequest.Method = "POST";
            httpRequest.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
       
            httpRequest.ContentType = "application/json";//application type
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
//request Paramets
             string    Params = new JavaScriptSerializer().Serialize(objJioFetchWalletREQUEST);

            byte[] data = encoding.GetBytes(Params);
            httpRequest.ContentLength = data.Length;
            try
            {
             //sending request to URL
                using (System.IO.Stream newStream = httpRequest.GetRequestStream())
                {
                    newStream.Write(data, 0, data.Length);
                }
//response from URL
                httpResponse = httpRequest.GetResponse() as System.Net.HttpWebResponse;
                using (System.IO.Stream resStream = httpResponse.GetResponseStream())
                {
                    System.IO.StreamReader reader = new System.IO.StreamReader(resStream);
                    responseData = reader.ReadToEnd();
                }

to get date in 2016-03-21T05:22:55.666+05.30 format(datetime+GMT timezone)

            string date= DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffzzzz");

object to json conversion

  string Params = new JavaScriptSerializer().Serialize(objJioStatusRequest);//json conversion

object to XML Conversion and parent node eliminating

  //XML Conversion
                    XmlSerializer ser = new XmlSerializer(objJioStatusRequest.GetType());
                    string result = string.Empty;
                    using (MemoryStream memStm = new MemoryStream())
                    {
                        ser.Serialize(memStm, objJioStatusRequest);
                        memStm.Position = 0;
                        result = new StreamReader(memStm).ReadToEnd();
                    }
                    //To remove Parant node
                    XmlDocument xd = new XmlDocument();
                    xd.LoadXml(result);
                    Params = xd.DocumentElement.InnerXml;

Wednesday, May 4, 2016

to delete the data in dataset

for (int tableno = 0; tableno < dsSMS.Tables.Count; tableno++)
                                {
                                    foreach (DataRow dr in dsSMS.Tables[tableno].Rows)
                                    {
                                        if (dr["ID"].ToString().Trim() == "24")
                                        {
                                            dr.Delete();
                                        }
                                    }
                                    dsSMS.Tables[tableno].AcceptChanges();
                                }

to find dataset has the records or not and to count the no. of records in the dataset

 bool datafound = false;
                // to check whether the data is there or not and no of rows in a dataset
                int count = 0;
                if (dsSMSJob != null && dsSMSJob.Tables.Count > 0)
                {
                    foreach (System.Data.DataTable table in dsSMSJob.Tables)
                    {
                        if (table.Rows.Count > 0)
                        {
                            count = count + table.Rows.Count; // no. of records in dataset
                            datafound = true; // data is there
                        }
                    }
                }
                if(datafound==true)
                    sendSMS(dsSMSJob, job);     // if the data is there do some operation

json parsing

{"results":[
                {"errorCode":"28673","errorMsg":"Destination number not numeric"},
                {"errorCode":"28674","errorMsg":"Destination number empty"},
                {"errorCode":"28675","errorMsg":"Sender address empty"},
                {"errorCode":"28676","errorMsg":"SMS over 160 character, Non-compliant message"},
                {"errorCode":"28677","errorMsg":"UDH is invalid"},
                {"errorCode":"28678","errorMsg":"Coding is invalid"},
                {"errorCode":"28679","errorMsg":"SMS text is empty"},
                {"errorCode":"28680","errorMsg":"Invalid sender ID"},
                {"errorCode":"28681","errorMsg":"Invalid message, Duplicate message, Submit failed"},
                {"errorCode":"28682","errorMsg":"Invalid Receiver ID (will validate Indian mobile numbers only)"},
                {"errorCode":"28683","errorMsg":"Invalid Date time for message Schedule (If the date specified in message post for schedule delivery is less than current date or more than expiry date or more than 1 year)"}
                ]}



  var json = System.IO.File.ReadAllText(yourpath);
            //dynamic stuff = JsonConvert.DeserializeObject(json);
            JObject results = JObject.Parse(json);

            foreach (var result in results["results"])
            {
                string errorCode = (string)result["errorCode"];
                string errorMsg = (string)result["errorMsg"];
                Console.WriteLine(errorCode + ",,,....,,," + errorMsg);


            }

Friday, April 15, 2016

404 error after adding Web API to an existing MVC Web Application

While it doesn't work with:
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    GlobalConfiguration.Configure(WebApiConfig.Register); //I AM THE 4th
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}      
It works with:
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register); //I AM THE 2nd
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}      

The configuration element is not declared

This warning generated from my app.config file is driving me crazy and I have been searching without getting any real answer as to why this is the case. Here is the code.
enter image description here
we can solve it by...
Go to XML menu (visual studio top menu item) choose schemas and find for DotNetConfig.xsd and choose use this schema.

cascading dropdown in mvc razor using jquery

This article shows how to create a Cascading Dropdownlist.

Use JSON with razor syntax.

CascadingDropDown enables a common scenario in which the contents of one list depends on the selection of another list and does so without having to embed the entire data set in the page or transfer it to the client at all.

The main purpose is to reduce Postbacks.

Let's start.

Srep 1: Create a project then select Web from above Menu in left
Step 2: Select ASP.NET MVC 4 Web Application.

MVC 4 Web Application

Internet Application

And name it Cascadingdropdownlist.

Step 3: After creating the application we will add a Controller to the page.

For adding the Controller right-click on the Controller Folder and select Add inside add Select Controller.

Adding Controller

Controller

And I am naming the Contoller CustomerFeedbackController.cs.

Step 4: After adding the Controller to the application I am now just adding a new action result and naming it LoadCountries.
public ActionResult LoadCountries()
{
     List<SelectListItem> li = new List<SelectListItem>();
     li.Add(new SelectListItem { Text = "Select", Value = "0" });
     li.Add(new SelectListItem { Text = "India", Value = "1" });
     li.Add(new SelectListItem { Text = "Srilanka", Value = "2" });
     li.Add(new SelectListItem { Text = "China", Value = "3" });
     li.Add(new SelectListItem { Text = "Austrila", Value = "4" });
     li.Add(new SelectListItem { Text = "USA", Value = "5" });
     li.Add(new SelectListItem { Text = "UK", Value = "6" });
     ViewData["country"] = li;
     return View();
}
In this I created a Generic List and in the list I am adding an item to it.

After adding I am storing it in ViewData for passing to the view.

Step 5: For adding the View to LoadCountries rigtht-click on the loadCountries and select Add View.

Add View

Add a click on the Add Button. Add Razor Syntax to the Begin Form.

@using (Html.BeginForm())
{
}

Step 6: Add a Dropdown list with Name of Countries and Binding ViewData to the Dropdownlist.
@using (Html.BeginForm())
{
    @Html.DropDownList("Country", ViewData["country"as List<SelectListItem>)
}
Now just run the application and check how it is output.

just run application

The preceding was a simple example of how to bind a list to a Dropdownlist in MVC.

Now we will be doing a Cascading Dropdown Demo. For that we would be writing a JSON script and JSON method.

And add two DropDownLists with an empty Datasource.

Step 7:
  1. State DropDownList

    @Html.DropDownList("State"new SelectList(string.Empty, "Value""Text"), "Please select a State"new { style = "width:250px", @class = "dropdown1" })
     
  2. City DropDownList

    @Html.DropDownList("city"new SelectList(string.Empty, "Value""Text"), "Please select a city"new { style ="width:250px", @class = "dropdown1" })
Now we have added two DropDownLists.

Here is a Snapshot of the View:

Snapshot of View

Step 8: Further we will be adding a method for the JSON and a script for JSON for the States.

Just below I have added the method for JSON.

And also you will see the method for JSON is taking an input parameter, id (this is the id of the Country Dropdownlist that I created).

The Script for JSON will be called when the Country Dropdownlist is selected.
public JsonResult GetStates(string id)
{
    List<SelectListItem> states = new List<SelectListItem>();
    switch (id)
    {
        case "1":
             states.Add(new SelectListItem { Text = "Select", Value = "0" });
             states.Add(new SelectListItem { Text = "ANDAMAN & NIKOBAR ISLANDS", Value = "1" });
             states.Add(new SelectListItem { Text = "ANDHRA PRADESH", Value = "2" });
             states.Add(new SelectListItem { Text = "ARUNACHAL PRADESH", Value = "3" });
             states.Add(new SelectListItem { Text = "ASSAM", Value = "4" });
             states.Add(new SelectListItem { Text = "BIHAR", Value = "5" });
             states.Add(new SelectListItem { Text = "CHANDIGARH", Value = "6" });
             states.Add(new SelectListItem { Text = "CHHATTISGARH", Value = "7" });
             states.Add(new SelectListItem { Text = "DADRA & NAGAR HAVELI", Value = "8" });
             states.Add(new SelectListItem { Text = "DAMAN & DIU", Value = "9" });
             states.Add(new SelectListItem { Text = "GOA", Value = "10" });
             states.Add(new SelectListItem { Text = "GUJARAT", Value = "11" });
             states.Add(new SelectListItem { Text = "HARYANA", Value = "12" });
             states.Add(new SelectListItem { Text = "HIMACHAL PRADESH", Value = "13" });
             states.Add(new SelectListItem { Text = "JAMMU & KASHMIR", Value = "14" });
              states.Add(new SelectListItem { Text = "JHARKHAND", Value = "15" });
              states.Add(new SelectListItem { Text = "KARNATAKA", Value = "16" });
              states.Add(new SelectListItem { Text = "KERALA", Value = "17" });
              states.Add(new SelectListItem { Text = "LAKSHADWEEP", Value = "18" });
              states.Add(new SelectListItem { Text = "MADHYA PRADESH", Value = "19" });
              states.Add(new SelectListItem { Text = "MAHARASHTRA", Value = "20" });
              states.Add(new SelectListItem { Text = "MANIPUR", Value = "21" });
              states.Add(new SelectListItem { Text = "MEGHALAYA", Value = "22" });
              states.Add(new SelectListItem { Text = "MIZORAM", Value = "23" });
              states.Add(new SelectListItem { Text = "NAGALAND", Value = "24" });
              states.Add(new SelectListItem { Text = "NCT OF DELHI", Value = "25" });
              states.Add(new SelectListItem { Text = "ORISSA", Value = "26" });
              states.Add(new SelectListItem { Text = "PUDUCHERRY", Value = "27" });
               states.Add(new SelectListItem { Text = "PUNJAB", Value = "28" });
               states.Add(new SelectListItem { Text = "RAJASTHAN", Value = "29" });
               states.Add(new SelectListItem { Text = "SIKKIM", Value = "30" });
               states.Add(new SelectListItem { Text = "TAMIL NADU", Value = "31" });
               states.Add(new SelectListItem { Text = "TRIPURA", Value = "32" });
               states.Add(new SelectListItem { Text = "UTTAR PRADESH", Value = "33" });
               states.Add(new SelectListItem { Text = "UTTARAKHAND", Value = "34" });
               states.Add(new SelectListItem { Text = "WEST BENGAL", Value = "35" });
            break;
               case "UK":
           break;
            case "India":
          break;
    }
    return Json(new SelectList(states, "Value""Text"));
}
Step 9: After creating the method for JSON I just wrote a script for JSON.
<script src="../../Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        //Dropdownlist Selectedchange event
        $("#Country").change(function () {
            $("#State").empty();
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetStates")'// we are calling json method

                dataType: 'json',

                data: { id: $("#Country").val() }, 
               // here we are get value of selected country and passing same value
                  as inputto json method GetStates.

                success: function (states) {
                    // states contains the JSON formatted list
                    // of states passed from the controller

                    $.each(states, function (i, state) {
                    $("#State").append('<option value="' + state.Value + '">' +  
                         state.Text + '</option>');                                                                                                
                    // here we are adding option for States

                    });
                },
                error: function (ex) {
                    alert('Failed to retrieve states.' + ex);
                }
            });
            return false;
        })
    });
</script>
Step 10:

We have just now bound States from Country. We will now bind city from States.

in the same manner I created a method for JSON for binding the City.
public JsonResult GetCity(string id)
{
            List<SelectListItem> City = new List<SelectListItem>();
            switch (id)
            {
                case "20":
                    City.Add(new SelectListItem { Text = "Select", Value = "0" });
                    City.Add(new SelectListItem { Text = "MUMBAI", Value = "1" });
                    City.Add(new SelectListItem { Text = "PUNE", Value = "2" });
                    City.Add(new SelectListItem { Text = "KOLHAPUR", Value = "3" });
                    City.Add(new SelectListItem { Text = "RATNAGIRI", Value = "4" });
                    City.Add(new SelectListItem { Text = "NAGPUR", Value = "5" });
                    City.Add(new SelectListItem { Text = "JALGAON", Value = "6" });
                    break;
            }

            return Json(new SelectList(City, "Value""Text"));
}
Step 11:  And also wrote a script for JSON that wil be active when you select States.
<script type="text/javascript">
    $(document).ready(function () {
        //Dropdownlist Selectedchange event
        $("#State").change(function () {
            $("#city").empty();
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetCity")',
                dataType: 'json',
                data: { id: $("#State").val() },
                success: function (citys) {
                    // states contains the JSON formatted list
                    // of states passed from the controller
                    $.each(citys, function (i, city) {
                        $("#city").append('<option value="'
+ city.Value + '">'
+ city.Text + '</option>');
                    });
                },
                error: function (ex) {
                    alert('Failed to retrieve states.' + ex);
                }
            });
            return false;
        })
    });
</script>