Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have c# code as below for website and its working fine 100%.
Now i want equivalent code for windows phone 7, click event replace with load method.. code where i got syntax error highlighted by underline and bold face.
   <pre>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Net;
using System.IO;

public partial class SampleEx : System.Web.UI.Page
{   
    /*
     * Generates an authentication token by contacting ClientLogin and passing
     * credentials for a given user.
     */
    private string getAuthToken(String email, String password)
    {
        // Construct the body of the request with email, password, service, and source
        string sdata =
                  "accountType=" + HttpUtility.UrlEncode("HOSTED_OR_GOOGLE") + "&"
                  + "Email=" + HttpUtility.UrlEncode(email) + "&"
                  + "Passwd=" + HttpUtility.UrlEncode(password) + "&"
                  + "service=" + HttpUtility.UrlEncode("fusiontables") + "&"
                  + "source=" + HttpUtility.UrlEncode("fusiontables.ApiExample")
                  + "&logintoken=&logincaptcha=";

        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] data = encoding.GetBytes(sdata);

        // Create the request
        HttpWebRequest req = (HttpWebRequest)
          WebRequest.Create("https://www.google.com/accounts/ClientLogin");
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        req.ContentLength = data.Length;

        // Send the body of the request
        Stream sout = req.GetRequestStream();
        sout.Write(data, 0, data.Length);
        sout.Close();

        try
        {
            // Get the response
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader stIn = new StreamReader(res.GetResponseStream());
            string s = stIn.ReadToEnd();

            // Extract the Auth token component and return it
            char[] delim = new char[] { '=' };
            string[] parts = s.Split(delim);
            return parts[3];
        }
        catch (WebException e)
        {
            // In case of error, usually 403, return the concrete error response
            StreamReader stIn = new StreamReader(e.Response.GetResponseStream());
            return stIn.ReadToEnd();
        }
    }

    /*
     * Executes a select query. The query will be send as a get request. Uses the
     * authentication token obtained through ClientLogin. Returns the body of the
     * response obtained from fusiontables.
     */
    private String executeSelect(String query, String token)
    {
        // Encode the query in  the url
        string url = "http://tables.googlelabs.com/api/query?sql="
          + HttpUtility.UrlEncode(query);
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

        // Add the authentication header
        req.Headers.Add("Authorization: GoogleLogin auth=" + token);

        try
        {
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader stIn = new StreamReader(res.GetResponseStream());
            return stIn.ReadToEnd();
        }
        catch (WebException e)
        {
            StreamReader stIn = new StreamReader(e.Response.GetResponseStream());
            return stIn.ReadToEnd();
        }
    }

    /*
     * Executes an statement that modifies data, that is, insert, update, or delete.
     * Uses the authentication token obtained through ClientLogin. Returns the body
     * of the response obtained from fusiontables.
     */
    private String executeUpdate(String query, String token)
    {
        string sdata = "sql=" + HttpUtility.UrlEncode(query);
        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] data = encoding.GetBytes(sdata);

        // Create the request, encode the query in the body of the post
        HttpWebRequest req = (HttpWebRequest)
          WebRequest.Create("http://tables.googlelabs.com/api/query");
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        req.ContentLength = data.Length;

        // Add the authentication header
        req.Headers.Add("Authorization: GoogleLogin auth=" + token);

        Stream sout = req.GetRequestStream();
        sout.Write(data, 0, data.Length);
        sout.Close();

        try
        {
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader stIn = new StreamReader(res.GetResponseStream());
            return stIn.ReadToEnd();
        }
        catch (WebException e)
        {
            StreamReader stIn = new StreamReader(e.Response.GetResponseStream());
            return stIn.ReadToEnd();
        }
    }

    /*
     * Handler for the click event on the single button in the aspx page.
     */
    public void Click(Object s, EventArgs e)
    {
        // Get the authentication token to use on all requests
        // Please modify the email and password to match your account
        string email = "punit.belani@gmail.com";
        string password = "punit1234";
        string token = getAuthToken(email, password);

        // Example of an insert query
        string result1 = "";// executeUpdate("insert into tableid ('column 1','column 2') values ('value 1', 'value 2')", token);

        // Example of a select query, should return the newly inserted row in the previous statement
        string result2 = executeSelect("select * from 3354083", token);

        // Show the result in the label
        lblMessage.Text = result1 + "||" + result2;
    }
}
Posted
Updated 4-Apr-12 1:44am
v3

