please leave a comment so that i know what not to write about

Pages

Friday, December 31, 2010

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

  

Tuesday, December 28, 2010

ParameterLess construct

When I was creating my first cloud app that’s used Microsoft Azure for storage and computation purposes I came across a strange problem which wasn’t related to the Azure itself but was more related to the c# and the .net framework.
When I was writing the code I made a Class which had no parameter less construct. Objects of this class were then used in the program. Because this class was derived from Ienumerator I could actually user Foreach() on the objects of this class but to my surprise the code shown below was showing error at the highlighted line.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;
namespace WebRole1
{
public class mspDataServiceContext : TableServiceContext
{
public mspDataServiceContext(string baseAddress, StorageCredentials credentials)
: base(baseAddress, credentials)
{
}
static int c;
public IQueryable<msp> msps
{
get
{
return this.CreateQuery<msp>("msps");
}
}
static int Count()
{
return c;
}
public int AddMsp(msp m)
{
foreach (msp k in this.msps)
{
if (k.UserId == m.UserId)
return 0;
}
//for (int i = 0; i <mspDataServiceContext.Count(); i++)
//{
// if (m.UserId == msps.ElementAt(i).UserId)
// return 0;
//}
this.AddObject("msps", m);
this.SaveChanges();
c++;
return 1;//indicatiing successful addition
}
public int DeleteMsp(string UserId)
{
foreach (msp k in msps)
{
if (k.UserId == UserId)
{
this.DeleteObject(k);
this.SaveChanges();
c--;
return 1;//indicating sucessful deletion
}
}
return 0;//indicating missing entry
}
public int updateMspLocation(string UserId, double lat, double lon)
{
msp m = null;
foreach (msp k in msps)
{
if (k.UserId == UserId)
{
m = k;
this.DeleteObject(k);
this.SaveChanges();
break;
}
else return 0;
}
m.lat = lat;
m.lon = lon;
this.AddMsp(m);
this.SaveChanges();
return 1;//indicating successful updation
}
public void DeleteAll()
{
foreach (msp m in this.msps)
{
this.DeleteObject(m);
}
The error was later rectified by adding a parameter less construct in the class because the foreach() command was making a msp k in every step and there was no parameterless construct so the compiler wasn’t allowing it to be made.
link to the full project is given below
There was an error in this gadget