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>