1 solution

I found converted code for xaml as below (both code purpose are same but syntax different):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.Text;

namespace TestApp
{
    public partial class googlefusion : PhoneApplicationPage
    {

        string email = "punit.belani@gmail.com";
        string password = "punit1234";
        string token = "";
        public delegate void updatetextdelegate(string text);

        public googlefusion()
        {
            InitializeComponent();
        }

        private void searchOnlineRequest(IAsyncResult asyncResult)
        {
            string sdata =
                     "accountType=" + HttpUtility.UrlEncode("HOSTED_OR_GOOGLE") + "&"
                     + "Email=" + HttpUtility.UrlEncode(email) + "&"
                     + "Passwd=" + HttpUtility.UrlEncode(password) + "&"
                     + "service=" + HttpUtility.UrlEncode("fusiontables") + "&"
                     + "source=" + HttpUtility.UrlEncode("fusiontables.ApiExample")
                     + "&logintoken=&logincaptcha=";

            UTF8Encoding encoding = new UTF8Encoding();
            HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
            Stream _body = request.EndGetRequestStream(asyncResult);
            byte[] formBytes = encoding.GetBytes(sdata);

            _body.Write(formBytes, 0, formBytes.Length);
            _body.Close();

            request.BeginGetResponse(SearchResponseCallback, request);
        }

        private void SearchResponseCallback(IAsyncResult asyncResult)
        {
            HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
            Stream content = response.GetResponseStream();

            if (request != null && response != null)
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    using (StreamReader reader = new StreamReader(content))
                    {
                        string _responseString = reader.ReadToEnd();
                        char[] delim = new char[] { '=' };
                        string[] parts = _responseString.Split(delim);
                        token = parts[3];
                        reader.Close();
                    }
                }
            }
            HttpWebRequest requestOut = HttpWebRequest.CreateHttp("http://tables.googlelabs.com/api/query?sql=select * from 3354083");
            requestOut.Headers["Authorization"] = "GoogleLogin auth=" + token;
            requestOut.ContentType = "application/x-www-form-urlencoded";
            requestOut.Method = "POST";
            requestOut.BeginGetRequestStream(searchOnlineRequestOut, requestOut);
        }
        private void searchOnlineRequestOut(IAsyncResult asyncResult)
        {

            UTF8Encoding encoding = new UTF8Encoding();
            HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;

            request.BeginGetResponse(SearchResponseCallbackOut, request);
        }
        private void SearchResponseCallbackOut(IAsyncResult asyncResult)
        {
            HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
            Stream content = response.GetResponseStream();

            if (request != null && response != null)
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    using (StreamReader reader = new StreamReader(content))
                    {
                        string _responseString = reader.ReadToEnd();
                        this.Dispatcher.BeginInvoke(new updatetextdelegate(Updatetext), _responseString);
                        reader.Close();
                    }
                }
            }
        }

        private void Updatetext(string text)
        {
            lblOut.Text = text;
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {

            HttpWebRequest request = HttpWebRequest.CreateHttp("https://www.google.com/accounts/ClientLogin");
            request.ContentType = "application/x-www-form-urlencoded";

            request.Method = "POST";

            request.BeginGetRequestStream(searchOnlineRequest, request);



        }
    }
}
 
Share this answer
 
Comments
bagus bujangga 23-Apr-12 9:35am    
if I want post a file, how to do it?
and how about code in PHP server side?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900