Problem accessing localhost URI from Silverlight - silverlight

(repost because of SO outage; apologies if the other one re-appears)
I'm building a Silverlight app that will run on Azure. My VS solution has two projects: the web role and the Silverlight. The web role has a Service that works. (I can go to localhost:88/expenseservice.svc/expenses and get the data I want.)
I am trying to access that data from Silverlight:
private void MainPage_Loaded(object sender, RoutedEventArgs args)
{
WebClient data = new WebClient();
data.DownloadStringCompleted += new DownloadStringCompletedEventHandler(data_DownloadStringCompleted);
Uri dataSource = new Uri("localhost:88/expenseservice.svc/expenses");
data.DownloadStringAsync(dataSource);
}
void data_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.InnerException.Message);
return;
}
// ...
}
However, this does not work. The message box shows the error:
The URI prefix is not recognized.
Here is the full exception:
e.Error.InnerException = {System.NotSupportedException: The URI prefix is not recognized.
at System.Net.WebRequest.Create(Uri requestUri)
at System.Net.WebClient.GetWebRequest(Uri address)
at System.Net.WebClient.DownloadStringAsync(Uri address, Object userToken)}
Is it complaining about localhost? Am I supposed to be doing something differently? Perhaps this is what "Add Service Reference" is for?

I think the prefix is not recognized because it is missing. The prefix should be the first part that describes what kind of service your URI is pointing to. For example http:// of svn:// and so on..
Just add the right one and it should work.. (I've never used Silverlight neither anything Microsoftish so I'm just guessing)

Related

Accessing Webservices from Silverlight - Security Issue

