I created a simple SL 4 app to connect to Google Analytics but I keep getting the following exception:
{System.Security.SecurityException: Security error.
at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at GoogleAnalytics.Silverlight.MainPage.<>c__DisplayClass4.<GetResponseCallback>b__3()}
I think it has something to do with xss but I’m not sure how to get around that. The following code works fine in a console app but doesn’t in SL.
The UI has a textblock control, here’s the code:
private byte[] _data;
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
string requestData = "Email=email@gmail.com" +
"&Passwd=password" +
"&source=Test-App" +
"&accountType=GOOGLE" +
"&service=analytics";
_data = Encoding.UTF8.GetBytes(requestData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri("https://www.google.com/accounts/ClientLogin", UriKind.Absolute));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = _data.Length;
request.BeginGetRequestStream(GetRequestStreamCallback, request);
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
this.Dispatcher.BeginInvoke(() =>
{
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream stream = request.EndGetRequestStream(asynchronousResult);
stream.Write(_data, 0, _data.Length);
stream.Close();
request.BeginGetResponse(GetResponseCallback, request);
}
catch (Exception e)
{
textBlock.Text = e.ToString();
}
});
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
this.Dispatcher.BeginInvoke(() =>
{
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream stream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);
textBlock.Text = streamReader.ReadToEnd().Split(new string[] { "Auth=" }, StringSplitOptions.None)[1];
streamReader.Close();
response.Close();
}
catch (Exception e)
{
textBlock.Text = e.ToString();
}
});
}
Update: fixed a typo.
Thanks
Silverlight cannot connect to GA services, I either have to use a service or JavaScript then pass the data to Silverlight.