Silverlight application ria service list files in service side - silverlight

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.

Related

Specflow-Share browser session between features if triggered between steps

I have implemented Specflow to reuse some steps across features as in this example -Specflow,Selenium-Share data between different Step definitions or classes .Since, in our project, we are integrating multiple features & reusing them. What is the best way to share browser session across features if its triggered in between steps as per the above approach?
My Scenario:
Once an application created, I need to launch new session, login different User-set different services and approve it.
But after logging in fails with below error on Step definition 4 in reused Whenstep of Given(Set the service to (.*)). That particular step is from different feature, hence the new session needs to be used in those steps. The LaunchURl method below is just launching the website with url, no new session created - This works fine
OpenQA.Selenium.WebDriverException : Unexpected error. System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it "IP here"
[Given(#"A New Application is added")]
public void GivenANewApplicationIsAdded()
{
Given("UK_The Service is set");
Given("User Navigated to New Application screen");
When("User fills up form as in data row 1");
Then("new SID generated");
}
[Given(#"New Browser Launched")]
public void GivenNewBrowserLaunched()
{
SeleniumContext sl = new SeleniumContext();
this.seleniumContext = sl;
}
[Given(#"Login is successful with ""(.*)"" and ""(.*)""")]
public void GivenLoginIsSuccessfulWithAnd(string userName, string password)
{
SuperTests spr = new SuperTests();
_driver = spr.LaunchURL(seleniumContext.WebDriver);
//seleniumContext.WebDriver = _driver;
LoginPage lg = new LoginPage(_driver);
lg.LoginProcess(userName, password);
}
[Given(#"Set the service to ""(.*)""")]
public void GivenSetTheServiceTo(string serviceId)
{
When("Select a Service from the option "+serviceId);
Then("The Services is changed to the one selected " + serviceId);
}
In other feature
[When(#"Select a Service from the option (.*)")]
public void WhenSelectAServiceFromTheOptionTestTeam(string p0)
{
HomePage mst = new HomePage(seleniumContext.WebDriver);
mst.SetServiceId(p0);
}
The 2 work around what we figured was
Create a new instance of binding class to call the methods or steps as shown below
[Given(#"Set the service to ""(.*)""")]
public void GivenSetTheServiceTo(string serviceId)
{
var serIdSteps = new UK_SetServiceIDSteps(seleniumContext);
serIdSteps.WhenUK_SelectAServiceFromTheOptionTest(serviceId);
serIdSteps.ThenUK_TheServicesIsChangedToTheOneSelected(serviceId);
}
or
tried this which worked as well- basically calling a new method to create a new session. for this I need not create any new instance for Binding class. Called the Step directly.
[Given(#"New Browser Launched")]
public void GivenNewBrowserLaunched()
{
SuperTests spr = new SuperTests();
_driver = spr.LaunchURL("Firefox");
seleniumContext.WebDriver = _driver;
}
public void GivenSetTheServiceTo(string serviceId)
{
When("UK_Select a Service from the option "+serviceId);
Then("UK_The Services is changed to the one selected " + serviceId);
}
Not sure, which is correct way of doing it? Trying to figure it out from Reusable steps point?The latter one is not advised as we need to change the type of browser to launch at multiple place.

Using the same class library in windows application and web service

I working with:
Class Library: Model.dll
using System;
using System.Collections.Generic;
using System.Text;
namespace root
{
public class Customer
{
private int _Id;
public int Id
{
get { return _Id; }
set { _Id = value; }
}
private string _Name;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
}
}
ASP.NET Web Service with reference to Model.dll so i can use in web method:
[WebMethod]
public string HelloWorld(root.Customer customer) {
return "Hello World";
}
Windows Application with reference to both Model.dll and Web Service (1).
root.Customer newCustomer = new Customer();
newCustomer.Id = 1;
newCustomer.Name = "Name";
ws.Service ws = new root.ws.Service();
ws.HelloWorld(newCustomer);
^ problem here
Error: Argument '1': cannot convert from 'root.Customer' to 'root.ws.Customer'
(1) Right click -> And Web Reference -> Web services in this solution -> Click Service.asmx ->
Enter Web reference name: ws -> Click Add reference
Updated: I can change line in generated Reference.cs file from
public string HelloWorld(Customer customer)
to
public string HelloWorld(root.Customer customer)
So function will be looking for real model instead of proxy object, but is not real answer.
I don't event think about editing this file after each web reference update.
How to force this for using real model?
I am afraid that reusing types in automatically generated ASMX proxies is impossible.
There are three options.
1) write your own code generator that will act like the wsdl.exe i.e. build a proxy of your web service but reusing your specified types
(rather difficult)
2) write your own code rewriter that will rewrite proxies generated automatically to use your own types. You'd invoke such rewriter each time after you build up your reference to the web service
(still tedious)
3) switch to WCF web services. a WCF service on a basicHttpBinding is semantically equivalent to a ASMX web service (uses the same communication protocol based on http + soap) but the WCF service metadata contain more information about types so that the proxy generator is able to "reuse types from referenced assemblies".
(suggested approach)
If you switch away from asmx and start using WCF's svc model, you can share a library between the server and client without much fuss at all. If that is an option, there are plenty of resources to help you out with WCF online.

silverlight 4, dynamically loading xap modules

I know that it is possible to load xap modules dynamically using Prism or MEF framework. However, I'd like not to use those frameworks; instead load my xap files manually. So, I created the following class (adapted from internet):
public class XapLoader
{
public event XapLoadedEventHandler Completed;
private string _xapName;
public XapLoader(string xapName)
{
if (string.IsNullOrWhiteSpace(xapName))
throw new ArgumentException("Invalid module name!");
else
_xapName = xapName;
}
public void Begin()
{
Uri uri = new Uri(_xapName, UriKind.Relative);
if (uri != null)
{
WebClient wc = new WebClient();
wc.OpenReadCompleted += onXapLoadingResponse;
wc.OpenReadAsync(uri);
}
}
private void onXapLoadingResponse(object sender, OpenReadCompletedEventArgs e)
{
if ((e.Error == null) && (e.Cancelled == false))
initXap(e.Result);
if (Completed != null)
{
XapLoadedEventArgs args = new XapLoadedEventArgs();
args.Error = e.Error;
args.Cancelled = e.Cancelled;
Completed(this, args);
}
}
private void initXap(Stream stream)
{
string appManifest = new StreamReader(Application.GetResourceStream(
new StreamResourceInfo(stream, null), new Uri("AppManifest.xaml",
UriKind.Relative)).Stream).ReadToEnd();
XElement deploy = XDocument.Parse(appManifest).Root;
List<XElement> parts = (from assemblyParts in deploy.Elements().Elements()
select assemblyParts).ToList();
foreach (XElement xe in parts)
{
string source = xe.Attribute("Source").Value;
AssemblyPart asmPart = new AssemblyPart();
StreamResourceInfo streamInfo = Application.GetResourceStream(
new StreamResourceInfo(stream, "application/binary"),
new Uri(source, UriKind.Relative));
asmPart.Load(streamInfo.Stream);
}
}
}
public delegate void XapLoadedEventHandler(object sender, XapLoadedEventArgs e);
public class XapLoadedEventArgs : EventArgs
{
public Exception Error { get; set; }
public bool Cancelled { get; set; }
}
The above code works fine; I can load any xap the following way:
XapLoader xapLoader = new XapLoader("Sales.xap");
xapLoader.Completed += new XapLoadedEventHandler(xapLoader_Completed);
xapLoader.Begin();
Now, I have a UserControl called InvoiceView in the Sales.xap project, so I would like to instantiate the class. In the current project (Main.xap) I added reference to Sales.xap project, however, since I load it manually I set "Copy Local = False". But when executed, the following code throws TypeLoadException:
Sales.InvoiceView view = new Sales.InvoiceView();
It seems the code can't find InvoiceView class. But I checked that XapLoader's initXap() method was successfully executed. So why the code can't find InvoiceView class? Can someone help me with this problem?
This is based on the asker's self-answer below, rather than the question.
If you delete a project/module the output DLLs/XAP files do hang around. If you click the "show all files" button you will see some these left-over output files in your clientbin, bin and obj folders of related projects.
You can delete them individually from the project, or, when in doubt, search for all BIN and OBJ (e.g. using desktop explorer) and delete all those folders. The BIN/CLIENTBIN/OBJ folders will be recreated when needed (this the job that the "clean" option in Visual Studio should have done!)
Hope this helps.
Ok, I found the cause. The above code works. After creating a new silverlight project (Sales.xap) I happened to compile my solution once. Then I deleted App class in the Sales.xap and renamed default MainPage class to SalesView. However, no matter how many times I compile my solution, Visual Studio's development web server was loading the first version of Sales.xap (where from?), so my code couldn't find SalesView. In my host Asp.Net project I set development server's port to a different port number, and the problem gone. So the problem was with Visual Studio's development server. Apparently it is keeping compiled xap files in some temporary folder, and doesn't always update those xap files when source code changed.
What I do to avoid such problems when executing freshly compiled Silverlight is clear the browser cache, chrome even has a clear silverlight cache ;)
this XAP Cache phenomena is often due to the visual studio embedded web server (ASP.NET Development Server).
Just stop the occurence of this server and the cache will be cleared.
Start again your project and the latest build of your xap is called.

Call a web service from a Windows Application

I am new to .NET and C#. I created a Web service, and I am able to view it from a Web page. When I try to call it from a Windows Application, I get the Exception 401 : unauthorized. Code compiles OK, but throws exception when running. This is the code from the Windows App. :
namespace BookStore
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Create a new instance of a service
localhost.Service1 datasvc = new localhost.Service1();
// Create instance of dataset, using WebService method GetTitleAuthors.
DataSet myData = datasvc.GetTitleAuthors();
// Set DataGrid's datasource to the myData DataSet.
dataGridView1.DataSource = myData;
//Expand all rows.
//dataGridView1.Expand(-1);
//Expand DataTable
//dataGridView1.NavigateTo(0, "Authors");
}
}
}
PS : I am using Windows Authentication in the website that hosts the web service.
I believe there is a property on the generated proxy to the effect of UseDefaultCredentials try setting that to true.
datasvc.UseDefaultCredentials = true;
Although it's been a while I think this will force the service to pass windows credentials.
I don't know what type your Service1 object inherits so I can't say what properties or methods you have associated with it, but whenever I know you can make calls to you web service with using
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);
And then either using
req.UseDefaultCredentials = true;
or
req.Credentials = new NetworkCredential(userName, password);

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