Search Results

Search found 7319 results on 293 pages for 'wcf binding'.

Page 7/293 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Invoke WCF rest service razor mvc 4

    - by Raj Esh
    I have been using jQuery to access my REST based wcf service which does not export the meta information. Using ajax, i could populate data into controls. I need guidance and directions as to how i can use these Rest service in my controller. I can't add Service reference to my MVC 4 project since my WCF rest does not to expose Metadata. Should i use UNITY? or any other DI frameworks?. Any sample would be of great help.

    Read the article

  • WCF service and security

    - by Gaz83
    Been building a WP7 app and now I need it to communicate to a WCF service I made to make changes to an SQL database. I am a little concerned about security as the user name and password for accessing the SQL database is in the App.Config. I have read in places that you can encrypt the user name and password in the config file. As the username and password is never exposed to the clients connected to the WCF service, would security in my situation be much of a problem? Just in case anyone suggests a method of security, I do not have SSL on my web server.

    Read the article

  • WCF Keep Alive: Whether to disable keepAliveEnabled

    - by Lijo
    I have a WCF web service hosted in a load balanced environment. I do not need any WCF session related functionality in the service. QUESTION What are the scenarios in which performances will be best if keepAliveEnabled = false keepAliveEnabled = true Reference From Load Balancing By default, the BasicHttpBinding sends a connection HTTP header in messages with a Keep-Alive value, which enables clients to establish persistent connections to the services that support them. This configuration offers enhanced throughput because previously established connections can be reused to send subsequent messages to the same server. However, connection reuse may cause clients to become strongly associated to a specific server within the load-balanced farm, which reduces the effectiveness of round-robin load balancing. If this behavior is undesirable, HTTP Keep-Alive can be disabled on the server using the KeepAliveEnabled property with a CustomBinding or user-defined Binding.

    Read the article

  • Should I use both WCF and ASP.NET Web API

    - by Mithir
    We already have a WCF API with basichttpbinding. Some of the calls have complex objects in both the response and request. We need to add RESTful abilities to the API. at first I tried adding a webHttp endpoint, but I got At most one body parameter can be serialized without wrapper elements If I made it Wrapped it wasn't pure as I need it to be. I got to read this, and this (which states "ASP.NET Web API is the new way to build RESTful service on .NET"). So my question is, should I make 2 APIs(2 different projects)? one for SOAP with WCF and one RESTful with ASP.NET Web API? is there anything wrong architecturally speaking with this approach?

    Read the article

  • WCF Security in a Windows Service

    - by Alphonso
    I have a WCF service which can run as Console App and a Windows Service. I have recently copied the console app up to a W2K3 server with the following security settings: <wsHttpBinding> <binding name="ServiceBinding_Security" transactionFlow="true" > <security mode="TransportWithMessageCredential" > <message clientCredentialType="UserName" /> </security> </binding> </wsHttpBinding> <serviceCredentials> <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="Common.CustomUserNameValidator, Common" /> </serviceCredentials> Security works fine with no problems. I have exactly the same code, but running in a windows service and I get the following error when I try to call any of the methods from a client: System.ServiceModel.Security.MessageSecurityException was unhandled Message="An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail." Source="mscorlib" StackTrace: Server stack trace: at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout) ...... (lots of stacktrace info - not very useful) InnerException: System.ServiceModel.FaultException Message="An error occurred when verifying security for the message." The exception tells me nothing. I'm assuming that it has something to do with acces to system resources from the Windows Service. I've tried running it under the same account as the console app, but no luck. Does anyone have any ideas?

    Read the article

  • WCF Service Layer in n-layered application: performance considerations

    - by Marconline
    Hi all. When I went to University, teachers used to say that in good structured application you have presentation layer, business layer and data layer. This is what I heard for more than 5 years. When I started working I discovered that this is true but sometimes is better to have more than just three layers. Two or three days ago I discovered this article by John Papa that explain how to use Entity Framework in layered application. According to that article you should have: UI Layer and Presentation Layer (Model View Pattern) Service Layer (WCF) Business Layer Data Access Layer Service Layer is, to me, one of the best ideas I've ever heard since I work. Your UI is then completely "diconnected" from Business and Data Layer. Now when I went deeper by looking into provided source code, I began to have some questions. Can you help me in answering them? Question #0: is this a good enterpise application template in your opinion? Question #1: where should I host the service layer? Should it be a Windows Service or what else? Question #2: in the source code provided the service layer expose just an endpoint with WSHttpBinding. This is the most interoperable binding but (I think) the worst in terms of performances (due to serialization and deserializations of objects). Do you agree? Question #3: if you agree with me at Question 2, which kind of binding would you use? Looking forward to hear from you. Have a nice weekend! Marco

    Read the article

  • WCF Service Impersonation

    - by robalot
    Good Day Everyone... Apparently, I'm not setting-up impersonation correctly for my WCF service. I do NOT want to set security on a method-by-method basis (in the actual code-behind). The service (at the moment) is open to be called by everyone on the intranet. So my questions are… Q: What web-config tags am I missing? Q: What do I need to change in the web-config to make impersonation work? The Service Web.config Looks Like... <configuration> <system.web> <authorization> <allow users="?"/> </authorization> <authentication mode="Windows"/> <identity impersonate="true" userName="MyDomain\MyUser" password="MyPassword"/> </system.web> <system.serviceModel> <services> <service behaviorConfiguration="wcfFISH.DataServiceBehavior" name="wcfFISH.DataService"> <endpoint address="" binding="wsHttpBinding" contract="wcfFISH.IFishData"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name="wcfFISH.DataServiceBehavior"> <serviceMetadata httpGetEnabled="false"/> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration>

    Read the article

  • WCF Security in a Windows Service

    - by Alphonso
    I have a WCF service which can run as Console App and a Windows Service. I have recently copied the console app up to a W2K3 server with the following security settings: <wsHttpBinding> <binding name="ServiceBinding_Security" transactionFlow="true" > <security mode="TransportWithMessageCredential" > <message clientCredentialType="UserName" /> </security> </binding> </wsHttpBinding> <serviceCredentials> <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="Common.CustomUserNameValidator, Common" /> </serviceCredentials> Security works fine with no problems. I have exactly the same code, but running in a windows service and I get the following error when I try to call any of the methods from a client: System.ServiceModel.Security.MessageSecurityException was unhandled Message="An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail." Source="mscorlib" StackTrace: Server stack trace: at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout) ...... (lots of stacktrace info - not very useful) InnerException: System.ServiceModel.FaultException Message="An error occurred when verifying security for the message." The exception tells me nothing. I'm assuming that it has something to do with acces to system resources from the Windows Service. I've tried running it under the same account as the console app, but no luck. Does anyone have any ideas?

    Read the article

  • BizTalk configuration broken following WCF hotfix installation

    - by Sir Crispalot
    I usually post over on StackOverflow, but thought this was probably better suited to ServerFault. Please migrate if I'm wrong! I am developing a WCF service and a BizTalk application on my workstation at the moment. As part of the WCF service, I had to install hotfix 971493 from Microsoft which updates some core WCF assemblies. Following installation of that hotfix, I am now experiencing severe issues in my existing BizTalk application. When I attempt to configure the properties of an existing WCF-Custom receive location, I get this error: Error loading properties (System.IO.FileLoadException) The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) If I click OK (the same error repeats four times) I eventually see the WCF-Custom properties dialog. However if I click on the various tabs, I continue to receive errors: The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) (Microsoft.BizTalk.Adapter.Wcf.Admin) The WCF-Custom receive location was working yesterday, and I installed the hotfix this morning. I'm guessing these two are related, and that BizTalk somehow has a reference to the old WCF assemblies. Does anyone know how I can fix this?

    Read the article

  • WCF set bindings on service at runtime

    - by Dave
    My app has to be installed on my client's webservers. Some clients want to use SSL and some do not. My app has a WCF service and I currently have to go into the web.config for each install and switch the security mode from to depending on the client's SSL situation. I am able to set the client bindings at runtime. However, I would like to know if there is a way to set the service bindings at runtime(on the server side).

    Read the article

  • WCF chunking/streaming - make it transparent for client

    - by bybor
    While developing WCF service i've faced problem of transferring large data as method params ( 4 Mb of raw size, not considering transfer/message overhead). The solution for this problem is to use chunking or streaming, but all the samples i've seen assume client is aware of used method and uses available block size for sending/receiving portions of data, and the problem (for me) is that it's not possible to call just one method, like SaveData(DataInformation info) but write wrapper method which will instead iterate smth like SaveDataChunk(byte[] buffer) Could it be somehow made transparent for client, just calling 'SaveData'?

    Read the article

  • How does LinqPad support WCF Data Services?

    - by user341127
    LinqPad supports WCF Data Services. If you assign an URL, such as http://services.odata.org/Northwind/Northwind.svc/. It will list all available data objects and you can query them. I guess LinqPad generates all available data classes at run time by reflection.Emit. I am wondering who can show me to how to do so. Or maybe someone has done it before. Any feedback are appreciated. Ying

    Read the article

  • Extending WCF Data Service to synthesize missing data on request

    - by Schneider
    I have got a WCF Data Service based on a LINQ to SQL data provider. I am making a query "get me all the records between two dates". The problem is that I want to synthesize two extra records such that I always get records that fall on the start and end dates, plus all the ones in between which come from the database. Is there a way to "intercept" the request so I can synthesize these records and return them to the client? Thanks

    Read the article

  • WCF how to pass token for authentication?

    - by Kevin
    I have a WCF service which would like to support basicHttpBinding and webHttpBinding. When the client successfully login, server will generate a token for client to pass to server on all the request make later. Question is how the client can pass the token to server? I don't want to add an extra parameter on every web method to hold the token.

    Read the article

  • WCF service monitoring

    - by Cicik
    I am writing WCF service hosted in WinForms application. Is there some way to monitor performance and statistics(count of instances, count of calls to endpoints, duration of calls, etc...) about service and display them in Form in which service is hosted?

    Read the article

  • Retrieve EF4 POCOs using WCF REST services starter kit

    - by muruge
    I am using WCF REST service (GET method) to retrieve my EF4 POCOs. The service seem to work just fine. When I query the uri in my browser I get the results as expected. In my client application I am trying to use WCF REST Starter Kit's HTTPExtension method - ReadAsDataContract() to convert the result back into my POCO. This works fine when the POCO's navigation property is a single object of related POCO. The problem is when the navigation property is a collection of related POCOs. The ReadAsDataContract() method throws an exception with message "Object reference not set to an instance of an object." Below are my POCOs. [DataContract(Namespace = "", Name = "Trip")] public class Trip { [DataMember(Order = 1)] public virtual int TripID { get; set; } [DataMember(Order = 2)] public virtual int RegionID { get; set; } [DataMember(Order = 3)] public virtual System.DateTime BookingDate { get; set; } [DataMember(Order = 4)] public virtual Region Region { // removed for brevity } } [DataContract(Namespace = "", Name = "Region")] public class Region { [DataMember(Order = 1)] public virtual int RegionID { get; set; } [DataMember(Order = 2)] public virtual string RegionCode { get; set; } [DataMember(Order = 3)] public virtual FixupCollection<Trip> Trips { // removed for brevity } } [CollectionDataContract(Namespace = "", Name = "{0}s", ItemName = "{0}")] [Serializable] public class FixupCollection<T> : ObservableCollection<T> { protected override void ClearItems() { new List<T>(this).ForEach(t => Remove(t)); } protected override void InsertItem(int index, T item) { if (!this.Contains(item)) { base.InsertItem(index, item); } } } And this is how I am trying retrieve a Region POCO. static void GetRegion() { string uri = "http://localhost:8080/TripService/Regions?id=1"; HttpClient client = new HttpClient(uri); using (HttpResponseMessage response = client.Get(uri)) { Region region; response.EnsureStatusIsSuccessful(); try { region = response.Content.ReadAsDataContract<Region>(); // this line throws exception because Region returns a collection of related trips Console.WriteLine(region.RegionName); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } Would appreciate any pointers.

    Read the article

  • Pattern for verifying authenticity of a request to WCF service

    - by fung
    I have a client app that makes calls to a WCF service. This app is on a public computer that's easily accessible and anyone can easily copy the .EXE and .CONFIG of my app into another machine and start using it. Is there a pattern where I can check if the request is coming only from an app on a computer I installed it on and not on one it has been copied to? Thanks in advance.

    Read the article

  • Passing Certificate to Svcutil to generate proxy for OSB Service

    - by webwires
    We are wanting to implement Two-Way SSL security from WCF to OSB Services. We have successfully deployed the certificates so that when you browse to the service with IE you get the appropriate prompt for certificate and then it takes you immediately to the WSDL. But, when you attempt to generate a proxy using svcutil as defined in steps 8 and 9 in this MSDN article. http://msdn.microsoft.com/en-us/library/cc949005.aspx I get the error: A reply message was received for operation 'Get' with action 'http://schemas.xmlsoap.org/ws/2004/09/transfer/Get'. However, your client code requires action 'http://schemas.xmlsoap.org/ws/2004/09/transfer/GetResponse'. The OSB services are set to use Soap 1.2 and the svcutil.exe.config we use is identicle to the article except for the findValue and x509FindType. Instead we used the FindByThumbprint pointing to the "My" store name and "CurrentUser" store location. The cert is there and is the same cert we select from the IE prompt.

    Read the article

  • Authenticating clients in the new WCF Http stack

    - by cibrax
    About this time last year, I wrote a couple of posts about how to use the “Interceptors” from the REST starker kit for implementing several authentication mechanisms like “SAML”, “Basic Authentication” or “OAuth” in the WCF Web programming model. The things have changed a lot since then, and Glenn finally put on our hands a new version of the Web programming model that deserves some attention and I believe will help us a lot to build more Http oriented services in the .NET stack. What you can get today from wcf.codeplex.com is a preview with some cool features like Http Processors (which I already discussed here), a new and improved version of the HttpClient library, Dependency injection and better TDD support among others. However, the framework still does not support an standard way of doing client authentication on the services (This is something planned for the upcoming releases I believe). For that reason, moving the existing authentication interceptors to this new programming model was one of the things I did in the last few days. In order to make authentication simple and easy to extend,  I first came up with a model based on what I called “Authentication Interceptors”. An authentication interceptor maps to an existing Http authentication mechanism and implements the following interface, public interface IAuthenticationInterceptor{ string Scheme { get; } bool DoAuthentication(HttpRequestMessage request, HttpResponseMessage response, out IPrincipal principal);} An authentication interceptors basically needs to returns the http authentication schema that implements in the property “Scheme”, and implements the authentication mechanism in the method “DoAuthentication”. As you can see, this last method “DoAuthentication” only relies on the HttpRequestMessage and HttpResponseMessage classes, making the testing of this interceptor very simple (There is no need to do some black magic with the WCF context or messages). After this, I implemented a couple of interceptors for supporting basic authentication and brokered authentication with SAML (using WIF) in my services. The following code illustrates how the basic authentication interceptors looks like. public class BasicAuthenticationInterceptor : IAuthenticationInterceptor{ Func<UsernameAndPassword, bool> userValidation; string realm;  public BasicAuthenticationInterceptor(Func<UsernameAndPassword, bool> userValidation, string realm) { if (userValidation == null) throw new ArgumentNullException("userValidation");  if (string.IsNullOrEmpty(realm)) throw new ArgumentNullException("realm");  this.userValidation = userValidation; this.realm = realm; }  public string Scheme { get { return "Basic"; } }  public bool DoAuthentication(HttpRequestMessage request, HttpResponseMessage response, out IPrincipal principal) { string[] credentials = ExtractCredentials(request); if (credentials.Length == 0 || !AuthenticateUser(credentials[0], credentials[1])) { response.StatusCode = HttpStatusCode.Unauthorized; response.Content = new StringContent("Access denied"); response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Basic", "realm=" + this.realm));  principal = null;  return false; } else { principal = new GenericPrincipal(new GenericIdentity(credentials[0]), new string[] {});  return true; } }  private string[] ExtractCredentials(HttpRequestMessage request) { if (request.Headers.Authorization != null && request.Headers.Authorization.Scheme.StartsWith("Basic")) { string encodedUserPass = request.Headers.Authorization.Parameter.Trim();  Encoding encoding = Encoding.GetEncoding("iso-8859-1"); string userPass = encoding.GetString(Convert.FromBase64String(encodedUserPass)); int separator = userPass.IndexOf(':');  string[] credentials = new string[2]; credentials[0] = userPass.Substring(0, separator); credentials[1] = userPass.Substring(separator + 1);  return credentials; }  return new string[] { }; }  private bool AuthenticateUser(string username, string password) { var usernameAndPassword = new UsernameAndPassword { Username = username, Password = password };  if (this.userValidation(usernameAndPassword)) { return true; }  return false; }} This interceptor receives in the constructor a callback in the form of a Func delegate for authenticating the user and the “realm”, which is required as part of the implementation. The rest is a general implementation of the basic authentication mechanism using standard http request and response messages. I also implemented another interceptor for authenticating a SAML token with WIF. public class SamlAuthenticationInterceptor : IAuthenticationInterceptor{ SecurityTokenHandlerCollection handlers = null;  public SamlAuthenticationInterceptor(SecurityTokenHandlerCollection handlers) { if (handlers == null) throw new ArgumentNullException("handlers");  this.handlers = handlers; }  public string Scheme { get { return "saml"; } }  public bool DoAuthentication(HttpRequestMessage request, HttpResponseMessage response, out IPrincipal principal) { SecurityToken token = ExtractCredentials(request);  if (token != null) { ClaimsIdentityCollection claims = handlers.ValidateToken(token);  principal = new ClaimsPrincipal(claims);  return true; } else { response.StatusCode = HttpStatusCode.Unauthorized; response.Content = new StringContent("Access denied");  principal = null;  return false; } }  private SecurityToken ExtractCredentials(HttpRequestMessage request) { if (request.Headers.Authorization != null && request.Headers.Authorization.Scheme == "saml") { XmlTextReader xmlReader = new XmlTextReader(new StringReader(request.Headers.Authorization.Parameter));  var col = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(); SecurityToken token = col.ReadToken(xmlReader);  return token; }  return null; }}This implementation receives a “SecurityTokenHandlerCollection” instance as part of the constructor. This class is part of WIF, and basically represents a collection of token managers to know how to handle specific xml authentication tokens (SAML is one of them). I also created a set of extension methods for injecting these interceptors as part of a service route when the service is initialized. var basicAuthentication = new BasicAuthenticationInterceptor((u) => true, "ContactManager");var samlAuthentication = new SamlAuthenticationInterceptor(serviceConfiguration.SecurityTokenHandlers); // use MEF for providing instancesvar catalog = new AssemblyCatalog(typeof(Global).Assembly);var container = new CompositionContainer(catalog);var configuration = new ContactManagerConfiguration(container); RouteTable.Routes.AddServiceRoute<ContactResource>("contact", configuration, basicAuthentication, samlAuthentication);RouteTable.Routes.AddServiceRoute<ContactsResource>("contacts", configuration, basicAuthentication, samlAuthentication); In the code above, I am injecting the basic authentication and saml authentication interceptors in the “contact” and “contacts” resource implementations that come as samples in the code preview. I will use another post to discuss more in detail how the brokered authentication with SAML model works with this new WCF Http bits. The code is available to download in this location.

    Read the article

  • Enabling Service Availability in WCF Services

    - by cibrax
    It is very important for the enterprise to know which services are operational at any given point. There are many factors that can affect the availability of the services, some of them are external like a database not responding or any dependant service not working. However, in some cases, you only want to know whether a service is up or down, so a simple heart-beat mechanism with “Ping” messages would do the trick. Unfortunately, WCF does not provide a built-in mechanism to support this functionality, and you probably don’t to implement a “Ping” operation in any service that you have out there. For solving this in a generic way, there is a WCF extensibility point that comes to help us, the “Operation Invokers”. In a nutshell, an operation invoker is the class responsible invoking the service method with a set of parameters and generate the output parameters with the return value. What I am going to do here is to implement a custom operation invoker that intercepts any call to the service, and detects whether a “Ping” header was attached to the message. If the “Ping” header is detected, the operation invoker returns a new header to tell the client that the service is alive, and the real operation execution is omitted. In that way, we have a simple heart beat mechanism based on the messages that include a "Ping” header, so the client application can determine at any point whether the service is up or down. My operation invoker wraps the default implementation attached by default to any operation by WCF. internal class PingOperationInvoker : IOperationInvoker { IOperationInvoker innerInvoker; object[] outputs = null; object returnValue = null; public const string PingHeaderName = "Ping"; public const string PingHeaderNamespace = "http://tellago.serviceModel"; public PingOperationInvoker(IOperationInvoker innerInvoker, OperationDescription description) { this.innerInvoker = innerInvoker; outputs = description.SyncMethod.GetParameters() .Where(p => p.IsOut) .Select(p => DefaultForType(p.ParameterType)).ToArray(); var returnValue = DefaultForType(description.SyncMethod.ReturnType); } private static object DefaultForType(Type targetType) { return targetType.IsValueType ? Activator.CreateInstance(targetType) : null; } public object Invoke(object instance, object[] inputs, out object[] outputs) { object returnValue; if (Invoke(out returnValue, out outputs)) { return returnValue; } else { return this.innerInvoker.Invoke(instance, inputs, out outputs); } } private bool Invoke(out object returnValue, out object[] outputs) { object untypedProperty = null; if (OperationContext.Current .IncomingMessageProperties.TryGetValue(HttpRequestMessageProperty.Name, out untypedProperty)) { var httpRequestProperty = untypedProperty as HttpRequestMessageProperty; if (httpRequestProperty != null) { if (httpRequestProperty.Headers[PingHeaderName] != null) { outputs = this.outputs; if (OperationContext.Current .IncomingMessageProperties.TryGetValue(HttpRequestMessageProperty.Name, out untypedProperty)) { var httpResponseProperty = untypedProperty as HttpResponseMessageProperty; httpResponseProperty.Headers.Add(PingHeaderName, "Ok"); } returnValue = this.returnValue; return true; } } } var headers = OperationContext.Current.IncomingMessageHeaders; if (headers.FindHeader(PingHeaderName, PingHeaderNamespace) > -1) { outputs = this.outputs; MessageHeader<string> header = new MessageHeader<string>("Ok"); var untyped = header.GetUntypedHeader(PingHeaderName, PingHeaderNamespace); OperationContext.Current.OutgoingMessageHeaders.Add(untyped); returnValue = this.returnValue; return true; } returnValue = null; outputs = null; return false; } } The implementation above looks for the “Ping” header either in the Http Request or the Soap message. The next step is to implement a behavior for attaching this operation invoker to the services we want to monitor. [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class PingBehavior : Attribute, IServiceBehavior, IOperationBehavior { public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters) { } public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) { } public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) { foreach (var endpoint in serviceDescription.Endpoints) { foreach (var operation in endpoint.Contract.Operations) { if (operation.Behaviors.Find<PingBehavior>() == null) operation.Behaviors.Add(this); } } } public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters) { } public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation) { } public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation) { dispatchOperation.Invoker = new PingOperationInvoker(dispatchOperation.Invoker, operationDescription); } public void Validate(OperationDescription operationDescription) { } } As an operation invoker can only be added in an “operation behavior”, a trick I learned in the past is that you can implement a service behavior as well and use the “Validate” method to inject it in all the operations, so the final configuration is much easier and cleaner. You only need to decorate the service with a simple attribute to enable the “Ping” functionality. [PingBehavior] public class HelloWorldService : IHelloWorld { public string Hello(string name) { return "Hello " + name; } } On the other hand, the client application needs to send a dummy message with a “Ping” header to detect whether the service is available or not. In order to simplify this task, I created a extension method in the WCF client channel to do this work. public static class ClientChannelExtensions { const string PingNamespace = "http://tellago.serviceModel"; const string PingName = "Ping"; public static bool IsAvailable<TChannel>(this IClientChannel channel, Action<TChannel> operation) { try { using (OperationContextScope scope = new OperationContextScope(channel)) { MessageHeader<string> header = new MessageHeader<string>(PingName); var untyped = header.GetUntypedHeader(PingName, PingNamespace); OperationContext.Current.OutgoingMessageHeaders.Add(untyped); try { operation((TChannel)channel); var headers = OperationContext.Current.IncomingMessageHeaders; if (headers.Any(h => h.Name == PingName && h.Namespace == PingNamespace)) { return true; } else { return false; } } catch (CommunicationException) { return false; } } } catch (Exception) { return false; } } } This extension method basically adds a “Ping” header to the request message, executes the operation passed as argument (Action<TChannel> operation), and looks for the corresponding “Ping” header in the response to see the results. The client application can use this extension with a single line of code, var client = new ServiceReference.HelloWorldClient(); var isAvailable = client.InnerChannel.IsAvailable<IHelloWorld>((c) => c.Hello(null)); The “isAvailable” variable will tell the client application whether the service is available or not. You can download the complete implementation from this location.    

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >