Wednesday, 9 July 2014

JSON WebRequest Reference

[] means ----array or list

{ } normal c# object


Example:

[
    {
        "id": "3403",
        "profile_id": "74110",
        "login_name": "43085",
        "login_pwd": "17dfabed4d4e2bd1a939b5b36ec9936f",
        "valid_from": "2012-09-26",
        "status_flag": "-1",
        "remarks": null,
        "style_id": null,
        "updated_by": null,
        "updated_date": "2012-09-26 06:02:29.964565",
        "mobile": null,
        "email": "demoparentapp@edsys.in",
        "token": null,
        "detailed_name": "Zinedin Zidan",
        "user_id": "3403",
        "institution_id": "4",
        "institution_name": "New Indian Model School, Dubai",
        "role_id": "8",
        "user_role_id": "3395",
        "role_type_id": "2",
        "user_name": "12345",
        "passwords": "12345",
        "phone": "0500000000",
        "mobile1": "0500000000",
        "student_details": {
            "id": "2454",
            "admission_no": "00010/14",
            "local_name": "Frank Ribery",
            "photo": "/9j/4AAQSkZJRgABAgEASABIAAD/"
        }
    },
    {
        "id": "3403",
        "profile_id": "74110",
        "login_name": "43085",
        "login_pwd": "17dfabed4d4e2bd1a939b5b36ec9936f",
        "valid_from": "2012-09-26",
        "status_flag": "-1",
        "remarks": null,
        "style_id": null,
        "updated_by": null,
        "updated_date": "2012-09-26 06:02:29.964565",
        "mobile": null,
        "email": "demoparentapp@edsys.in",
        "token": null,
        "detailed_name": "Zinedin Zidan",
        "user_id": "3403",
        "institution_id": "4",
        "institution_name": "New Indian Model School, Dubai",
        "role_id": "8",
        "user_role_id": "3395",
        "role_type_id": "2",
        "user_name": "12345",
        "passwords": "12345",
        "phone": "0500000000",
        "mobile1": "0500000000",
        "student_details": {
            "id": "2593",
            "admission_no": "00100/14",
            "local_name": "Lionel Messi",
            "photo": "/9j/4AAQSkZJRgABAgEASAB"
        }
    }
]


C# class
------------

 public class Parent
    {

        public string id { get; set; }
        public string profile_id { get; set; }
        public string login_name { get; set; }
        public string login_pwd { get; set; }
        public string valid_from { get; set; }
        public string status_flag { get; set; }
        public string remarks { get; set; }
        public string style_id { get; set; }
        public string updated_by { get; set; }
        public string updated_date { get; set; }
        public string detailed_name { get; set; }
        public string user_id { get; set; }
        public string institution_id { get; set; }


        public string institution_name { get; set; }
        public string role_id { get; set; }
        public string user_role_id { get; set; }
        public string role_type_id { get; set; }
        public string user_name { get; set; }
        public string passwords { get; set; }
        public string phone { get; set; }
        public string mobile1 { get; set; }
        public string email { get; set; }

        public student_details student_details { get; set; }

    }

    public class student_details
    {
        public string id { get; set; }
        public string admission_no { get; set; }
        public string local_name { get; set; }
        public string due_date { get; set; }
        public string due_amount { get; set; }
        public string photo { get; set; }
    }

Deserialize
----

 Parent[] parentobj = Newtonsoft.Json.JsonConvert.DeserializeObject<Parent[]>

(result);


C#
---
    public class mark_details_list
    {
        public string exam_id { get; set; }
        public string exam_code { get; set; }
     
        public List<mark_details> mark_details { get; set; }
             
    }

 public class mark_details
    {
        public string subject { get; set; }
        public string mark { get; set; }
        public string grade { get; set; }
        public string updated_date { get; set; }
    }

Json
------

{
  "exam_id": "12345",
  "exam_code": "0500000000",
  "mark_details": [
                   {
                    "subject": "3403",
                   "mark": "74110",
                    "grade": "43085",
               
                    "updated_date": "2012-09-26"

                    },
                   {
                   }

                 ],
}



JSON Http WebRequest
------------------

  private  void btn_Submit_Click(object sender, RoutedEventArgs e)
        {
       
       
            try
            {


               // if (!string.IsNullOrEmpty(txt_username.Text) && (!

string.IsNullOrEmpty(txt_Password.Text))) //commented by sidharth due to password

