Search Results

Search found 250 results on 10 pages for 'operationcontract'.

Page 7/10 | < Previous Page | 3 4 5 6 7 8 9 10  | Next Page >

  • Acr.ExtDirect &ndash; Part 1 &ndash; Method Resolvers

    - by Allan Ritchie
    One of the most important things of any open source libraries in my opinion is to be as open as possible while avoiding having your library become invasive to your code/business model design.  I personally could never stand marking my business and/or data access code with attributes everywhere.  XML also isn’t really a fav with too many people these days since it comes with a startup performance hit and requires runtime compiling.  I find that there is a whole ton of communication libraries out there currently requiring this (ie. WCF, RIA, etc).  Even though Acr.ExtDirect comes with its own set of attributes, you can piggy-back the [ServiceContract] & [OperationContract] attributes from WCF if you choose.  It goes beyond that though, there are 2 others “out-of-the-box” implementations – Convention based & XML Configuration.    Convention – I don’t actually recommend using this one since it opens up all of your public instance methods to remote execution calls. XML Configuration – This isn’t so bad but requires you enter all of your methods and there operation types into the Castle XML configuration & as I said earlier, XML isn’t the fav these days.   So what are your options if you don’t like attributes, convention, or XML Configuration?  Well, Acr.ExtDirect has its own extension base to give the API a list of methods and components to make available for remote execution.  1: public interface IDirectMethodResolver { 2:   3: bool IsServiceType(ComponentModel model, Type type); 4: string GetNamespace(ComponentModel model); 5: string[] GetDirectMethodNames(ComponentModel model); 6: DirectMethodType GetMethodType(ComponentModel model, MethodInfo method); 7: }   Now to implement our own method resolver:   1: public class TestResolver : IDirectMethodResolver { 2:   3: #region IDirectMethodResolver Members 4:   5: /// <summary> 6: /// Determine if you are calling a service 7: /// </summary> 8: /// <param name="model"></param> 9: /// <param name="type"></param> 10: /// <returns></returns> 11: public bool IsServiceType(ComponentModel model, Type type) { 12: return (type.Namespace == "MyBLL.Data"); 13: } 14:   15: /// <summary> 16: /// Return the calling name for the client side 17: /// </summary> 18: /// <param name="model"></param> 19: /// <returns></returns> 20: public string GetNamespace(ComponentModel model) { 21: return model.Name; 22: } 23:   24: public string[] GetDirectMethodNames(ComponentModel model) { 25: switch (model.Name) { 26: case "Products" : 27: return new [] { 28: "GetProducts", 29: "LoadProduct", 30: "Save", 31: "Update" 32: }; 33:   34: case "Categories" : 35: return new [] { 36: "GetProducts" 37: }; 38:   39: default : 40: throw new ArgumentException("Invalid type"); 41: } 42: } 43:   44: public DirectMethodType GetMethodType(ComponentModel model, MethodInfo method) { 45: if (method.Name.StartsWith("Save") || method.Name.StartsWith("Update")) 46: return DirectMethodType.FormSubmit; 47: 48: else if (method.Name.StartsWith("Load")) 49: return DirectMethodType.FormLoad; 50:   51: else 52: return DirectMethodType.Direct; 53: } 54:   55: #endregion 56: }   And there you have it, your own custom method resolver.  Pretty easy and pretty open ended!

    Read the article

  • WCF Restful services getting error 400 (bad request) when post xml data

    - by Wayne Lo
    I am trying to self host a WCF services and calling the services via javascript. It works when I pass the request data via Json but not xml (400 bad request). Please help. Contract: public interface iSelfHostServices { [OperationContract] [WebInvoke(Method = "POST", UriTemplate = INFOMATO.RestTemplate.hello_post2,RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)] Stream hello_post2(string helloString); } Server side code: public Stream hello_post2(string helloString) { if (helloString == null) { WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.BadRequest; return null; } WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK; return new MemoryStream(Encoding.UTF8.GetBytes(helloString)); } JavaScript: function testSelfHost_WCFService_post_Parameter() { var xmlString = "<helloString>'hello via Post'</helloString>"; Ajax_sendData("hello/post2", xmlString); } function Ajax_sendData(url, data) { var request = false; request = getHTTPObject(); if (request) { request.onreadystatechange = function() { parseResponse(request); }; request.open("post", url, true); request.setRequestHeader("Content-Type", "text/xml; charset=utf-8"); charset=utf-8"); request.send(data); return true; } } function getHTTPObject() { var xhr = false; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) {...} }

    Read the article

  • Send large JSON data to WCF Rest Service

    - by Christo Fur
    Hi I have a client web page that is sending a large json object to a proxy service on the same domain as the web page. The proxy (an ashx handler) then forwards the request to a WCF Rest Service. Using a WebClient object (standard .net object for making a http request) The JSON successfully arrives at the proxy via a jQuery POST on the client webpage. However, when the proxy forwards this to the WCF service I get a Bad Request - Error 400 This doesn't happen when the size of the json data is small The WCF service contract looks like this [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] [OperationContract] CarConfiguration CreateConfiguration(CarConfiguration configuration); And the DataContract like this [DataContract(Namespace = "")] public class CarConfiguration { [DataMember(Order = 1)] public int CarConfigurationId { get; set; } [DataMember(Order = 2)] public int UserId { get; set; } [DataMember(Order = 3)] public string Model { get; set; } [DataMember(Order = 4)] public string Colour { get; set; } [DataMember(Order = 5)] public string Trim { get; set; } [DataMember(Order = 6)] public string ThumbnailByteData { get; set; } [DataMember(Order = 6)] public string Wheel { get; set; } [DataMember(Order = 7)] public DateTime Date { get; set; } [DataMember(Order = 8)] public List<string> Accessories { get; set; } [DataMember(Order = 9)] public string Vehicle { get; set; } [DataMember(Order = 10)] public Decimal Price { get; set; } } When the ThumbnailByteData field is small, all is OK. When it is large I get the 400 error What are my options here? I've tried increasing the MaxBytesRecived config setting but that is not enough Any ideas?

    Read the article

  • Calling WCF service with parameter using jQuery

    - by Remi Despres-Smyth
    I'm trying to call a WCF web service hosted by IIS using jQuery. I can call it fine without any parameters, and I can also call it fine with a GET request that includes my parameter, but as soon as I try to send in the request via POST, the call is failing. The web service is currently nothing but: [OperationContract, WebInvoke] public ValidationResultSummary TestValidateOn( object day) { return null; } I've set the parameter to object, to make sure the issue isn't something with type coercion. With a breakpoint in the web service, I know the call without parameters as well as the GET call with param succeeds; in the latter the expected value is sent up. Calling code looks like: $.ajax({ // type: "GET", // url: "../Shared/Services/DomainServices.svc/TestValidateOn?day='12/Jan/2010'", type: "POST", url: "../Shared/Services/DomainServices.svc/TestValidateOn", // data: "{ }", --This works if object type param, calls with null data: "{'day': " + selectedDate + "}", // This fails miserably // data: "{'day': '" + selectedDate + "'}", --This also fails miserably contentType: "application/json; charset=utf-8", dataType: "json", success: function(data) { displayResults(data.d); }, error: function(xmlHttpReq, status, errThrown) { displayError(xmlHttpReq, status, errThrown); } }); The POST call never reaches my breakpoint, and on the client, error 500 - "Internal Server Error" - is returned. Any help would be appreciated.

    Read the article

  • WCF - The maximum nametable character count quota (16384) has been exceeded while reading XML data.

    - by Jankhana
    I'm having a WCF Service that uses wsHttpBinding. The server configuration is as follows : <bindings> <wsHttpBinding> <binding name="wsHttpBinding" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"> <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> <security mode="None"> <transport clientCredentialType="Windows" proxyCredentialType="None" realm="" /> <message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true" /> </security> </binding> </wsHttpBinding> </bindings> At the client side I'm including the Service reference of the WCF-Service. It works great if I have limited functions say 90 Operation Contract in my IService but if add one more OperationContract than I'm unable to Update the Service reference nor i'm able to add that service reference. In this article it's mentioned that by changing those config files(i.e devenv.exe.config, WcfTestClient.exe.config and SvcUtil.exe.config) it will work but even including those bindings in those config files still that error pops up saying There was an error downloading 'http://10.0.3.112/MyService/Service1.svc/mex'. The request failed with HTTP status 400: Bad Request. Metadata contains a reference that cannot be resolved: 'http://10.0.3.112/MyService/Service1.svc/mex'. There is an error in XML document (1, 89549). The maximum nametable character count quota (16384) has been exceeded while reading XML data. The nametable is a data structure used to store strings encountered during XML processing - long XML documents with non-repeating element names, attribute names and attribute values may trigger this quota. This quota may be increased by changing the MaxNameTableCharCount property on the XmlDictionaryReaderQuotas object used when creating the XML reader. Line 1, position 89549. If the service is defined in the current solution, try building the solution and adding the service reference again. Any idea how to solve this????

    Read the article

  • ContractFilter mismatch at the EndpointDispatcher

    - by Matt
    I've created a simple WCF service but when I use Visual Studio to add a service reference, this error comes up. The message with Action '' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver. Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None). Here is my Interface [ServiceContract] public interface IService { [OperationContract] DateTime GetTime(); } And my implementation [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class TestService : IService { public DateTime GetTime() { return DateTime.Now; } } Finally here is my web.config <system.serviceModel> <client/> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> <services> <service name="Test.TestService" > <endpoint address="" contract="Test.IService" binding="basicHttpBinding" > </endpoint> </service> </services> </system.serviceModel>

    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

  • Understanding ServiceKnownType in WCF

    - by SLC
    I am having a little trouble understanding ServiceKnownType in WCF. Taken from this blog, the following code does not work: [DataContract(Namespace = “http://mycompany.com/”)] public class Shape{…} [DataContract(Namespace = “http://mycompany.com/”)] public class Circle : Shape {…} [ServiceContract] public interface IMyServer { [OperationContract] bool AddShape(Shape shape); } . IMyServer client = new ChannelFactory<IMyServer>(binding, endPoint).CreateChannel(); client.AddShape(new Circle()); The reason it doesn't work is because you are trying to add a circle, but the servicecontract only allows a Shape. You are supposed to do something with knowntypes, but I am a bit confused about how that works. Since that code is in the service, why doesn't it know automatically that a Circle is derived from Shape? Additionally, what does ServiceKnownType actually do? When ServiceKnownType is put below the DataContract, apparently that makes it work. I am guessing it says hey, this particular object type called Shape can also be a Circle. I am having trouble understanding why it would do it this way around, because if you add a new type like Square you are going to have to add that too, wouldn't it make sense if it cannot infer it, to put the KnownType onto the Square rather than the Shape? So the Square says hey, I am a Shape, and you don't have to fiddle with the Shape class?

    Read the article

  • WCF Web Service Gives 404 error in Azure

    - by landyman
    I'm new to using WCF and Azure, but I have a WCF Web Service that works correctly when debugging in Visual Studio. I set the startup project to Azure, and I get 404 errors for any URL I try related to the service. Here is what I think is relavant code: From IWebService.cs [OperationContract] [WebGet(UriTemplate = "GetData/Xml?value={value}", ResponseFormat=WebMessageFormat.Xml)] string GetDataXml(string value); and from Web.config: <system.serviceModel> <services> <service name="WebService" behaviorConfiguration="WebServiceBehavior"> <!-- Service Endpoints --> <endpoint address="" binding="webHttpBinding" contract="IWebService" behaviorConfiguration="WebEndpointBehavior"></endpoint> <endpoint address="ws" binding="wsHttpBinding" contract="IWebService"/> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="WebServiceBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="WebEndpointBehavior"> <webHttp/> </behavior> </endpointBehaviors> </behaviors> </system.serviceModel> I have tried changing the binding to 'basicHttpBinding', but that had no luck. Thanks in advance for any help!

    Read the article

  • WCF deadlock when using callback channel

    - by mafutrct
    This is probably a simple mistake, but I could not figure out what was wrong. I basically got a method like this: [ServiceBehavior ( ConcurrencyMode = ConcurrencyMode.Reentrant, InstanceContextMode = InstanceContextMode.PerSession, IncludeExceptionDetailInFaults = true) ] public class Impl : SomeContract { public string Foo() { _CallbackChannel.Blah(); return ""; } } Its interface is decorated: [ServiceContract ( Namespace = "http://MyServiceInterface", SessionMode = SessionMode.Required, CallbackContract = typeof (WcfCallbackContract)) ] public interface SomeContract { [OperationContract] string Foo (); } The service is hosted like this: ServiceHost host = new ServiceHost (typeof (Impl)); var binding = new NetTcpBinding (); var address = new Uri ("net.tcp://localhost:8000/"); host.AddServiceEndpoint ( typeof (SomeContract), binding, address); host.Open (); The client implements the callback interface and calls Foo. Foo runs, calls the callback method and returns. However, the client is still struck in the call to Foo and never returns. The client callback method is never run. I guess I made a design mistake somewhere. If needed, I can post more code. Any help is appreciated.

    Read the article

  • WCF Service : WSHttpBinding

    - by jitm
    Hello, I've created the test self-hosted wcf application and tried to add support https. Code of server application is: using System; using System.Security.Cryptography.X509Certificates; using System.ServiceModel; using System.ServiceModel.Description; using System.ServiceModel.Security; namespace SelfHost { class Program { static void Main(string[] args) { string addressHttp = String.Format("http://{0}:8002/hello", System.Net.Dns.GetHostEntry("").HostName); Uri baseAddress = new Uri(addressHttp); WSHttpBinding b = new WSHttpBinding(); b.Security.Mode = SecurityMode.Transport; b.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate; Uri a = new Uri(addressHttp); Uri[] baseAddresses = new Uri[] { a }; ServiceHost sh = new ServiceHost(typeof(HelloWorldService), baseAddresses); Type c = typeof(IHelloWorldService); sh.AddServiceEndpoint(c, b, "hello"); sh.Credentials.ServiceCertificate.SetCertificate( StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName,"myCert"); sh.Credentials.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerOrChainTrust; try { sh.Open(); string address = sh.Description.Endpoints[0].ListenUri.AbsoluteUri; Console.WriteLine("Listening @ {0}", address); Console.WriteLine("Press enter to close the service"); Console.ReadLine(); sh.Close(); } catch (CommunicationException ce) { Console.WriteLine("A commmunication error occurred: {0}", ce.Message); Console.WriteLine(); } catch (System.Exception exc) { Console.WriteLine("An unforseen error occurred: {0}", exc.Message); Console.ReadLine(); } } } [ServiceContract] public interface IHelloWorldService { [OperationContract] string SayHello(string name); } public class HelloWorldService : IHelloWorldService { public string SayHello(string name) { return string.Format("Hello, {0}", name); } } } What name(address) should I out into line sh.AddServiceEndpoint(c, b, "hello"); because "hello" is incorrect ? Thanks.

    Read the article

  • problem with addressfilter in WCF

    - by Zé Carlos
    I've build my own WCF channel with all necessary stuff (like encoders, bindings, etc) to use it with ServiceHost. I just want to build the "channel stack" making no custumizations at "Service Model". To acomplish this, my encoder returns perfect ServiceModel.Messages with a XML infoset just like other channel does. Lets assume the following service implementation: [ServiceContract(Namespace = "http://MyNS")] public interface IService1 { [OperationContract(IsOneWay = true)] void dummy(); } public class Service1 : IService1 { public void dummy() { Console.WriteLine("In Service1:dummy()"); } } I used this service through other bindings and traced the following ServiceModel.Message contents (SOAP format): <s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing"> <s:Header> <a:Action s:mustUnderstand="1">http://MyNS/IService1/dummy</a:Action> <a:To s:mustUnderstand="1">amqp://localhost</a:To> </s:Header> <s:Body> <dummy xmlns="http://MyNS"></dummy> </s:Body> </s:Envelope> Then (just to debug) i changed my encoder to allways return this message. When i use my custom channel the WCF's runtime replay with an faul message telling: "The message with To '' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher. Check that the sender and receiver's EndpointAddresses agree." I read that the default EndPointDispatcher.AddressFilter simply looks to the "TO" header and delivery the message to corresponding service. This is happening with other bindings, why not happens with my custom channel too? Is there any way to i check what default AddressFilter is doing? Thanks

    Read the article

  • Problem with WCF Streaming

    - by H4mm3rHead
    Hi, I was looking at this thread: http://stackoverflow.com/questions/1935040/how-to-handle-large-file-uploads-via-wcf I need to have a web service hosted at my provider where i need to upload and download files to. We are talking videos from 1Mb to 100Mb hence the streaming approach. I cant get it to work, i declared an Interface: [ServiceContract] public interface IFileTransferService { [OperationContract] void UploadFile(Stream stream); } and all is fine, i implement it like this: public string FileName = "test"; public void UploadFile(Stream stream) { try { FileStream outStream = File.Open(FileName, FileMode.Create, FileAccess.Write); const int bufferLength = 4096; byte[] buffer = new byte[bufferLength]; int count = 0; while((count = stream.Read(buffer, 0, bufferLength)) > 0) { //progress outStream.Write(buffer, 0, count); } outStream.Close(); stream.Close(); //saved } catch(Exception ex) { throw new Exception("error: "+ex.Message); } } Still no problem, its published to my webserver out on the interweb. So far so good. Now i make a reference to it and will pass it a FileStream, but the argument is now a byte[] - why is that and how do i get it the proper way for streaming? Edit My binding look like this: <bindings> <basicHttpBinding> <binding name="StreamingFileTransferServicesBinding" transferMode="StreamedRequest" maxBufferSize="65536" maxReceivedMessageSize="204003200" /> </basicHttpBinding> </bindings> I can consume it without problems, and get no errors - other than my input parameter has changed from a stream to a byte[]

    Read the article

  • Complex data types in WCF?

    - by Hojou
    I've run into a problem trying to return an object that holds a collection of childobjects that again can hold a collection of grandchild objects. I get an error, 'connection forcibly closed by host'. Is there any way to make this work? I currently have a structure resembling this: pseudo code: Person: IEnumerable<Order> Order: IEnumberable<OrderLine> All three objects have the DataContract attribute and all public properties i want exposed (including the IEnumerable's) have the DataMember attribute. I have multiple OperationContract's on my service and all the methods returning a single object OR an IEnumerable of an object works perfectly. It's only when i try to nest IEnumerable that it turns bad. Also in my client service reference i picked the generic list as my collection type. I just want to emphasize, only one of my operations/methods fail with this error - the rest of them work perfectly. EDIT (more detailed error description): [SocketException (0x2746): An existing connection was forcibly closed by the remote host] [IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.] [WebException: The underlying connection was closed: An unexpected error occurred on a receive.] [CommunicationException: An error occurred while receiving the HTTP response to http://myservice.mydomain.dk/MyService.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.] I tried looking for logs but i can't find any... also i'm using a WSHttpBinding and an http endpoint.

    Read the article

  • Creating a WCF ServiceHost object takes three to four minutes on some PCs

    - by Steve
    Hello, I have created a WCF service which does not use the app.config to configure itself. However, it takes three to four minutes on some PCs to construct the ServiceHost object. Thinking there was something wrong with my service, I constructed a simple Hello, World service and tried it with that. I have the same issue. According to the profiler, all this time is spent reading in configuration for the service. So I have two questions really. Is it possible to disable reading config from the XML? More importantly, does anyone have any idea why this might be taking such an inordinate amount of time? Here is the sample service: [ServiceContract] public interface IMyService { [OperationContract] string GetString(); } [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class MyService : IMyService { public string GetString() { return "Hello, world!"; } } class Program { static void Main(string[] args) { Uri epAddress = new Uri("http://localhost:8731/Test"); Uri[] uris = new Uri[] { epAddress }; MyService srv = new MyService(); ServiceHost host = new ServiceHost(srv, uris); // this line takes 3-4 minutes host.AddServiceEndpoint(typeof(IMyService), new WSHttpBinding(), "Test"); ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; host.Description.Behaviors.Add(smb); host.Open(); return; } } I need for design reasons to create the service and pass it in as an object, rather than passing it in as a type. If there's any more information that can be of use, please let me know. Many thanks.

    Read the article

  • WCF MessageHeaders in OperationContext.Current

    - by Nate Bross
    If I use code like this [just below] to add Message Headers to my OperationContext, will all future out-going messages contain that data on any new ClientProxy defined from the same "run" of my application? The objective, is to pass a parameter or two to each OpeartionContract w/out messing with the signature of the OperationContract, since the parameters being passed will be consistant for all requests for a given run of my client application. public void DoSomeStuff() { var proxy = new MyServiceClient(); Guid myToken = Guid.NewGuid(); MessageHeader<Guid> mhg = new MessageHeader<Guid>(myToken); MessageHeader untyped = mhg.GetUntypedHeader("token", "ns"); OperationContext.Current.OutgoingMessageHeaders.Add(untyped); proxy.DoOperation(...); } public void DoSomeOTHERStuff() { var proxy = new MyServiceClient(); Guid myToken = Guid.NewGuid(); MessageHeader<Guid> mhg = new MessageHeader<Guid>(myToken); MessageHeader untyped = mhg.GetUntypedHeader("token", "ns"); OperationContext.Current.OutgoingMessageHeaders.Add(untyped); proxy.DoOtherOperation(...); } In other words, is it safe to refactor the above code like this? bool isSetup = false; public void SetupMessageHeader() { if(isSetup) { return; } Guid myToken = Guid.NewGuid(); MessageHeader<Guid> mhg = new MessageHeader<Guid>(myToken); MessageHeader untyped = mhg.GetUntypedHeader("token", "ns"); OperationContext.Current.OutgoingMessageHeaders.Add(untyped); isSetup = true; } public void DoSomeStuff() { var proxy = new MyServiceClient(); SetupMessageHeader(); proxy.DoOperation(...); } public void DoSomeOTHERStuff() { var proxy = new MyServiceClient(); SetupMessageHeader(); proxy.DoOtherOperation(...); } Since I don't really understand what's happening there, I don't want to cargo cult it and just change it and let it fly if it works, I'd like to hear your thoughts on if it is OK or not.

    Read the article

  • svcutil, WSDL, and the generated interfaces not being sufficient for implementation

    - by chtmd
    I have a WSDL file defining a service that I have to implement in WCF. I had read that I could generate the proxy using svcutil from the WSDL file, and that I could then use the generated interfaces to implement the service. Unfortunately, I can't quite seem to find a way to have the interfaces contain the correct attributes to expose the contracts. All operations have the "OperationContractAttribute" attribute, but it appears as though for the service to be exposed, I require the "OperationContract" for each one. Same thing with "ServiceContractAttribute" and "ServiceContract", and I imagine DataContract, but I haven't gotten that far. I could manually make these changes, but I would much prefer a technique where the existing code could be easily used, or better code could be generated for my uses. Is there some way that this can be done? Thanks. EDIT: Command used: svcutil ObjectManagerService.wsdl /n:*,Sample /o:ObjectManagerServiceProxy.cs /nologo Code sample: public interface ObjectManagerSyncPortType { // CODEGEN: Generating message contract since the operation createObject is neither RPC nor document wrapped. [System.ServiceModel.OperationContractAttribute(Action="http://www.sample.com/createObject", ReplyAction="*")] [System.ServiceModel.XmlSerializerFormatAttribute()] Sample.createObjectResponse1 createObject(Sample.createObjectRequest1 request); As best as I can tell/see the WSDL file is entirely self-contained and requires no additional XSD files.

    Read the article

  • WCF- "The underlying connection was closed: The connection was closed unexpectedly"

    - by SumGuy
    Hi there. I'm recieving that wonderfuly ambiguous error message when using one of my webmethods on my WCF webservice. As that error message doesn't provide any explanation whatsoever allow me to post my theory. I believe it may have something to do with the return type I'm using I have a Types DLL which is refrenced in both the webservice and the client. In this DLL is the base class ExceptionMessages. There is a child of this class called DrawingExcepions. Here is some code: public class ExceptionMessages { public object[] ReturnValue { get; set; } } public class DrawingExceptions : ExceptionMessages { private List<DrawingException> des = new List<DrawingException>(); } public class DrawingException { public Exception ExceptionMsg { get; set; } public List<object> Errors { get; set; } } The using code: [OperationContract] ExceptionMessages createNewBom(Bom bom, DrawingFiles dfs); public ExceptionMessages createNewBOM(Bom bom, DrawingFiles dfs) { return insertAssembly(bom, dfs); } public DrawingExceptions insertAssembly(Bom bom, DrawingFiles dfs) { DrawingExceptions des = new DrawingExceptions(); foreach (DrawingFile d in dfs.drawingFiles) { DrawingException temp = insertNewDrawing(bom, d); if (temp != null) des.addDrawingException(temp); if (d.Child != null) des.addDrawingException(insertAssembly(bom, d.Child)); } return des; } Returns to: ExceptionMessages ems = client.createNewBom(bom, currentDFS); if (ems is DrawingExceptions) { } Basically the return type from the webmethod is ExceptionMessages however I would usually be sending the child class back instead. My only idea is that it's the child that's causing the error but as far as I've read, this should have no effect. Has anyone got any ideas what could be going wrong here? If any more info is required, just ask :) Thanks.

    Read the article

  • Creating instance of a service-side DataContract class on client-side in WCF

    - by hgulyan
    Hi, I have my custom class Customer with its properties. I added DataContract mark above the class and DataMember to properties and it was working fine, but I'm calling a service class's function, passing customer instance as parameter and some of my properties get 0 values. While debugging I can see my properties values and after it gets to the function, some properties' values are 0. Why it can be so? There's no code between this two actions. DataContract mark workes fine, everything's ok. Any suggestions on this issue? I tried to change ByRef to ByVal, but it doesn't change anything. Why it would pass other values right and some of integer types just 0? Maybe the answer is simple, but I can't figure it out. Thank You. <DataContract()> Public Class Customer Private Type_of_clientField As Integer = -1 <DataMember(Order:=1)> Public Property type_of_client() As Integer Get Return Type_of_clientField End Get Set(ByVal value As Integer) Type_of_clientField = value End Set End Property End Class <ServiceContract(SessionMode:=SessionMode.Allowed)> <DataContractFormat()> Public Interface CustomerService <OperationContract()> Function addCustomer(ByRef customer As Customer) As Long End Interface type_of_client properties value is 6 before I call addCustomer function. After it enters that function the value is 0. UPDATE: The issue is in instance creating. When I create an instance of a class on client side, that is stored on service side, some of my properties pass 0 or nothing, but when I call a function of a service class, that returns a new instance of that class, it works fine. What's is the difference? Could that be serialization issue?

    Read the article

  • MS AJAX Library 4.0 Sys.create.dataView

    - by azamsharp
    One again Microsoft poor documentation has left me confused. I am trying to use the new features of the .NET 4.0 framework. I am using the following code to populate the Title and Director but it keeps getting blank. <script language="javascript" type="text/javascript"> Sys.require([Sys.components.dataView, Sys.components.dataContext,Sys.scripts.WebServices], function () { Sys.create.dataView("#moviesView", { dataProvider: "MovieService.svc", fetchOperation: "GetMovies", autoFetch: true }); }); </script> And here it the HTML code: <ul id="moviesView"> <li> {{Title}} - {{Director}} </li> </ul> IS THIS THE LATEST URL TO Start.js file. Here is the Ajax-Enabled WCF Service: [ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class MovieService { [OperationContract] public Movie GetMovies() { return new Movie() { Title = "SS", Director = "SSSSS" }; } } [DataContract] public class Movie { [DataMember] public string Title { get; set; } [DataMember] public string Director { get; set; } }

    Read the article

  • How do I Pass Parameter in Ajax Url?

    - by Nimit Joshi
    I have developed a service which is running successfully. Following is my service code: namespace WcfService1 { [ServiceContract] public interface IService1 { [OperationContract] [WebInvoke(Method="GET", ResponseFormat = WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.Wrapped, UriTemplate="/display/{a}/{b}")] string Display(string a, string b); } } My Service: namespace WcfService1 { public class Service1 : IService1 { public string Display(string a, string b) { int ab = Convert.ToInt32(a); int bc = Convert.ToInt32(b); int cb = ab + bc; return cb.ToString(); } } } How do i call this with the help of ajax url? I have tried out the following code but it is not working. <script type="text/javascript"> $(document).ready(function () { $('#BtnRegister').click(function () { debugger; var No1 = document.getElementById('TxtFirstNumber').value; var No2 = document.getElementById('TxtSecondNumber').value; $.ajax({ cache: false, type: "GET", async: false, url: "http://localhost:22727/Service1.svc/Display", data: 'a=' +No1+'&b='+No2, contentType: "application/json; charset=ytf-8", dataType: "json", processData: true, success: function (result) { alert("data"); }, error: function (xhr, textStatus, errorThrown) { alert(textStatus + ':' + errorThrown); } }); }); }); </script>

    Read the article

  • Invoking WCF service from Javascript

    - by KhanS
    I have a asp.net web application, and have some java script code in it. While calling the service I am getting the exception Service1 is undefined. Below is my code. Service: namespace WebApplication2 { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together. [ServiceContract(Namespace="WCFServices")] public interface IService1 { [OperationContract] string HelloWorld(); } } Implementation namespace WebApplication2 { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together. [ServiceBehavior(IncludeExceptionDetailInFaults = true)] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class Service1 : IService1 { public string HelloWorld() { return "Hello world from service"; } } } ASPX page: <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <asp:ScriptManager ID="QNAScriptManager" runat="server"> <Services> <asp:ServiceReference Path="~/Service1.svc" /> </Services> <Scripts> <asp:ScriptReference Path="~/Scripts/Questions.js" /> </Scripts> </asp:ScriptManager> </asp:Content> Java Script var ServiceProxy; function pageLoad() { ServiceProxy = new Service1(); ServiceProxy.set_defaultSucceededCallback(SucceededCallback); } function GetString() { ServiceProxy.HelloWorld(); } function SucceededCallback(result, userContext, methodName) { var RsltElem = document.getElementById("Results"); RsltElem.innerHTML = result + " from " + methodName + "."; alert("Msg received from service"); }

    Read the article

  • IncludeExceptionDetailInFaults not behaving as thought

    - by pdiddy
    I have this simple test project just to test the IncludeExceptionDetailInFaults behavior. public class Service1 : IService1 { public string GetData(int value) { throw new InvalidCastException("test"); return string.Format("You entered: {0}", value); } } [ServiceContract] public interface IService1 { [OperationContract] string GetData(int value); } In the app.config of the service i have it set to true <serviceDebug includeExceptionDetailInFaults="True" /> On the client side: try { using (var proxy = new ServiceReference1.Service1Client()) Console.WriteLine(proxy.GetData(5)); } catch (Exception ex) { Console.WriteLine(ex.Message); } This is what I thought the behavior was: Setting to includeExceptionDetailInFaults=true would propagate the exception detail to the client. But I'm always getting the CommunicationObjectFaultException. I did try having the FaultContract(typeof(InvalidCastException)) on the contract but same behavior, only getting the CommunicationObjectFaultException. The only way to make it work was to throw new FaultException(new InvalidCastException("test")); But I thought with IncludeExceptionDetailInFaults=true the above was done automatically. Am I missing something?

    Read the article

  • xsd.exe - schema to class - for use with WCF

    - by NealWalters
    I have created a schema as an agreed upon interface between our company and an external company. I am now creating a WCF C# web service to handle the interface. I ran the XSD utility and it created a C# class. The schema was built in BizTalk, and references other schemas, so all-in-all there are over 15 classes being generated. I put [DataContract} attribute in front of each of the classes. Do I have to put the [DataMember] attribute on every single property? When I generate a test client program, the proxy does not have any code for any of these 15 classes. We used to use this technique when using .asmx services, but not sure if it will work the same with WCF. If we change the schema, we would want to regenerate the WCF class, and then we would haev to each time redecorate it with all the [DataMember] attributes? Is there an newer tool similar to XSD.exe that will work better with WCF? Thanks, Neal Walters SOLUTION (buried in one of Saunders answer/comments): Add the XmlSerializerFormat to the Interface definition: [OperationContract] [XmlSerializerFormat] // ADD THIS LINE Transaction SubmitTransaction(Transaction transactionIn); Two notes: 1) After I did this, I saw a lot more .xsds in the my proxy (Service Reference) test client program, but I didn't see the new classes in my intellisense. 2) For some reason, until I did a build on the project, I didn't get all the classes in the intellisense (not sure why).

    Read the article

  • Problem with MessageContract, Generic return types and clientside naming

    - by Soeteman
    I'm building a web service which uses MessageContracts, because I want to add custom fields to my SOAP header. In a previous topic, I learned that a composite response has to be wrapped. For this purpose, I devised a generic ResponseWrapper class. [MessageContract(WrapperNamespace = "http://mynamespace.com", WrapperName="WrapperOf{0}")] public class ResponseWrapper<T> { [MessageBodyMember(Namespace = "http://mynamespace.com")] public T Response { get; set; } } I made a ServiceResult base class, defined as follows: [MessageContract(WrapperNamespace = "http://mynamespace.com")] public class ServiceResult { [MessageBodyMember] public bool Status { get; set; } [MessageBodyMember] public string Message { get; set; } [MessageBodyMember] public string Description { get; set; } } To be able to include the request context in the response, I use a derived class of ServiceResult, which uses generics: [MessageContract(WrapperNamespace = "http://mynamespace.com", WrapperName = "ServiceResultOf{0}")] public class ServiceResult<TRequest> : ServiceResult { [MessageBodyMember] public TRequest Request { get; set; } } This is used in the following way [OperationContract()] ResponseWrapper<ServiceResult<HCCertificateRequest>> OrderHealthCertificate(RequestContext<HCCertificateRequest> context); I expected my client code to be generated as ServiceResultOfHCCertificateRequest OrderHealthCertificate(RequestContextOfHCCertificateRequest context); Instead, I get the following: ServiceResultOfHCCertificateRequestzSOTD_SSj OrderHealthCertificate(CompType1 c1, CompType2 c2, HCCertificateRequest context); CompType1 and CompType2 are properties of the RequestContext class. The problem is that a hash is added to the end of ServiceResultOfHCCertificateRequestzSOTD_SSj. How do I need define my generic return types in order for the client type to be generated as expected (without the hash)?

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10  | Next Page >