Search Results

Search found 66 results on 3 pages for 'webget'.

Page 1/3 | 1 2 3  | Next Page >

  • WCF ResponseFormat For WebGet

    - by michael lucas
    WCF offers two options for ResponseFormat attribute in WebGet annotation in ServiceContract. [ServiceContract] public interface IService1 { [OperationContract] [WebGet(UriTemplate = "greet/{value}", BodyStyle = WebMessageBodyStyle.Bare)] string GetData(string value); [OperationContract] [WebGet(UriTemplate = "foo", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)] string Foo(); The options for ResponseForamt are WebMessageFormat.Json and WebMessageFormat.Xml. Is it possible to write my own web message format? I would like that when client calls foo() method he gets raw string - without json or xml wrappers.

    Read the article

  • OData and custom WCF WebGet methods

    - by reinier
    I've created an OData endpoint (using entity framework, WCF data service) and added a custom test WebGet test method like so: [WebGet(UriTemplate = "{text}")] public IQueryable<string> SplitString(string text) { if (text == null) throw new DataServiceException("text not specified"); var result = (from s in text.Split('-') orderby s select s); return result.AsQueryable(); } and a config line: config.SetServiceOperationAccessRule("SplitString", ServiceOperationRights.All); However, no matter how I specify the url, I can not get the text param to be filled out. (it is always null). so: http://localhost/myservice.svc/SplitString/testtext does not work. What is the correct url format (or UriTemplate) one should use? The only examples I found of odata and WebGet only have an example method which doesn't have any parameters.

    Read the article

  • Serializing data using IEnumerable<T> with WebGet

    - by Jim
    possible duplicate: Cannot serialize parameter of type ‘System.Linq.Enumerable… ’ when using WCF, LINQ, JSON Hi, If my method signiature looks like this, it works fine. [WebGet] MyClass[] WebMethod() If the signiature looks like this [WebGet] IEnumerable<T> WebMethod() I get the following error: Cannot serialize parameter of type 'X.Y.Z.T+<WebMethod>d__2c' (for operation 'WebMethod', contract 'IService') because it is not the exact type 'System.Collections.Generic.IEnumerable`1[X.Y.Z.T]' in the method signature and is not in the known types collection. In order to serialize the parameter, add the type to the known types collection for the operation using ServiceKnownTypeAttribute. I have tried adding. ServiceKnownType(typeof(IEnumerable)) Same error. Is this a bug in 2010 beta 2, or is this likely to be correct going forward? Thanks

    Read the article

  • Ado.net dataservices BeginExecuteBatch call works on development fails on production server with Obj

    - by Mike Morley
    We have an ado.net dataservices 1.0 call that is being passed to a [WebGet] service operation as a batch through BeginExecuteBatch. Everything works perfectly on our development server - we have the project configured to use IIS instead of the cassini web server to make it as close to our production server as we can. When we publish to the production server, all the service operations work perfectly except the batch call, which fails with Object does not match target type. . I have not been able to find any cause for this. I can even run a single non-batch style GET operation against the [WebGet] service by copying the URL used in the batch and pasting it in a browser. I have not been able to find any information to help me solve this - any guidance would be most appreciated. Thanks, Mike M. Error message From Fiddler: HTTP/1.1 500 Internal Server Error Content-Type: application/xml DataServiceVersion: 1.0; An error occurred while processing this request. Object does not match target type. System.Reflection.TargetException at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.Data.Services.RequestUriProcessor.CreateFirstSegment(IDataService service, String identifier, Boolean checkRights, String queryPortion, Boolean& crossReferencingUrl) at System.Data.Services.RequestUriProcessor.CreateSegments(String[] segments, IDataService service) at System.Data.Services.RequestUriProcessor.ProcessRequestUri(Uri absoluteRequestUri, IDataService service) at System.Data.Services.DataService`1.BatchDataService.HandleBatchContent(Stream responseStream)

    Read the article

  • Dataset bind to Gridview within WCF REST retrieval method and Linq to Sql

    - by user643794
    I used a WCF REST template to build a WCF service library to create PUT and GET calls. PUT method works fine sending my blob to a database. On the GET, I want to be able to access the web service directly and display the results from a stored procedure as a dataset and bind this to a gridview. The stored procedure is a simple select statement, returning three of the four columns from the table. I have the following: [WebGet(UriTemplate = "/?name={name}", ResponseFormat = WebMessageFormat.Xml)] public List<Object> GetCollection(string name) { try { db.OpenDbConnection(); // Call to SQL stored procedure return db.GetCustFromName(name); } catch (Exception e) { Log.Error("Stored Proc execution failed. ", e); } finally { db.CloseDbConnection(); } return null; } I also added Linq to SQL class to include my database table and stored procedures access. I also created the Default.aspx file in addition to the other required files. protected void Page_Load(object sender, EventArgs e) { ServiceDataContext objectContext = new ServiceDataContext(); var source = objectContext.GetCustFromName("Tiger"); Menu1.DataSource = source; Menu1.DataBind(); } But this gives me The entity type '' does not belong to any registered model. Where should the data binding be done? What should be the return type for GetCollection()? I am stuck with this. Please provide help on how to do this.

    Read the article

  • Any ideas on a WCF Interceptor for a REST WebGet request to change the Url/Querystring parameters

    - by REA_ANDREW
    Does any one know of a way I can intercept a REST Get request inside WCF, so for example I could change the value of any of the querystring parameters. So I need to have some code run, prior to WCF Evaluating the UriTemplate of the WebGet attribute and be able to edit it, before returning the value which it will use to continue processing the request. Any help would be greatly appreciated Andrew

    Read the article

  • Is it possible to set ContentType for a WCF WebGet method?

    - by James Cadd
    I'm working with a WCF restful/http method that returns a stream of image data. I want to make sure that the content type is marked as "image/png". The method is defined as: [ServiceContract] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] public class TileImageService { [WebGet(UriTemplate = "{id}")] public Stream GetTileImage(string id) { Bitmap bmp = new Bitmap(173, 173); Graphics g = Graphics.FromImage(bmp); g.Clear(Color.Blue); g.DrawString(DateTime.Now.ToLongTimeString(), new Font("Chiller", 20), Brushes.White, new PointF(10, 10)); g.Flush(); MemoryStream ms = new MemoryStream(); bmp.Save(ms, ImageFormat.Png); ms.Seek(0, SeekOrigin.Begin); return ms; } } In Firefox it looks like the content type is marked as application/octet stream. Is there a way to change the content type?

    Read the article

  • How to call a service operation at a REST style WCF endpoint uri?

    - by Dieter Domanski
    Hi, is it possible to call a service operation at a wcf endpoint uri with a self hosted service? I want to call some default service operation when the client enters the endpoint uri of the service. In the following sample these uris correctly call the declared operations (SayHello, SayHi): - http://localhost:4711/clerk/hello - http://localhost:4711/clerk/hi But the uri - http://localhost:4711/clerk does not call the declared SayWelcome operation. Instead it leads to the well known 'Metadata publishing disabled' page. Enabling mex does not help, in this case the mex page is shown at the endpoint uri. private void StartSampleServiceHost() { ServiceHost serviceHost = new ServiceHost(typeof(Clerk), new Uri( "http://localhost:4711/clerk/")); ServiceEndpoint endpoint = serviceHost.AddServiceEndpoint(typeof(IClerk), new WebHttpBinding(), ""); endpoint.Behaviors.Add(new WebHttpBehavior()); serviceHost.Open(); } [ServiceContract] public interface IClerk { [OperationContract, WebGet(UriTemplate = "")] Stream SayWelcome(); [OperationContract, WebGet(UriTemplate = "/hello/")] Stream SayHello(); [OperationContract, WebGet(UriTemplate = "/hi/")] Stream SayHi(); } public class Clerk : IClerk { public Stream SayWelcome() { return Say("welcome"); } public Stream SayHello() { return Say("hello"); } public Stream SayHi() { return Say("hi"); } private Stream Say(string what) { string page = @"<html><body>" + what + "</body></html>"; return new MemoryStream(Encoding.UTF8.GetBytes(page)); } } Is there any way to disable the mex handling and to enable a declared operation instead? Thanks in advance, Dieter

    Read the article

  • WCF service - HTTP500

    - by ilkin
    Hi guys, I need help with wcf service. i have a ajax-enabled wcf service: public class AddFavorites : Page { // Add [WebGet] attribute to use HTTP GET [WebGet(RequestFormat = WebMessageFormat.Json)] [OperationContract] public void AddFavorite() { this.AddMyFavorite(10, "sometext", "sometext"); } } And clientside looks like this: function AddFavorite() { $.ajax({ type: "GET", url: "/WebServices/AddFavorites.svc/AddFavorite", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", cache: false }); }; Im using fiddler to trace the application and i always get HTTP500. The class is inherited from Page class and uses the AddMyFavorite method that takes care of database. Website is hosted on iis7

    Read the article

  • Custom Logic and Proxy Classes in ADO.NET Data Services

    - by rasx
    I've just read "Injecting Custom Logic in ADO.NET Data Services" and my next question is, How do you get your [WebGet] method to show up in the client-side proxy classes? Sure, I can call this directly (RESTfully) with, say, WebClient but I thought the strong typing features in ADO.NET Data Services would "hide" this from me auto-magically. So here we have: public class MyService : DataService<MyDataSource> { // This method is called only once to initialize service-wide policies. public static void InitializeService(IDataServiceConfiguration config) { config.SetEntitySetAccessRule("Customers", EntitySetRights.AllRead); config.SetServiceOperationAccessRule("CustomersInCity", ServiceOperationRights.All); } [WebGet] public IQueryable<MyDataSource.Customers> CustomersInCity(string city) { return from c in this.CurrentDataSource.Customers where c.City == city select c; } } How can I get CustomersInCity() to show up in my client-side class defintions?

    Read the article

  • How to return Json from WCF Service?

    - by Zinoo
    Hi, I have the piece of code below of a template Ajax enabled WCF service. What can i do to make it return JSon instead of XML? thanks. using System; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Activation; [ServiceContract(Namespace = "WCFServiceEight")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class CostService { // Add [WebGet] attribute to use HTTP GET [OperationContract] [WebGet] public double CostOfSandwiches(int quantity) { return 1.25 * quantity; } }

    Read the article

  • WCF Rest Service Date issue

    - by Ranish
    I am working on a WCF Rest service for a iPhone application. I have a WebGet method which returns a “date time”. I am using following code [OperationContract] [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "GetDate")] DateTime GetDate(); When I tried to call the method using Mozilla rest client I am able to get following result "/Date(1355116291037+0530)/" But the problem is when this method consume from the iPhone side we are getting another date time value( there is around 5:30 hours difference) . Any one have any idea regarding this issue,Please help me Thanks in advance

    Read the article

  • Combined SOAP/JSON/XML in WCF, using UriTemplate

    - by gregmac
    I'm trying to build a generic web service interface using WCF, to allow 3rd party developers to hook into our software. After much struggling and reading (this question helped a lot), I finally got SOAP, JSON and XML (POX) working together. To simplify, here's my code (to make this example simple, I'm not using interfaces -- I did try this both ways): <ServiceContract()> _ Public Class TestService Public Sub New() End Sub <OperationContract()> _ <WebGet()> _ Public Function GetDate() As DateTime Return Now End Function '<WebGet(UriTemplate:="getdateoffset/{numDays}")> _ <OperationContract()> _ Public Function GetDateOffset(ByVal numDays As Integer) As DateTime Return Now.AddDays(numDays) End Function End Class and the web.config code: <services> <service name="TestService" behaviorConfiguration="TestServiceBehavior"> <endpoint address="soap" binding="basicHttpBinding" contract="TestService"/> <endpoint address="json" binding="webHttpBinding" behaviorConfiguration="jsonBehavior" contract="TestService"/> <endpoint address="xml" binding="webHttpBinding" behaviorConfiguration="poxBehavior" contract="TestService"/> <endpoint address="mex" contract="IMetadataExchange" binding="mexHttpBinding" /> </service> </services> <behaviors> <endpointBehaviors> <behavior name="jsonBehavior"> <enableWebScript/> </behavior> <behavior name="poxBehavior"> <webHttp /> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="TestServiceBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> </behaviors> This actually works -- I'm able to go to TestService.svc/xml/GetDate for xml, TestService.svc/json/GetDate for json, and point a SOAP client at TestService.svc?wsdl and have the SOAP queries work. The part I'd like to fix is the queries. I have to use TestService.svc/xml/GetDateOffset?numDays=4 instead of TestService.svc/xml/GetDateOffset/4. If I specify the UriTemplate, I get the error: Endpoints using 'UriTemplate' cannot be used with 'System.ServiceModel.Description.WebScriptEnablingBehavior'. But of course without using <enableWebScript/>, JSON doesn't work. The only other thing I've seen that I think will work is making 3 different services (.svc files), that all implement an interface that specifies the contract, but in the classes specify different WebGet/WebInvoke attributes on each class. This seems like a lot of extra work, that frankly, I don't see why the framework doesn't handle for me. The implementation of the classes would all be the same, except for the attributes, which means over time it would be easy for bugs/changes to get fixed/done in one implementation but not the others, leading to inconsistent behaviour when using the JSON vs SOAP implementation for example. Am I doing something wrong here? Am I taking a totally wrong approach and misusing WCF? Is there a better way to do this? With my experience doing web stuff, I think it should be possible for some kind of framework to handle this ... I even have an idea in my head of how to build it. It just seems like WCF is supposed to be doing this, and I don't really want to reinvent the wheel.

    Read the article

  • WCF 405 Method Not Allowed Crazy Error Help!

    - by devmania
    hi, i am going crazy i have read like 10s of articles also on stackoverflow about that i am calling webservice in restful way and should enable this in service and in webconfig, so i did that but as soon as i add the [WebGet()] Attribute i get this crazy error if i remove it then the service get called seamlessly i am using VS 2010 RC 1 IIS 7 Windows 7 here is my code [ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode =AspNetCompatibilityRequirementsMode.Allowed)] public class Service2 { [OperationContract] [WebGet()] public List<Table1> GetCustomers(string numberToFetch) { using (DataClassesDataContext context = new DataClassesDataContext()) { return context.Table1s.Take(numberToFetch).ToList( ); } } } and my ASPX page Code <body xmlns:sys="javascript:Sys" xmlns:dataview="javascript:Sys.UI.DataView"> <div id="CustomerView" class="sys-template" sys:attach="dataview" dataview:autofetch="true" dataview:dataprovider="Service2.svc" dataview:fetchParameters="{{ {numberToFetch: 2} }}" dataview:fetchoperation="GetCustomers"> <ul> <li>{{name}}</li> </ul> </div> and my Web.config code <system.serviceModel> <behaviors> <endpointBehaviors> <behavior name="Service2AspNetAjaxBehavior"> <enableWebScript /> </behavior> </endpointBehaviors> </behaviors> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> <services> <service name="Service2"> <endpoint address="" behaviorConfiguration="Service2AspNetAjaxBehavior" binding="webHttpBinding" contract="Service2" /> </service> </services> </system.serviceModel> totally appreciate the help

    Read the article

  • How can I return json from my WCF rest service (.NET 4), using Json.Net, without it being a string,

    - by Samuel Meacham
    The DataContractJsonSerializer is unable to handle many scenarios that Json.Net handles just fine when properly configured (specifically, cycles). A service method can either return a specific object type (in this case a DTO), in which case the DataContractJsonSerializer will be used, or I can have the method return a string, and do the serialization myself with Json.Net. The problem is that when I return a json string as opposed to an object, the json that is sent to the client is wrapped in quotes. Using DataContractJsonSerializer, returning a specific object type, the response is: {"Message":"Hello World"} Using Json.Net to return a json string, the response is: "{\"Message\":\"Hello World\"}" I do not want to have to eval() or JSON.parse() the result on the client, which is what I would have to do if the json comes back as a string, wrapped in quotes. I realize that the behavior is correct; it's just not what I want/need. I need the raw json; the behavior when the service method's return type is an object, not a string. So, how can I have my method return an object type, but not use the DataContractJsonSerializer? How can I tell it to use the Json.Net serializer instead? Or, is there someway to directly write to the response stream? So I can just return the raw json myself? Without the wrapping quotes? Here is my contrived example, for reference: [DataContract] public class SimpleMessage { [DataMember] public string Message { get; set; } } [ServiceContract] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] public class PersonService { // uses DataContractJsonSerializer // returns {"Message":"Hello World"} [WebGet(UriTemplate = "helloObject")] public SimpleMessage SayHelloObject() { return new SimpleMessage("Hello World"); } // uses Json.Net serialization, to return a json string // returns "{\"Message\":\"Hello World\"}" [WebGet(UriTemplate = "helloString")] public string SayHelloString() { SimpleMessage message = new SimpleMessage() { Message = "Hello World" }; string json = JsonConvert.Serialize(message); return json; } // I need a mix of the two. Return an object type, but use the Json.Net serializer. }

    Read the article

  • Unable to call RESTful web services methods

    - by Alessandro
    Hello, I'm trying to dive into the RESTful web services world and have started with the following template: [ServiceContract] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] public class Test { // TODO: Implement the collection resource that will contain the SampleItem instances [WebGet(UriTemplate = ""), OperationContract] public List<SampleItem> GetCollection() { // TODO: Replace the current implementation to return a collection of SampleItem instances return new List<SampleItem>() {new SampleItem() {Id = 1, StringValue = "Hello"}}; } [WebInvoke(UriTemplate = "", Method = "POST"), OperationContract] public SampleItem Create(SampleItem instance) { // TODO: Add the new instance of SampleItem to the collection throw new NotImplementedException(); } [WebGet(UriTemplate = "{id}"), OperationContract] public SampleItem Get(string id) { // TODO: Return the instance of SampleItem with the given id throw new NotImplementedException(); } [WebInvoke(UriTemplate = "{id}", Method = "PUT"), OperationContract] public SampleItem Update(string id, SampleItem instance) { return new SampleItem { Id = 99, StringValue = "Done" }; } [WebInvoke(UriTemplate = "{id}", Method = "DELETE"), OperationContract] public void Delete(string id) { // TODO: Remove the instance of SampleItem with the given id from the collection throw new NotImplementedException(); } } I am able to perform the GET operation but I am unable to perform PUT, POST or DELETE requests. Can anyone explain me how to perform these operations and how to create the correct URLs? Best regards Alessandro

    Read the article

  • WCF contracts - namespaces and SerializationExceptions

    - by qntmfred
    I am using a third party web service that offers the following calls and responses http://api.athirdparty.com/rest/foo?apikey=1234 <response> <foo>this is a foo</foo> </response> and http://api.athirdparty.com/rest/bar?apikey=1234 <response> <bar>this is a bar</bar> </response> This is the contract and supporting types I wrote [ServiceContract] [XmlSerializerFormat] public interface IFooBarService { [OperationContract] [WebGet( BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Xml, UriTemplate = "foo?key={apikey}")] FooResponse GetFoo(string apikey); [OperationContract] [WebGet( BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Xml, UriTemplate = "bar?key={apikey}")] BarResponse GetBar(string apikey); } [XmlRoot("response")] public class FooResponse { [XmlElement("foo")] public string Foo { get; set; } } [XmlRoot("response")] public class BarResponse { [XmlElement("bar")] public string Bar { get; set; } } and then my client looks like this static void Main(string[] args) { using (WebChannelFactory<IFooBarService> cf = new WebChannelFactory<IFooBarService>("thirdparty")) { var channel = cf.CreateChannel(); FooResponse result = channel.GetFoo("1234"); } } When I run this I get the following exception Unable to deserialize XML body with root name 'response' and root namespace '' (for operation 'GetFoo' and contract ('IFooBarService', 'http://tempuri.org/')) using XmlSerializer. Ensure that the type corresponding to the XML is added to the known types collection of the service. If I comment out the GetBar operation from IFooBarService, it works fine. I know I'm missing an important concept here - just don't know quite what to look for. What is the proper way to construct my contract types, so that they can be properly deserialized?

    Read the article

  • Consuming C# Webservice

    - by Debby
    Hi, I have a simple webservice running and I have a console application client consuming the service. I did have issues getting this running and I had been helped by some wonderful people in this community. I have another problem, if i want to call the service from the client in a loop, it doesnt work. It works only for the first time and then it just keeps waiting. Why is this happening and how can I resolve it. The code: namespace WebService { [ServiceContract] public interface IService { [OperationContract(Name="Result")] [WebGet(UriTemplate = "/")] Stream Result(); } public class Service:IService { public Stream Result() { // read a file from the server and return it as stream } } } The client: namespace WebServiceClient { [ServiceContract] public interface IService { [OperationContract(Name="Result")] [WebGet(UriTemplate = "/")] Stream Result(); } } static void Main() { Console.WriteLine("Press enter when the service is available"); Console.ReadLine(); // creating factory HttpChunkingBinding binding = new HttpChunkingBinding(); binding.MaxReceivedMessageSize = 0x7fffffffL; ChannelFactory<WebServiceClient.IService> factory = new ChannelFactory<WebServiceClient.IService> (binding, new EndpointAddress("http://localhost/WebService/Service")); WebServiceClient.IService service = factory.CreateChannel(); for(int i = 0; i < 10; i++) { Stream s = service.Result(); // write this stream to a file and close the stream } //Closing our channel. ((IClientChannel)service).Close(); } Thanks,

    Read the article

  • Consuming WCF Web Service

    - by Debby
    Hi, I have a simple web service running and I have a console application client consuming the service. I did have issues getting this running and I had been helped by some wonderful people in this community. I have another problem: if I want to call the service from the client in a loop, it doesn't work. It works only for the first time and then it just keeps waiting. Why is this happening and how can I resolve it. The code: namespace WebService { [ServiceContract] public interface IService { [OperationContract(Name="Result")] [WebGet(UriTemplate = "/")] Stream Result(); } public class Service:IService { public Stream Result() { // read a file from the server and return it as stream } } } The client: namespace WebServiceClient { [ServiceContract] public interface IService { [OperationContract(Name="Result")] [WebGet(UriTemplate = "/")] Stream Result(); } } static void Main() { Console.WriteLine("Press enter when the service is available"); Console.ReadLine(); // creating factory HttpChunkingBinding binding = new HttpChunkingBinding(); binding.MaxReceivedMessageSize = 0x7fffffffL; ChannelFactory<WebServiceClient.IService> factory = new ChannelFactory<WebServiceClient.IService> (binding, new EndpointAddress("http://localhost/WebService/Service")); WebServiceClient.IService service = factory.CreateChannel(); for(int i = 0; i < 10; i++) { Stream s = service.Result(); // write this stream to a file and close the stream } //Closing our channel. ((IClientChannel)service).Close(); } Thanks,

    Read the article

  • Running SSIS packages from C#

    - by Piotr Rodak
    Most of the developers and DBAs know about two ways of deploying packages: You can deploy them to database server and run them using SQL Server Agent job or you can deploy the packages to file system and run them using dtexec.exe utility. Both approaches have their pros and cons. However I would like to show you that there is a third way (sort of) that is often overlooked, and it can give you capabilities the ‘traditional’ approaches can’t. I have been working for a few years with applications that run packages from host applications that are implemented in .NET. As you know, SSIS provides programming model that you can use to implement more flexible solutions. SSIS applications are usually thought to be batch oriented, with fairly rigid architecture and processing model, with fixed timeframes when the packages are executed to process data. It doesn’t to be the case, you don’t have to limit yourself to batch oriented architecture. I have very good experiences with service oriented architectures processing large amounts of data. These applications are more complex than what I would like to show here, but the principle stays the same: you can execute packages as a service, on ad-hoc basis. You can also implement and schedule various signals, HTTP calls, file drops, time schedules, Tibco messages and other to run the packages. You can implement event handler that will trigger execution of SSIS when a certain event occurs in StreamInsight stream. This post is just a small example of how you can use the API and other features to create a service that can run SSIS packages on demand. I thought it might be a good idea to implement a restful service that would listen to requests and execute appropriate actions. As it turns out, it is trivial in C#. The application is implemented as console application for the ease of debugging and running. In reality, you might want to implement the application as Windows service. To begin, you have to reference namespace System.ServiceModel.Web and then add a few lines of code: Uri baseAddress = new Uri("http://localhost:8011/");               WebServiceHost svcHost = new WebServiceHost(typeof(PackRunner), baseAddress);                           try             {                 svcHost.Open();                   Console.WriteLine("Service is running");                 Console.WriteLine("Press enter to stop the service.");                 Console.ReadLine();                   svcHost.Close();             }             catch (CommunicationException cex)             {                 Console.WriteLine("An exception occurred: {0}", cex.Message);                 svcHost.Abort();             } The interesting lines are 3, 7 and 13. In line 3 you create a WebServiceHost object. In line 7 you start listening on the defined URL and then in line 13 you shut down the service. As you have noticed, the WebServiceHost constructor is accepting type of an object (here: PackRunner) that will be instantiated as singleton and subsequently used to process the requests. This is the class where you put your logic, but to tell WebServiceHost how to use it, the class must implement an interface which declares methods to be used by the host. The interface itself must be ornamented with attribute ServiceContract. [ServiceContract]     public interface IPackRunner     {         [OperationContract]         [WebGet(UriTemplate = "runpack?package={name}")]         string RunPackage1(string name);           [OperationContract]         [WebGet(UriTemplate = "runpackwithparams?package={name}&rows={rows}")]         string RunPackage2(string name, int rows);     } Each method that is going to be used by WebServiceHost has to have attribute OperationContract, as well as WebGet or WebInvoke attribute. The detailed discussion of the available options is outside of scope of this post. I also recommend using more descriptive names to methods . Then, you have to provide the implementation of the interface: public class PackRunner : IPackRunner     {         ... There are two methods defined in this class. I think that since the full code is attached to the post, I will show only the more interesting method, the RunPackage2.   /// <summary> /// Runs package and sets some of its variables. /// </summary> /// <param name="name">Name of the package</param> /// <param name="rows">Number of rows to export</param> /// <returns></returns> public string RunPackage2(string name, int rows) {     try     {         string pkgLocation = ConfigurationManager.AppSettings["PackagePath"];           pkgLocation = Path.Combine(pkgLocation, name.Replace("\"", ""));           Console.WriteLine();         Console.WriteLine("Calling package {0} with parameter {1}.", name, rows);                  Application app = new Application();         Package pkg = app.LoadPackage(pkgLocation, null);           pkg.Variables["User::ExportRows"].Value = rows;         DTSExecResult pkgResults = pkg.Execute();         Console.WriteLine();         Console.WriteLine(pkgResults.ToString());         if (pkgResults == DTSExecResult.Failure)         {             Console.WriteLine();             Console.WriteLine("Errors occured during execution of the package:");             foreach (DtsError er in pkg.Errors)                 Console.WriteLine("{0}: {1}", er.ErrorCode, er.Description);             Console.WriteLine();             return "Errors occured during execution. Contact your support.";         }                  Console.WriteLine();         Console.WriteLine();         return "OK";     }     catch (Exception ex)     {         Console.WriteLine(ex);         return ex.ToString();     } }   The method accepts package name and number of rows to export. The packages are deployed to the file system. The path to the packages is configured in the application configuration file. This way, you can implement multiple services on the same machine, provided you also configure the URL for each instance appropriately. To run a package, you have to reference Microsoft.SqlServer.Dts.Runtime namespace. This namespace is implemented in Microsoft.SQLServer.ManagedDTS.dll which in my case was installed in the folder “C:\Program Files (x86)\Microsoft SQL Server\100\SDK\Assemblies”. Once you have done it, you can create an instance of Microsoft.SqlServer.Dts.Runtime.Application as in line 18 in the above snippet. It may be a good idea to create the Application object in the constructor of the PackRunner class, to avoid necessity of recreating it each time the service is invoked. Then, in line 19 you see that an instance of Microsoft.SqlServer.Dts.Runtime.Package is created. The method LoadPackage in its simplest form just takes package file name as the first parameter. Before you run the package, you can set its variables to certain values. This is a great way of configuring your packages without all the hassle with dtsConfig files. In the above code sample, variable “User:ExportRows” is set to value of the parameter “rows” of the method. Eventually, you execute the package. The method doesn’t throw exceptions, you have to test the result of execution yourself. If the execution wasn’t successful, you can examine collection of errors exposed by the package. These are the familiar errors you often see during development and debugging of the package. I you run the package from the code, you have opportunity to persist them or log them using your favourite logging framework. The package itself is very simple; it connects to my AdventureWorks database and saves number of rows specified in variable “User::ExportRows” to a file. You should know that before you run the package, you can change its connection strings, logging, events and many more. I attach solution with the test service, as well as a project with two test packages. To test the service, you have to run it and wait for the message saying that the host is started. Then, just type (or copy and paste) the below command to your browser. http://localhost:8011/runpackwithparams?package=%22ExportEmployees.dtsx%22&rows=12 When everything works fine, and you modified the package to point to your AdventureWorks database, you should see "OK” wrapped in xml: I stopped the database service to simulate invalid connection string situation. The output of the request is different now: And the service console window shows more information: As you see, implementing service oriented ETL framework is not a very difficult task. You have ability to configure the packages before you run them, you can implement logging that is consistent with the rest of your system. In application I have worked with we also have resource monitoring and execution control. We don’t allow to run more than certain number of packages to run simultaneously. This ensures we don’t strain the server and we use memory and CPUs efficiently. The attached zip file contains two projects. One is the package runner. It has to be executed with administrative privileges as it registers HTTP namespace. The other project contains two simple packages. This is really a cool thing, you should check it out!

    Read the article

  • ASP.NET Frameworks and Raw Throughput Performance

    - by Rick Strahl
    A few days ago I had a curious thought: With all these different technologies that the ASP.NET stack has to offer, what's the most efficient technology overall to return data for a server request? When I started this it was mere curiosity rather than a real practical need or result. Different tools are used for different problems and so performance differences are to be expected. But still I was curious to see how the various technologies performed relative to each just for raw throughput of the request getting to the endpoint and back out to the client with as little processing in the actual endpoint logic as possible (aka Hello World!). I want to clarify that this is merely an informal test for my own curiosity and I'm sharing the results and process here because I thought it was interesting. It's been a long while since I've done any sort of perf testing on ASP.NET, mainly because I've not had extremely heavy load requirements and because overall ASP.NET performs very well even for fairly high loads so that often it's not that critical to test load performance. This post is not meant to make a point  or even come to a conclusion which tech is better, but just to act as a reference to help understand some of the differences in perf and give a starting point to play around with this yourself. I've included the code for this simple project, so you can play with it and maybe add a few additional tests for different things if you like. Source Code on GitHub I looked at this data for these technologies: ASP.NET Web API ASP.NET MVC WebForms ASP.NET WebPages ASMX AJAX Services  (couldn't get AJAX/JSON to run on IIS8 ) WCF Rest Raw ASP.NET HttpHandlers It's quite a mixed bag, of course and the technologies target different types of development. What started out as mere curiosity turned into a bit of a head scratcher as the results were sometimes surprising. What I describe here is more to satisfy my curiosity more than anything and I thought it interesting enough to discuss on the blog :-) First test: Raw Throughput The first thing I did is test raw throughput for the various technologies. This is the least practical test of course since you're unlikely to ever create the equivalent of a 'Hello World' request in a real life application. The idea here is to measure how much time a 'NOP' request takes to return data to the client. So for this request I create the simplest Hello World request that I could come up for each tech. Http Handler The first is the lowest level approach which is an HTTP handler. public class Handler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Write("Hello World. Time is: " + DateTime.Now.ToString()); } public bool IsReusable { get { return true; } } } WebForms Next I added a couple of ASPX pages - one using CodeBehind and one using only a markup page. The CodeBehind page simple does this in CodeBehind without any markup in the ASPX page: public partial class HelloWorld_CodeBehind : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Response.Write("Hello World. Time is: " + DateTime.Now.ToString() ); Response.End(); } } while the Markup page only contains some static output via an expression:<%@ Page Language="C#" AutoEventWireup="false" CodeBehind="HelloWorld_Markup.aspx.cs" Inherits="AspNetFrameworksPerformance.HelloWorld_Markup" %> Hello World. Time is <%= DateTime.Now %> ASP.NET WebPages WebPages is the freestanding Razor implementation of ASP.NET. Here's the simple HelloWorld.cshtml page:Hello World @DateTime.Now WCF REST WCF REST was the token REST implementation for ASP.NET before WebAPI and the inbetween step from ASP.NET AJAX. I'd like to forget that this technology was ever considered for production use, but I'll include it here. Here's an OperationContract class: [ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class WcfService { [OperationContract] [WebGet] public Stream HelloWorld() { var data = Encoding.Unicode.GetBytes("Hello World" + DateTime.Now.ToString()); var ms = new MemoryStream(data); // Add your operation implementation here return ms; } } WCF REST can return arbitrary results by returning a Stream object and a content type. The code above turns the string result into a stream and returns that back to the client. ASP.NET AJAX (ASMX Services) I also wanted to test ASP.NET AJAX services because prior to WebAPI this is probably still the most widely used AJAX technology for the ASP.NET stack today. Unfortunately I was completely unable to get this running on my Windows 8 machine. Visual Studio 2012  removed adding of ASP.NET AJAX services, and when I tried to manually add the service and configure the script handler references it simply did not work - I always got a SOAP response for GET and POST operations. No matter what I tried I always ended up getting XML results even when explicitly adding the ScriptHandler. So, I didn't test this (but the code is there - you might be able to test this on a Windows 7 box). ASP.NET MVC Next up is probably the most popular ASP.NET technology at the moment: MVC. Here's the small controller: public class MvcPerformanceController : Controller { public ActionResult Index() { return View(); } public ActionResult HelloWorldCode() { return new ContentResult() { Content = "Hello World. Time is: " + DateTime.Now.ToString() }; } } ASP.NET WebAPI Next up is WebAPI which looks kind of similar to MVC. Except here I have to use a StringContent result to return the response: public class WebApiPerformanceController : ApiController { [HttpGet] public HttpResponseMessage HelloWorldCode() { return new HttpResponseMessage() { Content = new StringContent("Hello World. Time is: " + DateTime.Now.ToString(), Encoding.UTF8, "text/plain") }; } } Testing Take a minute to think about each of the technologies… and take a guess which you think is most efficient in raw throughput. The fastest should be pretty obvious, but the others - maybe not so much. The testing I did is pretty informal since it was mainly to satisfy my curiosity - here's how I did this: I used Apache Bench (ab.exe) from a full Apache HTTP installation to run and log the test results of hitting the server. ab.exe is a small executable that lets you hit a URL repeatedly and provides counter information about the number of requests, requests per second etc. ab.exe and the batch file are located in the \LoadTests folder of the project. An ab.exe command line  looks like this: ab.exe -n100000 -c20 http://localhost/aspnetperf/api/HelloWorld which hits the specified URL 100,000 times with a load factor of 20 concurrent requests. This results in output like this:   It's a great way to get a quick and dirty performance summary. Run it a few times to make sure there's not a large amount of varience. You might also want to do an IISRESET to clear the Web Server. Just make sure you do a short test run to warm up the server first - otherwise your first run is likely to be skewed downwards. ab.exe also allows you to specify headers and provide POST data and many other things if you want to get a little more fancy. Here all tests are GET requests to keep it simple. I ran each test: 100,000 iterations Load factor of 20 concurrent connections IISReset before starting A short warm up run for API and MVC to make sure startup cost is mitigated Here is the batch file I used for the test: IISRESET REM make sure you add REM C:\Program Files (x86)\Apache Software Foundation\Apache2.2\bin REM to your path so ab.exe can be found REM Warm up ab.exe -n100 -c20 http://localhost/aspnetperf/MvcPerformance/HelloWorldJsonab.exe -n100 -c20 http://localhost/aspnetperf/api/HelloWorldJson ab.exe -n100 -c20 http://localhost/AspNetPerf/WcfService.svc/HelloWorld ab.exe -n100000 -c20 http://localhost/aspnetperf/handler.ashx > handler.txt ab.exe -n100000 -c20 http://localhost/aspnetperf/HelloWorld_CodeBehind.aspx > AspxCodeBehind.txt ab.exe -n100000 -c20 http://localhost/aspnetperf/HelloWorld_Markup.aspx > AspxMarkup.txt ab.exe -n100000 -c20 http://localhost/AspNetPerf/WcfService.svc/HelloWorld > Wcf.txt ab.exe -n100000 -c20 http://localhost/aspnetperf/MvcPerformance/HelloWorldCode > Mvc.txt ab.exe -n100000 -c20 http://localhost/aspnetperf/api/HelloWorld > WebApi.txt I ran each of these tests 3 times and took the average score for Requests/second, with the machine otherwise idle. I did see a bit of variance when running many tests but the values used here are the medians. Part of this has to do with the fact I ran the tests on my local machine - result would probably more consistent running the load test on a separate machine hitting across the network. I ran these tests locally on my laptop which is a Dell XPS with quad core Sandibridge I7-2720QM @ 2.20ghz and a fast SSD drive on Windows 8. CPU load during tests ran to about 70% max across all 4 cores (IOW, it wasn't overloading the machine). Ideally you can try running these tests on a separate machine hitting the local machine. If I remember correctly IIS 7 and 8 on client OSs don't throttle so the performance here should be Results Ok, let's cut straight to the chase. Below are the results from the tests… It's not surprising that the handler was fastest. But it was a bit surprising to me that the next fastest was WebForms and especially Web Forms with markup over a CodeBehind page. WebPages also fared fairly well. MVC and WebAPI are a little slower and the slowest by far is WCF REST (which again I find surprising). As mentioned at the start the raw throughput tests are not overly practical as they don't test scripting performance for the HTML generation engines or serialization performances of the data engines. All it really does is give you an idea of the raw throughput for the technology from time of request to reaching the endpoint and returning minimal text data back to the client which indicates full round trip performance. But it's still interesting to see that Web Forms performs better in throughput than either MVC, WebAPI or WebPages. It'd be interesting to try this with a few pages that actually have some parsing logic on it, but that's beyond the scope of this throughput test. But what's also amazing about this test is the sheer amount of traffic that a laptop computer is handling. Even the slowest tech managed 5700 requests a second, which is one hell of a lot of requests if you extrapolate that out over a 24 hour period. Remember these are not static pages, but dynamic requests that are being served. Another test - JSON Data Service Results The second test I used a JSON result from several of the technologies. I didn't bother running WebForms and WebPages through this test since that doesn't make a ton of sense to return data from the them (OTOH, returning text from the APIs didn't make a ton of sense either :-) In these tests I have a small Person class that gets serialized and then returned to the client. The Person class looks like this: public class Person { public Person() { Id = 10; Name = "Rick"; Entered = DateTime.Now; } public int Id { get; set; } public string Name { get; set; } public DateTime Entered { get; set; } } Here are the updated handler classes that use Person: Handler public class Handler : IHttpHandler { public void ProcessRequest(HttpContext context) { var action = context.Request.QueryString["action"]; if (action == "json") JsonRequest(context); else TextRequest(context); } public void TextRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Write("Hello World. Time is: " + DateTime.Now.ToString()); } public void JsonRequest(HttpContext context) { var json = JsonConvert.SerializeObject(new Person(), Formatting.None); context.Response.ContentType = "application/json"; context.Response.Write(json); } public bool IsReusable { get { return true; } } } This code adds a little logic to check for a action query string and route the request to an optional JSON result method. To generate JSON, I'm using the same JSON.NET serializer (JsonConvert.SerializeObject) used in Web API to create the JSON response. WCF REST   [ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class WcfService { [OperationContract] [WebGet] public Stream HelloWorld() { var data = Encoding.Unicode.GetBytes("Hello World " + DateTime.Now.ToString()); var ms = new MemoryStream(data); // Add your operation implementation here return ms; } [OperationContract] [WebGet(ResponseFormat=WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.WrappedRequest)] public Person HelloWorldJson() { // Add your operation implementation here return new Person(); } } For WCF REST all I have to do is add a method with the Person result type.   ASP.NET MVC public class MvcPerformanceController : Controller { // // GET: /MvcPerformance/ public ActionResult Index() { return View(); } public ActionResult HelloWorldCode() { return new ContentResult() { Content = "Hello World. Time is: " + DateTime.Now.ToString() }; } public JsonResult HelloWorldJson() { return Json(new Person(), JsonRequestBehavior.AllowGet); } } For MVC all I have to do for a JSON response is return a JSON result. ASP.NET internally uses JavaScriptSerializer. ASP.NET WebAPI public class WebApiPerformanceController : ApiController { [HttpGet] public HttpResponseMessage HelloWorldCode() { return new HttpResponseMessage() { Content = new StringContent("Hello World. Time is: " + DateTime.Now.ToString(), Encoding.UTF8, "text/plain") }; } [HttpGet] public Person HelloWorldJson() { return new Person(); } [HttpGet] public HttpResponseMessage HelloWorldJson2() { var response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new ObjectContent<Person>(new Person(), GlobalConfiguration.Configuration.Formatters.JsonFormatter); return response; } } Testing and Results To run these data requests I used the following ab.exe commands:REM JSON RESPONSES ab.exe -n100000 -c20 http://localhost/aspnetperf/Handler.ashx?action=json > HandlerJson.txt ab.exe -n100000 -c20 http://localhost/aspnetperf/MvcPerformance/HelloWorldJson > MvcJson.txt ab.exe -n100000 -c20 http://localhost/aspnetperf/api/HelloWorldJson > WebApiJson.txt ab.exe -n100000 -c20 http://localhost/AspNetPerf/WcfService.svc/HelloWorldJson > WcfJson.txt The results from this test run are a bit interesting in that the WebAPI test improved performance significantly over returning plain string content. Here are the results:   The performance for each technology drops a little bit except for WebAPI which is up quite a bit! From this test it appears that WebAPI is actually significantly better performing returning a JSON response, rather than a plain string response. Snag with Apache Benchmark and 'Length Failures' I ran into a little snag with Apache Benchmark, which was reporting failures for my Web API requests when serializing. As the graph shows performance improved significantly from with JSON results from 5580 to 6530 or so which is a 15% improvement (while all others slowed down by 3-8%). However, I was skeptical at first because the WebAPI test reports showed a bunch of errors on about 10% of the requests. Check out this report: Notice the Failed Request count. What the hey? Is WebAPI failing on roughly 10% of requests when sending JSON? Turns out: No it's not! But it took some sleuthing to figure out why it reports these failures. At first I thought that Web API was failing, and so to make sure I re-ran the test with Fiddler attached and runiisning the ab.exe test by using the -X switch: ab.exe -n100 -c10 -X localhost:8888 http://localhost/aspnetperf/api/HelloWorldJson which showed that indeed all requests where returning proper HTTP 200 results with full content. However ab.exe was reporting the errors. After some closer inspection it turned out that the dates varying in size altered the response length in dynamic output. For example: these two results: {"Id":10,"Name":"Rick","Entered":"2012-09-04T10:57:24.841926-10:00"} {"Id":10,"Name":"Rick","Entered":"2012-09-04T10:57:24.8519262-10:00"} are different in length for the number which results in 68 and 69 bytes respectively. The same URL produces different result lengths which is what ab.exe reports. I didn't notice at first bit the same is happening when running the ASHX handler with JSON.NET result since it uses the same serializer that varies the milliseconds. Moral: You can typically ignore Length failures in Apache Benchmark and when in doubt check the actual output with Fiddler. Note that the other failure values are accurate though. Another interesting Side Note: Perf drops over Time As I was running these tests repeatedly I was finding that performance steadily dropped from a startup peak to a 10-15% lower stable level. IOW, with Web API I'd start out with around 6500 req/sec and in subsequent runs it keeps dropping until it would stabalize somewhere around 5900 req/sec occasionally jumping lower. For these tests this is why I did the IIS RESET and warm up for individual tests. This is a little puzzling. Looking at Process Monitor while the test are running memory very quickly levels out as do handles and threads, on the first test run. Subsequent runs everything stays stable, but the performance starts going downwards. This applies to all the technologies - Handlers, Web Forms, MVC, Web API - curious to see if others test this and see similar results. Doing an IISRESET then resets everything and performance starts off at peak again… Summary As I stated at the outset, these were informal to satiate my curiosity not to prove that any technology is better or even faster than another. While there clearly are differences in performance the differences (other than WCF REST which was by far the slowest and the raw handler which was by far the highest) are relatively minor, so there is no need to feel that any one technology is a runaway standout in raw performance. Choosing a technology is about more than pure performance but also about the adequateness for the job and the easy of implementation. The strengths of each technology will make for any minor performance difference we see in these tests. However, to me it's important to get an occasional reality check and compare where new technologies are heading. Often times old stuff that's been optimized and designed for a time of less horse power can utterly blow the doors off newer tech and simple checks like this let you compare. Luckily we're seeing that much of the new stuff performs well even in V1.0 which is great. To me it was very interesting to see Web API perform relatively badly with plain string content, which originally led me to think that Web API might not be properly optimized just yet. For those that caught my Tweets late last week regarding WebAPI's slow responses was with String content which is in fact considerably slower. Luckily where it counts with serialized JSON and XML WebAPI actually performs better. But I do wonder what would make generic string content slower than serialized code? This stresses another point: Don't take a single test as the final gospel and don't extrapolate out from a single set of tests. Certainly Twitter can make you feel like a fool when you post something immediate that hasn't been fleshed out a little more <blush>. Egg on my face. As a result I ended up screwing around with this for a few hours today to compare different scenarios. Well worth the time… I hope you found this useful, if not for the results, maybe for the process of quickly testing a few requests for performance and charting out a comparison. Now onwards with more serious stuff… Resources Source Code on GitHub Apache HTTP Server Project (ab.exe is part of the binary distribution)© Rick Strahl, West Wind Technologies, 2005-2012Posted in ASP.NET  Web Api   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Allowing Access to HttpContext in WCF REST Services

    - by Rick Strahl
    If you’re building WCF REST Services you may find that WCF’s OperationContext, which provides some amount of access to Http headers on inbound and outbound messages, is pretty limited in that it doesn’t provide access to everything and sometimes in a not so convenient manner. For example accessing query string parameters explicitly is pretty painful: [OperationContract] [WebGet] public string HelloWorld() { var properties = OperationContext.Current.IncomingMessageProperties; var property = properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty; string queryString = property.QueryString; var name = StringUtils.GetUrlEncodedKey(queryString,"Name"); return "Hello World " + name; } And that doesn’t account for the logic in GetUrlEncodedKey to retrieve the querystring value. It’s a heck of a lot easier to just do this: [OperationContract] [WebGet] public string HelloWorld() { var name = HttpContext.Current.Request.QueryString["Name"] ?? string.Empty; return "Hello World " + name; } Ok, so if you follow the REST guidelines for WCF REST you shouldn’t have to rely on reading query string parameters manually but instead rely on routing logic, but you know what: WCF REST is a PITA anyway and anything to make things a little easier is welcome. To enable the second scenario there are a couple of steps that you have to take on your service implementation and the configuration file. Add aspNetCompatibiltyEnabled in web.config Fist you need to configure the hosting environment to support ASP.NET when running WCF Service requests. This ensures that the ASP.NET pipeline is fired up and configured for every incoming request. <system.serviceModel>     <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> </system.serviceModel> Markup your Service Implementation with AspNetCompatibilityRequirements Attribute Next you have to mark up the Service Implementation – not the contract if you’re using a separate interface!!! – with the AspNetCompatibilityRequirements attribute: [ServiceContract(Namespace = "RateTestService")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class RestRateTestProxyService Typically you’ll want to use Allowed as the preferred option. The other options are NotAllowed and Required. Allowed will let the service run if the web.config attribute is not set. Required has to have it set. All these settings determine whether an ASP.NET host AppDomain is used for requests. Once Allowed or Required has been set on the implemented class you can make use of the ASP.NET HttpContext object. When I allow for ASP.NET compatibility in my WCF services I typically add a property that exposes the Context and Request objects a little more conveniently: public HttpContext Context { get { return HttpContext.Current; } } public HttpRequest Request { get { return HttpContext.Current.Request; } } While you can also access the Response object and write raw data to it and manipulate headers THAT is probably not such a good idea as both your code and WCF will end up writing into the output stream. However it might be useful in some situations where you need to take over output generation completely and return something completely custom. Remember though that WCF REST DOES actually support that as well with Stream responses that essentially allow you to return any kind of data to the client so using Response should really never be necessary. Should you or shouldn’t you? WCF purists will tell you never to muck with the platform specific features or the underlying protocol, and if you can avoid it you definitely should avoid it. Querystring management in particular can be handled largely with Url Routing, but there are exceptions of course. Try to use what WCF natively provides – if possible as it makes the code more portable. For example, if you do enable ASP.NET Compatibility you won’t be able to self host a WCF REST service. At the same time realize that especially in WCF REST there are number of big holes or access to some features are a royal pain and so it’s not unreasonable to access the HttpContext directly especially if it’s only for read-only access. Since everything in REST works of URLS and the HTTP protocol more control and easier access to HTTP features is a key requirement to building flexible services. It looks like vNext of the WCF REST stuff will feature many improvements along these lines with much deeper native HTTP support that is often so useful in REST applications along with much more extensibility that allows for customization of the inputs and outputs as data goes through the request pipeline. I’m looking forward to this stuff as WCF REST as it exists today still is a royal pain (in fact I’m struggling with a mysterious version conflict/crashing error on my machine that I have not been able to resolve – grrrr…).© Rick Strahl, West Wind Technologies, 2005-2011Posted in ASP.NET  AJAX  WCF  

    Read the article

  • Config for WCF with multiple endpoints

    - by vdh_ant
    Hi guys I'm new to WCF and am trying to get some ideas I have off the ground. Basically I have a web WCF Application project with the following in its web.config: <system.serviceModel> <services> <service name="WcfService1.ServiceContract.IDirectorySearchService" behaviorConfiguration="defaultServiceBehavior"> <endpoint name="restxml" address="xml" binding="webHttpBinding" contract="WcfService1.ServiceContract.IDirectorySearchServiceXml" behaviorConfiguration="xmlRestBehavior"/> <endpoint name="restjson" address="json" binding="webHttpBinding" contract="WcfService1.ServiceContract.IDirectorySearchServiceJson" behaviorConfiguration="jsonRestBehavior"/> <endpoint name="soap" address="soap" binding="basicHttpBinding" contract="WcfService1.ServiceContract.IDirectorySearchService"/> <endpoint name="mex" address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="defaultServiceBehavior"> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="xmlRestBehavior"> <webHttp/> </behavior> <behavior name="jsonRestBehavior"> <enableWebScript/> </behavior> </endpointBehaviors> </behaviors> </system.serviceModel> My interfaces look like this: [ServiceContract] public interface IDirectorySearchServiceXml { [OperationContract] [WebGet(UriTemplate = "Search/")] SearchResults Search(); } [ServiceContract] public interface IDirectorySearchServiceJson { [OperationContract] [WebGet(UriTemplate = "Search/")] SearchResults Search(); } [ServiceContract] public interface IDirectorySearchService { [OperationContract] SearchResults Search(int? sportId, int? instituteId, DateTime? startDate, DateTime? endDate); } Now the part I am having a little trouble with is what else I need to get this up and running... Like given this what .svc files do I need and do I have the config right... Also what addresses do I need to use to get this running either through the browser or through the WCF test client. Note I am currently using 3.5. Cheers Anthony

    Read the article

  • WCF Ajax service - How can I pass an Array or JSON to the service? What should the method parameter

    - by Kettenbach
    I have a very simple WCF service I would like to pass it an array or json? [OperationContract, WebGet(ResponseFormat = WebMessageFormat.Json)] public string GetPreDisplay(string inputData) { //DoSomething with inputData return "Sweet!"; } My javascript... var data = [paymentControls['claimNum'], paymentControls['claimSeq']]; $lps.GetPreDisplay(data, onComplete); Obviously string is the wrong type. Can anyone point me in the right direction? Thanks, ~ck

    Read the article

1 2 3  | Next Page >