I am trying to get a simple WebClient call working from Silverlight to youtube. I lifted the code from the Microsoft Silverlight site.
Here is the code:
private void SearchTrack_Click(object sender, RoutedEventArgs e)
{
Uri serviceUri = new Uri("https://www.googleapis.com/youtube/v3/search?part=id%2Csnippet&q=sara+smile&key=AAAAAAAAAAAAAAA");
WebClient downloader = new WebClient();
downloader.OpenReadCompleted += new OpenReadCompletedEventHandler(downloader_OpenReadCompleted);
downloader.OpenReadAsync(serviceUri);
}
void downloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
Stream responseStream = e.Result;
// Continue working with responseStream here...
}
}
The call fails with the following error:
[System.Security.SecurityException] = {System.Security.SecurityException ---> System.Security.SecurityException: Security error.
at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClassa.
If I just hit the URL from my browser the JSON is returned without an issue.
I am running the application from VS/Cassini so I don't think it is the FIle system problem identified at http://blogs.msdn.com/b/silverlightws/archive/2008/03/30/some-tips-on-cross-domain-calls.aspx.
Any help would be greatly appreciated.
Barry
Here it's said, that it's not possible so easy to interract with google apis from silverlight because of corssdomain access restrictions. You need to add some intermidiate WCF-service, through which Your SL-app will communicate with youtube api.

Silverlight application ria service list files in service side

Having a silverlight application, intended to implement backup restore mechanism for the end user.
I have to get list of files in a specific directory resided in WebSite project via ria services.
By using which object I will be able to list files in specific directory of WebSite project.
Thanks for your attention.
You can use the Directory class to enumerate files on the server. Adding a method to your domain service to return the list of file names to the Silverlight client should be fairly trivial after that.
http://msdn.microsoft.com/en-us/library/system.io.directory(v=vs.100).aspx
The answer is some kind of hack. I was inspired by the method that I have used to send client IP address to the service.
In default.aspx add this param to your silverlight object :
<param name="initParams" value="clientIP=<%=Request.UserHostAddress%>,serverPath=<%=Server.MapPath(".")%>" />
And in silverlight application :
public string ClientIP=string.Empty;
public string ServerPath = string.Empty;
private void Application_Startup(object sender, StartupEventArgs e)
{
this.RootVisual = new MainPage();
try
{
ClientIP = e.InitParams["clientIP"].ToString();
ServerPath = e.InitParams["serverPath"].ToString();
}
catch
{
}
}
Consider that I sent client ip to the xap file for logging issues. You can omit it if you care.
and in Silverlight application call service method in this way :
ser.GetFileList(((App)(App.Current)).ServerPath, FilesListReceived, null);
And the service side :
public List<string> GetFileList(string baseDirectory)
{
var result = new List<BRFile>();
var files =Directory.EnumerateFiles( baseDirectory + "\\DBBackup" );
....
}
Good Luck.

Using Silverlight 4 WebClient OpenReadCompleted throughs Security Exceptions on hosted web server. What's the pronblem?

Seems to be a simple thing using a WebClient object to retrieve content of a text file in a Silverlight web application.
It works in our intranet setup on a local server, but when deployed on a hosted "hostgator" server, WebClient gets a security exception. Following suggestions from numerous web blogs, I tried crossdomain access policy and crossdomain.xml with no result - no wonder, all in on the same domain.
private void LoadCSVFile(string csvFile)
{
try
{
WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri(csvFile, UriKind.Absolute));
}
catch (Exception ex)
{
string errorMessage = String.Format("Ex accessing csv: {0}\n{1}", csvFile,
}
}
//the csvFile is an absolute path: http://myserver.com/myapplication:port/sourcefiles/file.csv
//The sourcefiles is a virtual directory in the same website containing csv files
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
try
{
using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Result))
{
mainFileData = new List<string>();
string line;
}
}
catch (Exception ex)
{
string errorMessage = ex.InnerException;
}else
{
"here is the place for the exception!!!!!!! so, e.Error is not null"
}
}
The text of the exception reads: System.SecurityException: Security error at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult) etc.
Spend 2 days gooogling with no result.
Please help.
V
A couple of things to check:
(1) The format for the URL that you list (http://myserver.com/myapplication:port/sourcefiles/file.csv) looks odd. Shouldn't it be http://myserver.com:port/myapplication/sourcefiles/file.csv? Or is that just a typo?
(2) What's the port number that you're accessing? The Silverlight WebClient will only access ports 80 and 443.
(3) Can you get to the file using a direct URL? Sometimes web servers need to be told about a specific file type before they'll allow it to be served up.

Silverlight 3 Out of the Browser Updates

I have a few users that are using a silverlight app that aren't recieving updates when a new release is published. Isn't this suppose to be automatic or perhaps I'm missing an option somewhere? I was also starting to think that maybe the XAP file is cached and I some how need to prevent that.
Any thoughts out there?
You need to write a few lines of code.
If you're familiar with 'one click' deployment then some of the options you're used to don't exist in Silverlight. You need to write the code yourself.
http://nerddawg.blogspot.com/2009/07/silverlight-out-of-browser-apps-how.html
private void Application_Startup(object sender, StartupEventArgs e)
{
this.RootVisual = new MainPage();
if (Application.Current.IsRunningOutOfBrowser)
{
Application.Current.CheckAndDownloadUpdateAsync();
}
and then in your App() constructor :
Application.Current.CheckAndDownloadUpdateCompleted +=
new CheckAndDownloadUpdateCompletedEventHandler(Current_CheckAndDownloadUpdateCompleted);
and an event handler :
void Current_CheckAndDownloadUpdateCompleted(object sender, CheckAndDownloadUpdateCompletedEventArgs e)
{
// http://nerddawg.blogspot.com/2009/07/silverlight-out-of-browser-apps-how.html
if (e.UpdateAvailable)
{
MessageBox.Show("The application has been updated! Please close and reopen it to load the new version.");
}
else if (e.Error != null && e.Error is PlatformNotSupportedException)
{
MessageBox.Show("An application update is available, " +
"but it requires a new version of Silverlight. " +
"Please contact tech support for further instructions.");
}
}
It only auto updates if the developer performs the CheckAndDownloadUpdateAsync() call. See updates: http://timheuer.com/blog/archive/2009/07/10/silverlight-3-released-what-is-new-and-changed.aspx#oob

Download a html file in Silverlight

I'm trying to use the WebClient class to download a html file from another website and present it as a text stream, But I'm getting a security error, what am I doing wrong, or is this another one of Silverlights security "Features"
[code]
namespace ImageScrape
{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
WebClient cl = new WebClient();
cl.OpenReadCompleted += new OpenReadCompletedEventHandler(cl_OpenReadCompleted);
cl.OpenReadAsync(new Uri(#"http://www.google.co.uk/",UriKind.Absolute));
}
void cl_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
testTextBlock.Text = e.Result.ToString();
}
}
}
[/code]
EDIT
Thanks guys, I was really hoping I wouldn't have to create this as a WCF service as 1) I only know the basics and 2) The idea is that you can use this .xap without having to connect to a central server, mainly because for this I don't have a server that I could host a WCF service on.
Does anyone know a way to get around this, or anywhere that would host a WCF service for free?
I think there are security issues with going directly to another site from the silverlight client.
The best work around for this would be to move this code into a web service and then serve the content you require to client from there.

Resources