Skip to main content

Data manipulation in azure development storage by using web services – workaround


While developing the Azure project this was the biggest problem I came across and being just a newcomer in this area I could not solve it. So I figured a way around that worked perfectly well and then I used it to finally make a working project. Nearly all the solutions I came across in the different portals were about the same problem without the development storage anywhere in question but for the people who first need to make a working solution in the development storage using anything like the VS2010 there was no help nowhere.
The problem was that while accessing data which was stored in a blob in cloud storage through a web service by a Silverlight client. It gives an impression to the storage of the cloud that this is being done by cross site scripting (this is what I got from all the different sources I read) and because this was not allowed the cloud project (webrole in my case) was blocking the request and was returning nothing in return.
So this solution that I figured out is to manually send request on the endpoint exposed by the web service and then retrieve a JSON object as the data.
If you have the similar problem you can use this to
Below is the section of the code in question fully explained. J

private string RootUri
        {
            get
            {
                string scheme = HtmlPage.Document.DocumentUri.Scheme;
                string host = HtmlPage.Document.DocumentUri.Host;
                int port = HtmlPage.Document.DocumentUri.Port;

                string template = "{0}://{1}";
                string uri = string.Format(template, scheme, host);
                if (port != 80 && port != 443)
                    uri += ":" + port;
                return uri + "/";
            }
        }
This piece of code constructs a uri so that every time some data needs to be retrieved this can be used.

void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
           
            Uri getMspListUri = new Uri(RootUri + "Service1.svc/GetMspList");
          
            WebClient getMspListClient = new WebClient();
            getMspListClient.OpenReadCompleted += new OpenReadCompletedEventHandler(getMspListClient_OpenReadCompleted);
            getMspListClient.OpenReadAsync(getMspListUri);
        }

This piece of code here is the code inside the MainPage_loaded event and this code is first creating a Uri object using the root Uri and the endpoint of the webservice. With the function name to be called is the GetMspList (this thing is later explained in this post). After this a Webclient object is made and in its OpenReadCompleted event handler I have given the name of the function to be called. That being getMspListClient_OpenReadCompleted

After this Webclient object is asked to read the data. The first time I was doing it I was praying for it to work because I had put so much in this problem already.

void getMspListClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
           
            Stream stm = e.Result;
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<Dictionary<string, string>>));
            //this object here serializes deserializes the objects that the webservice is sending

            List<Dictionary<string, string>> mspList = (List<Dictionary<string, string>>)ser.ReadObject(stm);
            //this is the peice of data i was receiving

            foreach (var msp in mspList)
            {
                MspPushpin pin = new MspPushpin();
                if (msp["Lat"] != "" && msp["Lon"] != "")
                {
                    Location d = new Location(Convert.ToDouble(msp["Lat"]), Convert.ToDouble(msp["Lon"]));
                    pin.Location = d;
                    pin.Name = msp["FirstName"] + msp["LastName"];
                    pin.UserId = msp["UserId"];
                    pin.EmailAddress = msp["emailAddress"];
                    pin.ImageUri = msp["ImageBlobUri"];

                    ScaleTransform st = new ScaleTransform();
                    st.ScaleX = 0.25;
                    st.ScaleY = 0.25;
                    st.CenterX = (pin as FrameworkElement).Height / 2;
                    st.CenterY = (pin as FrameworkElement).Height / 2;

                    pin.RenderTransform = st;
                    pin.MouseEnter += new MouseEventHandler(pin_MouseEnter);
                    pin.MouseLeave += new MouseEventHandler(pin_MouseLeave);
                    if (d.Latitude == 0 && d.Longitude == 0)
                    { }
                    else
                    {
                        PushPinLayer.AddChild(pin, d);
                    }
                }
            }
            status = "MSP list retrived sucessfully";
        }

The code is explained using the comments within the code.

Now the turn of the code of the webservice sending the data.

