Sunday, February 24, 2008

Writing a simple c# WebService

If you want to save state from Silverlight between sessions, you will need access to the server’s file system or database. To access either, you will need to create a web service.

In later posts I will discus how to USE the web service from within Silverlight, but for now, this is just how to make a web service in .NET.

Create a new class that extends System.Web.Services.WebService:

using System.Web.Script.Services;

public class ExampleWs : System.Web.Services.WebService



Add four attributes to the class:

[WebService(Namespace = "http://yourSiteName.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[ScriptService] //To allow this Web Service to be called from script, using ASP.NET AJAX
public class ExampleWs : System.Web.Services.WebService



Create a simple method. You want your web methods to be as simple as possible. Don’t make a habit of doing business logic from within a web method, instead, simply call a function from your business logic’s dll.
Here, we will just return the string “Hello World”:

[WebMethod] //attribute needed for method to be visible as a web method
[ScriptMethod] //To allow this Web Method to be called from script, using ASP.NET AJAX
public string HelloWorldExample(bool allCaps)
{
if(allCaps)
return “HELLO WORLD”;
return “Hello World”;
}


From the web service, you are out of the Silverlight sandbox and can access the file system of the server.
To read the files in a directory:

[WebMethod] //attribute needed for method to be visible as a web method
[ScriptMethod] //To allow this Web Method to be called from script, using ASP.NET AJAX
public string[] GetFileNames(string dir)
{
string[] files = {""};
try
{
string path = Server.MapPath(dir).ToString(); //get the path on the server
files = System.IO.Directory.GetFiles(path);
return files;
}
catch (Exception)
{
return files;
}
}


If you publish this web service to a web site, you can call it by simply going to www.yourwebsite.com\ExampleWs.asmx

No comments: