Silverlight calling WCF - silverlight

I am new to silverlight, just wanted know if the steps involved in calling the WCF service same in Silverlight as it was in asp or is there any difference.If there is any difference then request you to help me out.
Thanks in advance.

The main things that you needs aware are
silverlight support only basichttpbinding
you need to have either clientaccesspolicy.xml file or crossdomain.xml in your root folder of wcf host server, then only you can successfully call a webservice from silerlight
http://msdn.microsoft.com/en-us/library/cc197955%28v=vs.95%29.aspx

I got the answer, there is slight difference between asp and silverlight.
In silverlight all service calls are asynchronous, so you have to have an eventhandler for when the async call is completed you get your data.
Just a small e.g
When you call your WCF service from asp, you use
proxy_http.FunctionClient fc = new proxy_http.FunctionClient();
txtDisplay.Text = fc.Add(Convert.ToInt32(txtFirst.Text),Convert.ToInt32(txtSecond.Text)).ToString();
in case of Silverlight you will use
private void Add_Click(object sender, RoutedEventArgs e)
{
proxy_htt.FunctionClient fc = new proxy_htt.FunctionClient();
fc.AddCompleted += new EventHandler<proxy_htt.AddCompletedEventArgs>(fc_AddCompleted);
fc.AddAsync(Convert.ToInt32(txtFirst.Text),Convert.ToInt32(txtSecond.Text));
}
void fc_AddCompleted(object sender, proxy_htt.AddCompletedEventArgs e)
{
txtResult.Text = e.Result.ToString();
}

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.

Silverlight Web Service

Below is the code i used to consume web servcie in SilverLight.
private void button1_Click(object sender, RoutedEventArgs e)
{
BasicHttpBinding bind = new BasicHttpBinding();
EndpointAddress endpoint = new EndpointAddress("http://loalhost/Service.asmx");
ServiceSoapClient client = new ServiceSoapClient(bind, endpoint);
client.RunHelloCompleted += new EventHandler<RunHelloCompletedEventArgs>(client_RunQwinCompleted);
client.RunHelloAsync(command);
}
void client_RunHelloCompleted(object sender, RunHelloCompletedEventArgs e)
{
txtProcess.Text=Process(e.Result);
}
I want to know a way that after i run RunHelloAsync(Command), I want to get the returned result without going to Completed event. Please advise me. thank you.
Simple answer : You can't. Everything in Silverlight is Asynchronous so there is no way to block after the client.RunHelloAsync(command) call and wait for the result.
Long answer : There are ways to simulate working with calls in a synchronous fashion, but the calls still being made asynchronously. Take a look at this thread for a few more answers.

Asynchronous Callback method is never called to give results from web service from Silverlight

I'm calling off asynchronously to a web service (Amazon Web Services) from a Silverlight app and my callback method is never actually triggered after I start the asynchronous call.
I've set up another web service proxy in a console app, and I'm able to make a synchronous call and get a response using the same arguments without any issues.
Am I possibly having problems with the fact that this is called from within a browser? I'm not sure where to start, since I don't get a response at all, much less an error.
Below is the code I'm using:
private void btnQueryAmazon_Click(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrEmpty(txtQuery.Text))
{
ItemSearch search = new ItemSearch();
/// set authentication and search parameters
AmazonService.AWSECommerceServicePortTypeClient service = new AmazonService.AWSECommerceServicePortTypeClient();
service.ItemLookupCompleted += new EventHandler<AmazonService.ItemLookupCompletedEventArgs>(service_ItemLookupCompleted);
service.ItemSearchAsync(search);
}
}
void service_ItemLookupCompleted(object sender, AmazonService.ItemLookupCompletedEventArgs e)
{
txtError.Text = e.Result.Items.Count().ToString();
grdItems.ItemsSource = e.Result.Items;
}
Well, there's your problem ;)
It looks like you're calling the ItemSearch method on the service, but you're wiring up and handling the ItemLookup method.
I do it all the time.

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