[OperationContract]
        [WebGet(UriTemplate = "GetMspList", ResponseFormat = WebMessageFormat.Json)]
        public List<Dictionary<string, string>> GetMspList()
        {
            List<Dictionary<string, string>> mspList = new List<Dictionary<string, string>>();
           
            try
            {
                CloudStorageAccount account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
                mspDataServiceContext context = new mspDataServiceContext(account.TableEndpoint.ToString(), account.Credentials);

                foreach (msp _currentMsp in context.msps)
                {
                    Dictionary<string, string> mspDetails = new Dictionary<string, string>();
                    mspDetails["FirstName"]=_currentMsp.FirstName;
                    mspDetails["LastName"]=_currentMsp.LastName;
                    mspDetails.Add("ImageBlobUri", _currentMsp.ImageBlobUri);
                    mspDetails.Add("emailAddress", _currentMsp.EmailAddress);
                    mspDetails.Add("Lat", _currentMsp.lat.ToString());
                    mspDetails.Add("Lon", _currentMsp.lon.ToString());
                    mspDetails.Add("UserId", _currentMsp.UserId);

                    mspList.Add(mspDetails);
                }
            }
            catch (DataServiceRequestException ex)
            {
                throw ex;
            }

            return mspList;
        }

And this I think is self-explanatory and is just an example of normal code writing In a webservice in c#. if there is some problem in the entire post please mail me or just put a comment :)

following is a link to the complete project

  

Comments

  1. parv sharma is a boombastic hero and the absa"freaking"lutely "wow-man" of the new computer era. watch out all you microsofts, googles, oracles, brutal parv is on the prowl!

    ReplyDelete
  2. oh man... i totally understood this one ! rocks...

    ReplyDelete
  3. Great work yar!!
    this will definitely help many to get out of this prblm!!
    thnks!!! " small box with great knowledge"

    ReplyDelete

Post a Comment

Popular posts from this blog

Customized Online Learning Dangerous as it is Necessary

The recent uprise in Online Learning Platform like Pluralsight, Coursera has raised some important questions over traditional learning system and also on traditional examination systems.
The fact that online learning courses are derived from what users need and not what should be actually taught has also raised serious concerns about what is finally going inside the heads of professionals.

Traditional system while teaching any subject also includes major things that might never be used in real life but still is important to actual context of that particular subject. The syllabus goes through the hands of experts before finally reaching the learners. Online education / Videos have completely disrupted this system and now only what is needed is taught leaving out all the motivational factors and context of the subject that brings glamour and other related attributes to the identity of the subject.

So yes while system has to evolve to teach students more than C++ in today's world bu…

Dynaminism in .Net 4.0

few dayz ago came across THIS question.
the solution to this can easily be figured out by the new dynamic features introduced in .Net 4.0.
i have made a project to demonstrate this.
the main code in the project goes like this

publicstaticdynamic[] GetDynamicObject(DataTable dt, Dictionary<string, string> mapping)
        {
List<dynamic> returnList = newList<dynamic>();
foreach (DataRow row in dt.Rows)
            {
dynamic obj = newExpandoObject();
var objectDic = (IDictionary<string, object>)obj;
foreach (DataColumn column in dt.Columns)
                {
                    objectDic.Add(mapping!=null?mapping.ContainsKey(column.ColumnName) ? mapping[column.ColumnName] : column.ColumnName:column.ColumnName,row[column]);
                }
                returnList.Add(obj);
            }
return returnList.ToArray();
        }The static method here named "GetDynamicObject" simply takes a data table(which can be populated by the data in the database) and a dictionary of…

Problem with Google visualization API- DataTable

One of the most widely charting API is the Google visualization API. Which enables the developers to create charts using
javascript at runtime by supplying the data in a particular format. I had to use this API with ASP.Net. So the major problem in
front of me was how to transfer the data in my database to the client side JavaScript.
Which I could solve by using .ashx pages. I created my own class for
transforming .Net DataTable to a JSON string. The final problem that I faced was that when I transferred the
JSON string to the client side using Jquery AJAX method though it was parsing
the JSON correctly. The Google DataTable was being formed correctly the final
AnnonatedTimeline I was trying to make with that JSON data was showing errors. So
to debug I created a Google DataTable manually and converted it into JSON using
the method it provides. The JSON string that was given out by Google’s very own
DataTable and my JSON string were exact match still, still mine was showing
errors. Aft…