char
                if (!string.IsNullOrEmpty(txt_username.Text) && (!

string.IsNullOrEmpty(txt_Password.Password)))
                {
                 
           
                    logobj.username = txt_username.Text;
                   // logobj.password = txt_Password.Text;
                    logobj.password = txt_Password.Password;

                    logobj.device_id = IMEI;

                    logobj.app_version = "1.0";


                    string loginWebServiceUrl =

"http://schoolccesoftware.com/PportalApp/index.php/WSlogin";

                    string postData = Newtonsoft.Json.JsonConvert.SerializeObject

(logobj);

                 
               
                    ProcessWebRequest(loginWebServiceUrl);

                    UserControls.ucProgressbar ucprogressbar = new

UserControls.ucProgressbar();
                    ucprogressbar.txt_process_head.Text = "Login";

                    pop_progress.Child = ucprogressbar;

                    pop_progress.IsOpen = true;
               
 
                }
                else
                {

                    MessageBox.Show("Please Enter your Credentials");
                }

           
            }
            catch (Exception ex)
            {

            }

        }



   
   

     

   

        public void ProcessWebRequest(string strUrl)
        {
         
            string result = null;
            try
            {
                HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create

(strUrl);
           
                HttpWReq.Method = "POST";
                HttpWReq.ContentType = "application/x-www-form-urlencoded";
           
                HttpWReq.BeginGetRequestStream(new AsyncCallback

(GetRequestStreamCallback), HttpWReq);
           

             

            }
            catch (Exception ex)
            {
                MessageBox.Show("Something went wrong please contact Edsys");
            }
        }

        public void GetRequestStreamCallback(IAsyncResult asynchronousResult)
        {
            try
            {
             
                HttpWebRequest HttpWReq =

(HttpWebRequest)asynchronousResult.AsyncState;
                Stream postStream = HttpWReq.EndGetRequestStream

(asynchronousResult);
                string postData = string.Empty;
           
                postData = Newtonsoft.Json.JsonConvert.SerializeObject(logobj);
                byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(postData);
                postStream.Write(byteArray, 0, byteArray.Length);
                postStream.Close();
                HttpWReq.BeginGetResponse(new AsyncCallback(GetResponse),

HttpWReq);
             
             
             
            }
            catch (Exception ex)
            {
                MessageBox.Show("Something went wrong please contact Edsys");
            }
        }

     

        public void GetResponse(IAsyncResult callbackResult)
        {
       
            try
            {
               // string s="{\"status\":\"false\",\"message\":\"Access denied !

This device has been register to a parent and cannot be used for other parent\

\/student. For more assistance reach out to info@edsys.in\"}";
                HttpWebRequest HttpWReq =

(HttpWebRequest)callbackResult.AsyncState;
                HttpWebResponse response =

(HttpWebResponse)HttpWReq.EndGetResponse(callbackResult);
                using (StreamReader httpWebStreamReader = new StreamReader

(response.GetResponseStream()))
                {
                    string result = httpWebStreamReader.ReadToEnd();

                    if (result == "{\"success\": false}")
                    {
                   
                   //   Dispatcher.BeginInvoke(()=>MessageBox.Show("Invalid

Username or Password"));

                      Dispatcher.BeginInvoke(() =>
                      {

                          MessageBox.Show("Invalid Username or Password");
                          pop_progress.IsOpen = false;

                      });
                   
                    }
                    else if(result=="{\"status\":\"false\",\"message\":\"Incorrect

Device Token\"}")
                    {
                        Dispatcher.BeginInvoke(() =>
                        {

                            MessageBox.Show(" This device has been already

registered in another device");
                            pop_progress.IsOpen = false;

                        });
                    }

                    else if (result == "{\"status\":\"false\",\"message\":\"Access

denied ! This device has been register to a parent and cannot be used for other

parent\\/student. For more assistance reach out to info@edsys.in\"}")
                    {
                        Dispatcher.BeginInvoke(() =>
                        {

                            MessageBox.Show("Access denied ! This device has been

register to a parent and cannot be used for other parent");
                            pop_progress.IsOpen = false;

                        });
                   
                    }


                    else
                    {
                        //  objParent = new List<Parent>();
                        StaticParent.objParent = new List<BAL.Parent>();

                        Parent[] parentobj =

Newtonsoft.Json.JsonConvert.DeserializeObject<Parent[]>(result);
                        for (int i = 0; i < parentobj.Count(); i++)
                        {

                            StaticParent.objParent.Add(parentobj[i]);
                        }
                        AppSettings appobj = new AppSettings();

                        appobj.IsolatedStorageParentDetails = parentobj.ToList();

                        appobj.IsLoginSettings = true;

                        //  Dispatcher.BeginInvoke(() =>

(Application.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri

("/Menu.xaml", UriKind.Relative)));

                        userEmail = parentobj[0].email;
                        userContact = parentobj[0].phone;
                        // string userName = parentobj[0].login_name;
                        string userName = parentobj[0].user_name;


                        if (userName != "12345")
                        {
                            PushNotify();
                            // pop_progress.IsOpen = false;
                            Dispatcher.BeginInvoke(() =>

(Application.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri

("/Menu.xaml", UriKind.Relative))); //Doubt it need for push notification
                        }
                        else
                        {
                            Dispatcher.BeginInvoke(() =>

(Application.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri

("/Menu.xaml", UriKind.Relative)));
                        }



                    }
               
               
                }
            }
            catch (Exception ex)
            {
                if(ex.Message=="The remote server returned an error: NotFound.")
                {
                    Dispatcher.BeginInvoke(() =>
                    {

                        MessageBox.Show("Remote server not responding");
                        pop_progress.IsOpen = false;

                    });
                }
           
            }
     
         

        }

No comments:

Post a Comment