15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

890 ❘ ChaPTer 32 dAtA services<br />

{<br />

class Program<br />

{<br />

static void Main()<br />

{<br />

DataServiceHost host = new DataServiceHost(typeof(MenuDataService),<br />

new Uri[] { new Uri("http://localhost:9000/Samples ") });<br />

host.Open();<br />

Console.WriteLine("service running");<br />

Console.WriteLine("Press return to exit");<br />

Console.ReadLine();<br />

}<br />

}<br />

}<br />

host.Close();<br />

code snippet DataServicesHost/Program.cs<br />

Now you can start the executable <strong>and</strong> request the service with the links http://localhost:9000/Samples/<br />

Menus <strong>and</strong> http://localhost:9000/Samples/Categories from within Internet Explorer. To use Internet<br />

Explorer to see the data returned from the service, you need to deselect the option “Turn on feed reading view.”<br />

To start a listener without elevated administrator rights, you need to confi gure the<br />

ACL for the port <strong>and</strong> the user with netsh http add urlacl url=http://+:9000/<br />

Samples user=username listen=yes. Of course to change these administrative settings,<br />

elevated administrator rights are required.<br />

additional service operations<br />

Instead of offering just the properties from the data model, you can add additional service operations<br />

to the data service. In the sample code, you can see the method GetMenusByName() , which gets a<br />

request parameter from the client <strong>and</strong> returns all menus starting with the requested string with an<br />

IQueryable < Menu > collection. Such operations need to be added to the service operation access rules in the<br />

InitalizeService() method in case you do not offer all service operations using the * .<br />

public class MenuDataService : DataService < MenuCardDataModel ><br />

{<br />

public static void InitializeService(DataServiceConfiguration config)<br />

{<br />

config.SetEntitySetAccessRule("Menus", EntitySetRights.All);<br />

config.SetEntitySetAccessRule("Categories", EntitySetRights.All);<br />

config.SetServiceOperationAccessRule("GetMenusByName",<br />

ServiceOperationRights.All);<br />

}<br />

config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;<br />

}<br />

[WebGet(UriTemplate="GetMenusByNamename={name}",<br />

BodyStyle=WebMessageBodyStyle.Bare)]<br />

public IQueryable < Menu > GetMenusByName(string name)<br />

{<br />

return (from m in CurrentDataSource.Menus<br />

where m.Name.StartsWith(name)<br />

select m).AsQueryable();<br />

}<br />

code snippet DataServicesHost/MenuDataService.cs<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!