Search Results

Search found 22762 results on 911 pages for 'wcf client'.

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

  • Handling WCF Service Paths in Silverlight 4 – Relative Path Support

    - by dwahlin
    If you’re building Silverlight applications that consume data then you’re probably making calls to Web Services. We’ve been successfully using WCF along with Silverlight for several client Line of Business (LOB) applications and passing a lot of data back and forth. Due to the pain involved with updating the ServiceReferences.ClientConfig file generated by a Silverlight service proxy (see Tim Heuer’s post on that subject to see different ways to deal with it) we’ve been using our own technique to figure out the service URL. Going that route makes it a peace of cake to switch between development, staging and production environments. To start, we have a ServiceProxyBase class that handles identifying the URL to use based on the XAP file’s location (this assumes that the service is in the same Web project that serves up the XAP file). The GetServiceUrlBase() method handles this work: public class ServiceProxyBase { public ServiceProxyBase() { if (!IsDesignTime) { ServiceUrlBase = GetServiceUrlBase(); } } public string ServiceUrlBase { get; set; } public static bool IsDesignTime { get { return (Application.Current == null) || (Application.Current.GetType() == typeof (Application)); } } public static string GetServiceUrlBase() { if (!IsDesignTime) { string url = Application.Current.Host.Source.OriginalString; return url.Substring(0, url.IndexOf("/ClientBin", StringComparison.InvariantCultureIgnoreCase)); } return null; } } Silverlight 4 now supports relative paths to services which greatly simplifies things.  We changed the code above to the following: public class ServiceProxyBase { private const string ServiceUrlPath = "../Services/JobPlanService.svc"; public ServiceProxyBase() { if (!IsDesignTime) { ServiceUrl = ServiceUrlPath; } } public string ServiceUrl { get; set; } public static bool IsDesignTime { get { return (Application.Current == null) || (Application.Current.GetType() == typeof (Application)); } } public static string GetServiceUrl() { if (!IsDesignTime) { return ServiceUrlPath; } return null; } } Our ServiceProxy class derives from ServiceProxyBase and handles creating the ABC’s (Address, Binding, Contract) needed for a WCF service call. Looking through the code (mainly the constructor) you’ll notice that the service URI is created by supplying the base path to the XAP file along with the relative path defined in ServiceProxyBase:   public class ServiceProxy : ServiceProxyBase, IServiceProxy { private const string CompletedEventargs = "CompletedEventArgs"; private const string Completed = "Completed"; private const string Async = "Async"; private readonly CustomBinding _Binding; private readonly EndpointAddress _EndPointAddress; private readonly Uri _ServiceUri; private readonly Type _ProxyType = typeof(JobPlanServiceClient); public ServiceProxy() { _ServiceUri = new Uri(Application.Current.Host.Source, ServiceUrl); var elements = new BindingElementCollection { new BinaryMessageEncodingBindingElement(), new HttpTransportBindingElement { MaxBufferSize = 2147483647, MaxReceivedMessageSize = 2147483647 } }; // order of entries in collection is significant: dumb _Binding = new CustomBinding(elements); _EndPointAddress = new EndpointAddress(_ServiceUri); } #region IServiceProxy Members /// <summary> /// Used to call a WCF service operation. /// </summary> /// <typeparam name="T">The type of EventArgs that will be returned by the service operation.</typeparam> /// <param name="callback">The method to call once the WCF call returns (the callback).</param> /// <param name="parameters">Any parameters that the service operation expects.</param> public void CallService<T>(EventHandler<T> callback, params object[] parameters) where T : EventArgs { try { var proxy = new JobPlanServiceClient(_Binding, _EndPointAddress); string action = typeof (T).Name.Replace(CompletedEventargs, String.Empty); _ProxyType.GetEvent(action + Completed).AddEventHandler(proxy, callback); _ProxyType.InvokeMember(action + Async, BindingFlags.InvokeMethod, null, proxy, parameters); } catch (Exception exp) { MessageBox.Show("Unable to use ServiceProxy.CallService to retrieve data: " + exp.Message); } } #endregion } The relative path support for calling services in Silverlight 4 definitely simplifies code and is yet another good reason to move from Silverlight 3 to Silverlight 4.   For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit http://www.thewahlingroup.com.

    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

  • Getting WCF Bindings and Behaviors from any config source

    - by cibrax
    The need of loading WCF bindings or behaviors from different sources such as files in a disk or databases is a common requirement when dealing with configuration either on the client side or the service side. The traditional way to accomplish this in WCF is loading everything from the standard configuration section (serviceModel section) or creating all the bindings and behaviors by hand in code. However, there is a solution in the middle that becomes handy when more flexibility is needed. This solution involves getting the configuration from any place, and use that configuration to automatically configure any existing binding or behavior instance created with code.  In order to configure a binding instance (System.ServiceModel.Channels.Binding) that you later inject in any endpoint on the client channel or the service host, you first need to get a binding configuration section from any configuration file (you can generate a temp file on the fly if you are using any other source for storing the configuration).  private BindingsSection GetBindingsSection(string path) { System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration( new System.Configuration.ExeConfigurationFileMap() { ExeConfigFilename = path }, System.Configuration.ConfigurationUserLevel.None); var serviceModel = ServiceModelSectionGroup.GetSectionGroup(config); return serviceModel.Bindings; }   The BindingsSection contains a list of all the configured bindings in the serviceModel configuration section, so you can iterate through all the configured binding that get the one you need (You don’t need to have a complete serviceModel section, a section with the bindings only works).  public Binding ResolveBinding(string name) { BindingsSection section = GetBindingsSection(path); foreach (var bindingCollection in section.BindingCollections) { if (bindingCollection.ConfiguredBindings.Count > 0 && bindingCollection.ConfiguredBindings[0].Name == name) { var bindingElement = bindingCollection.ConfiguredBindings[0]; var binding = (Binding)Activator.CreateInstance(bindingCollection.BindingType); binding.Name = bindingElement.Name; bindingElement.ApplyConfiguration(binding); return binding; } } return null; }   The code above does just that, and also instantiates and configures the Binding object (System.ServiceModel.Channels.Binding) you are looking for. As you can see, the binding configuration element contains a method “ApplyConfiguration” that receives the binding instance that needs to be configured. A similar thing can be done for instance with the “Endpoint” behaviors. You first get the BehaviorsSection, and then, the behavior you want to use.  private BehaviorsSection GetBehaviorsSection(string path) { System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration( new System.Configuration.ExeConfigurationFileMap() { ExeConfigFilename = path }, System.Configuration.ConfigurationUserLevel.None); var serviceModel = ServiceModelSectionGroup.GetSectionGroup(config); return serviceModel.Behaviors; }public List<IEndpointBehavior> ResolveEndpointBehavior(string name) { BehaviorsSection section = GetBehaviorsSection(path); List<IEndpointBehavior> endpointBehaviors = new List<IEndpointBehavior>(); if (section.EndpointBehaviors.Count > 0 && section.EndpointBehaviors[0].Name == name) { var behaviorCollectionElement = section.EndpointBehaviors[0]; foreach (BehaviorExtensionElement behaviorExtension in behaviorCollectionElement) { object extension = behaviorExtension.GetType().InvokeMember("CreateBehavior", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, behaviorExtension, null); endpointBehaviors.Add((IEndpointBehavior)extension); } return endpointBehaviors; } return null; }   In this case, the code for creating the behavior instance is more tricky. First of all, a behavior in the configuration section actually represents a set of “IEndpoint” behaviors, and the behavior element you get from the configuration does not have any public method to configure an existing behavior instance. This last one only contains a protected method “CreateBehavior” that you can use for that purpose. Once you get this code implemented, a client channel can be easily configured as follows  var binding = resolver.ResolveBinding("MyBinding"); var behaviors = resolver.ResolveEndpointBehavior("MyBehavior"); SampleServiceClient client = new SampleServiceClient(binding, new EndpointAddress(new Uri("http://localhost:13749/SampleService.svc"), new DnsEndpointIdentity("localhost"))); foreach (var behavior in behaviors) { if(client.Endpoint.Behaviors.Contains(behavior.GetType())) { client.Endpoint.Behaviors.Remove(behavior.GetType()); } client.Endpoint.Behaviors.Add(behavior); }   The code above assumes that a configuration file (in any place) with a binding “MyBinding” and a behavior “MyBehavior” exists. That file can look like this,  <system.serviceModel> <bindings> <basicHttpBinding> <binding name="MyBinding"> <security mode="Transport"></security> </binding> </basicHttpBinding> </bindings> <behaviors> <endpointBehaviors> <behavior name="MyBehavior"> <clientCredentials> <windows/> </clientCredentials> </behavior> </endpointBehaviors> </behaviors> </system.serviceModel>   The same thing can be done of course in the service host if you want to manually configure the bindings and behaviors.  

    Read the article

  • How to create a new WCF/MVC/jQuery application from scratch

    - by pjohnson
    As a corporate developer by trade, I don't get much opportunity to create from-the-ground-up web sites; usually it's tweaks, fixes, and new functionality to existing sites. And with hobby sites, I often don't find the challenges I run into with enterprise systems; usually it's starting from Visual Studio's boilerplate project and adding whatever functionality I want to play around with, rarely deploying outside my own machine. So my experience creating a new enterprise-level site was a bit dated, and the technologies to do so have come a long way, and are much more ready to go out of the box. My intention with this post isn't so much to provide any groundbreaking insights, but to just tie together a lot of information in one place to make it easy to create a new site from scratch. Architecture One site I created earlier this year had an MVC 3 front end and a WCF 4-driven service layer. Using Visual Studio 2010, these project types are easy enough to add to a new solution. I created a third Class Library project to store common functionality the front end and services layers both needed to access, for example, the DataContract classes that the front end uses to call services in the service layer. By keeping DataContract classes in a separate project, I avoided the need for the front end to have an assembly/project reference directly to the services code, a bit cleaner and more flexible of an SOA implementation. Consuming the service Even by this point, VS has given you a lot. You have a working web site and a working service, neither of which do much but are great starting points. To wire up the front end and the services, I needed to create proxy classes and WCF client configuration information. I decided to use the SvcUtil.exe utility provided as part of the Windows SDK, which you should have installed if you installed VS. VS also provides an Add Service Reference command since the .NET 1.x ASMX days, which I've never really liked; it creates several .cs/.disco/etc. files, some of which contained hardcoded URL's, adding duplicate files (*1.cs, *2.cs, etc.) without doing a good job of cleaning up after itself. I've found SvcUtil much cleaner, as it outputs one C# file (containing several proxy classes) and a config file with settings, and it's easier to use to regenerate the proxy classes when the service changes, and to then maintain all your configuration in one place (your Web.config, instead of the Service Reference files). I provided it a reference to a copy of my common assembly so it doesn't try to recreate the data contract classes, had it use the type List<T> for collections, and modified the output files' names and .NET namespace, ending up with a command like: svcutil.exe /l:cs /o:MyService.cs /config:MyService.config /r:MySite.Common.dll /ct:System.Collections.Generic.List`1 /n:*,MySite.Web.ServiceProxies http://localhost:59999/MyService.svc I took the generated MyService.cs file and drop it in the web project, under a ServiceProxies folder, matching the namespace and keeping it separate from classes I coded manually. Integrating the config file took a little more work, but only needed to be done once as these settings didn't often change. A great thing Microsoft improved with WCF 4 is configuration; namely, you can use all the default settings and not have to specify them explicitly in your config file. Unfortunately, SvcUtil doesn't generate its config file this way. If you just copy & paste MyService.config's contents into your front end's Web.config, you'll copy a lot of settings you don't need, plus this will get unwieldy if you add more services in the future, each with its own custom binding. Really, as the only mandatory settings are the endpoint's ABC's (address, binding, and contract) you can get away with just this: <system.serviceModel>  <client>    <endpoint address="http://localhost:59999/MyService.svc" binding="wsHttpBinding" contract="MySite.Web.ServiceProxies.IMyService" />  </client></system.serviceModel> By default, the services project uses basicHttpBinding. As you can see, I switched it to wsHttpBinding, a more modern standard. Using something like netTcpBinding would probably be faster and more efficient since the client & service are both written in .NET, but it requires additional server setup and open ports, whereas switching to wsHttpBinding is much simpler. From an MVC controller action method, I instantiated the client, and invoked the method for my operation. As with any object that implements IDisposable, I wrapped it in C#'s using() statement, a tidy construct that ensures Dispose gets called no matter what, even if an exception occurs. Unfortunately there are problems with that, as WCF's ClientBase<TChannel> class doesn't implement Dispose according to Microsoft's own usage guidelines. I took an approach similar to Technology Toolbox's fix, except using partial classes instead of a wrapper class to extend the SvcUtil-generated proxy, making the fix more seamless from the controller's perspective, and theoretically, less code I have to change if and when Microsoft fixes this behavior. User interface The MVC 3 project template includes jQuery and some other common JavaScript libraries by default. I updated the ones I used to the latest versions using NuGet, available in VS via the Tools > Library Package Manager > Manage NuGet Packages for Solution... > Updates. I also used this dialog to remove packages I wasn't using. Given that it's smart enough to know the difference between the .js and .min.js files, I was hoping it would be smart enough to know which to include during build and publish operations, but this doesn't seem to be the case. I ended up using Cassette to perform the minification and bundling of my JavaScript and CSS files; ASP.NET 4.5 includes this functionality out of the box. The web client to web server link via jQuery was easy enough. In my JavaScript function, unobtrusively wired up to a button's click event, I called $.ajax, corresponding to an action method that returns a JsonResult, accomplished by passing my model class to the Controller.Json() method, which jQuery helpfully translates from JSON to a JavaScript object.$.ajax calls weren't perfectly straightforward. I tried using the simpler $.post method instead, but ran into trouble without specifying the contentType parameter, which $.post doesn't have. The url parameter is simple enough, though for flexibility in how the site is deployed, I used MVC's Url.Action method to get the URL, then sent this to JavaScript in a JavaScript string variable. If the request needed input data, I used the JSON.stringify function to convert a JavaScript object with the parameters into a JSON string, which MVC then parses into strongly-typed C# parameters. I also specified "json" for dataType, and "application/json; charset=utf-8" for contentType. For success and error, I provided my success and error handling functions, though success is a bit hairier. "Success" in this context indicates whether the HTTP request succeeds, not whether what you wanted the AJAX call to do on the web server was successful. For example, if you make an AJAX call to retrieve a piece of data, the success handler will be invoked for any 200 OK response, and the error handler will be invoked for failed requests, e.g. a 404 Not Found (if the server rejected the URL you provided in the url parameter) or 500 Internal Server Error (e.g. if your C# code threw an exception that wasn't caught). If an exception was caught and handled, or if the data requested wasn't found, this would likely go through the success handler, which would need to do further examination to verify it did in fact get back the data for which it asked. I discuss this more in the next section. Logging and exception handling At this point, I had a working application. If I ran into any errors or unexpected behavior, debugging was easy enough, but of course that's not an option on public web servers. Microsoft Enterprise Library 5.0 filled this gap nicely, with its Logging and Exception Handling functionality. First I installed Enterprise Library; NuGet as outlined above is probably the best way to do so. I needed a total of three assembly references--Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, and Microsoft.Practices.EnterpriseLibrary.Logging. VS links with the handy Enterprise Library 5.0 Configuration Console, accessible by right-clicking your Web.config and choosing Edit Enterprise Library V5 Configuration. In this console, under Logging Settings, I set up a Rolling Flat File Trace Listener to write to log files but not let them get too large, using a Text Formatter with a simpler template than that provided by default. Logging to a different (or additional) destination is easy enough, but a flat file suited my needs. At this point, I verified it wrote as expected by calling the Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write method from my C# code. With those settings verified, I went on to wire up Exception Handling with Logging. Back in the EntLib Configuration Console, under Exception Handling, I used a LoggingExceptionHandler, setting its Logging Category to the category I already had configured in the Logging Settings. Then, from code (e.g. a controller's OnException method, or any action method's catch block), I called the Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicy.HandleException method, providing the exception and the exception policy name I had configured in the Exception Handling Settings. Before I got this configured correctly, when I tried it out, nothing was logged. In working with .NET, I'm used to seeing an exception if something doesn't work or isn't set up correctly, but instead working with these EntLib modules reminds me more of JavaScript (before the "use strict" v5 days)--it just does nothing and leaves you to figure out why, I presume due in part to the listener pattern Microsoft followed with the Enterprise Library. First, I verified logging worked on its own. Then, verifying/correcting where each piece wires up to the next resolved my problem. Your C# code calls into the Exception Handling module, referencing the policy you pass the HandleException method; that policy's configuration contains a LoggingExceptionHandler that references a logCategory; that logCategory should be added in the loggingConfiguration's categorySources section; that category references a listener; that listener should be added in the loggingConfiguration's listeners section, which specifies the name of the log file. One final note on error handling, as the proper way to handle WCF and MVC errors is a whole other very lengthy discussion. For AJAX calls to MVC action methods, depending on your configuration, an exception thrown here will result in ASP.NET'S Yellow Screen Of Death being sent back as a response, which is at best unnecessarily and uselessly verbose, and at worst a security risk as the internals of your application are exposed to potential hackers. I mitigated this by overriding my controller's OnException method, passing the exception off to the Exception Handling module as above. I created an ErrorModel class with as few properties as possible (e.g. an Error string), sending as little information to the client as possible, to both maximize bandwidth and mitigate risk. I then return an ErrorModel in JSON format for AJAX requests: if (filterContext.HttpContext.Request.IsAjaxRequest()){    filterContext.Result = Json(new ErrorModel(...));    filterContext.ExceptionHandled = true;} My $.ajax calls from the browser get a valid 200 OK response and go into the success handler. Before assuming everything is OK, I check if it's an ErrorModel or a model containing what I requested. If it's an ErrorModel, or null, I pass it to my error handler. If the client needs to handle different errors differently, ErrorModel can contain a flag, error code, string, etc. to differentiate, but again, sending as little information back as possible is ideal. Summary As any experienced ASP.NET developer knows, this is a far cry from where ASP.NET started when I began working with it 11 years ago. WCF services are far more powerful than ASMX ones, MVC is in many ways cleaner and certainly more unit test-friendly than Web Forms (if you don't consider the code/markup commingling you're doing again), the Enterprise Library makes error handling and logging almost entirely configuration-driven, AJAX makes a responsive UI more feasible, and jQuery makes JavaScript coding much less painful. It doesn't take much work to get a functional, maintainable, flexible application, though having it actually do something useful is a whole other matter.

    Read the article

  • Setting custom behaviour via .config file - why doesn't this work?

    - by Andrew Shepherd
    I am attempting to insert a custom behavior into my service client, following the example here. I appear to be following all of the steps, but I am getting a ConfigurationErrorsException. Is there anyone more experienced than me who can spot what I'm doing wrong? Here is the entire app.config file. <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <behaviors> <endpointBehaviors> <behavior name="ClientLoggingEndpointBehaviour"> <myLoggerExtension /> </behavior> </endpointBehaviors> </behaviors> <extensions> <behaviorExtensions> <add name="myLoggerExtension" type="ChatClient.ClientLoggingEndpointBehaviourExtension, ChatClient, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"/> </behaviorExtensions> </extensions> <bindings> </bindings> <client> <endpoint behaviorConfiguration="ClientLoggingEndpointBehaviour" name="ChatRoomClientEndpoint" address="http://localhost:8016/ChatRoom" binding="wsDualHttpBinding" contract="ChatRoomLib.IChatRoom" /> </client> </system.serviceModel> </configuration> Here is the exception message: An error occurred creating the configuration section handler for system.serviceModel/behaviors: Extension element 'myLoggerExtension' cannot be added to this element. Verify that the extension is registered in the extension collection at system.serviceModel/extensions/behaviorExtensions. Parameter name: element (C:\Documents and Settings\Andrew Shepherd\My Documents\Visual Studio 2008\Projects\WcfPractice\ChatClient\bin\Debug\ChatClient.vshost.exe.config line 5) I know that I've correctly written the reference to the ClientLoggingEndpointBehaviourExtensionobject, because through the debugger I can see it being instantiated.

    Read the article

  • WCF to WCF communication 401, HttpClient

    - by youwhut
    I have a WCF REST service that needs to communicate with another WCF REST service. There are three websites: Default Web Site Website1 Website2 If I set up both services in Default Web Site and connect to the other (using HttpClient) using the URI http://localhost/service then everything is okay. The desired set-up is to move these two services to separate websites and rather than using the URI http://localhost/service, accessing the service via http://website1.domain.com/service still using HttpClient. I received the exception: System.ArgumentOutOfRangeException: Unauthorized (401) is not one of the following: OK (200), Created (201), Accepted (202), NonAuthoritativeInformation (203), NoContent (204), ResetContent (205), PartialContent (206) I can see this is a 401, but what is going on here? Thanks

    Read the article

  • Client server architecture question

    - by Shane Fulmer
    I am working on a client server system, and am running into issues where multiple clients are executing an action at the same time. We are able to solve this by locking on the critical section of code, which ensures that the first client will complete the action before the second client enters the code block. My question is this: our server is also clustered, so multiple instances of the server itself can exist, which recreates the same problem as before. How could we solve this problem? Thanks!

    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

  • Pass a JSON array to a WCF web service

    - by Tawani
    I am trying to pass a JSON array to a WCF service. But it doesn't seem to work. I actually pulled an array [GetStudents] out the service and sent the exact same array back to the service [SaveStudents] and nothing (empty array) was received. The JSON array is of the format: [ {"Name":"John","Age":12}, {"Name":"Jane","Age":11}, {"Name":"Bill","Age":12} ] And the contracts are of the following format: //Contracts [DataContract] public class Student{ [DataMember]public string Name { get; set; } [DataMember]public int Age{ get; set; } } [CollectionDataContract(Namespace = "")] public class Students : List<Student> { [DataMember]public Endorsements() { } [DataMember]public Endorsements(IEnumerable<Student> source) : base(source) { } } //Operations public Students GetStudents() { var result = new Students(); result.Add(new Student(){Name="John",12}); result.Add(new Student(){Name="Jane",11}); result.Add(new Student(){Name="Bill",12}); return result; } //Operations public void SaveStudents(Students list) { Console.WriteLine(list.Count); //It always returns zero } It there a particular way to send an array to a WCF REST service?

    Read the article

  • WCF Service Client Lifetime

    - by Burt
    I have a WPF appliction that uses WCF services to make calls to the server. I use this property in my code to access the service private static IProjectWcfService ProjectService { get { _projectServiceFactory = new ProjectWcfServiceFactory(); return _projectServiceFactory.Create(); } } The Create on the factory looks like this public IProjectWcfService Create() { _serviceClient = new ProjectWcfServiceClient(); //ToDo: Need some way of saving username and password _serviceClient.ClientCredentials.UserName.UserName = "Brendan"; _serviceClient.ClientCredentials.UserName.Password = "password"; return _serviceClient; } To access the service methods I use somethingn like the following. ProjectService.Save(dto); Is this a good approach for what I am trying to do? I am getting an errorthat I can't track down that I think may be realted to having too many service client connections open (is this possible?) notice I never close the service client or reuse it. What would the best practice for WCF service client's be for WPF calling? Thanks in advance...

    Read the article

  • WCF Service timeout in Callback

    - by Muckers Mate
    I'm trying to get to grips with WCF, in particular writing a WCF Service application with callback. I've setup the service, together with the callback contract but when the callback is called, the app is timing out. Essentially, from a client I'm setting a property within the service class. The Setter of this property, if it fails validation fires a callback and, well, this is timing out. I realise that this is probably to it not being an Asynchronous calback, but can someone please show me how to resolve this? Thanks // The call back (client-side) interface public interface ISAPUploadServiceReply { [OperationContract(IsOneWay = true)] void Reply(int stateCode); } // The Upload Service interface [ServiceContract(CallbackContract = typeof(ISAPUploadServiceReply))] public interface ISAPUploadService { int ServerState { [OperationContract] get; [OperationContract(IsOneWay=true)] set; And the implementation... public int ServerState { get { return serverState; } set { if (InvalidState(Value)) { var to = OperationContext.Current.GetCallbackChannel<ISAPUploadServiceReply>(); to.Reply(eInvalidState); } else serverState = value; } }

    Read the article

  • Reading data from an Entity Framework data model through a WCF Data Service

    - by nikolaosk
    This is going to be the fourth post of a series of posts regarding ASP.Net and the Entity Framework and how we can use Entity Framework to access our datastore. You can find the first one here , the second one here and the third one here . I have a post regarding ASP.Net and EntityDataSource. You can read it here .I have 3 more posts on Profiling Entity Framework applications. You can have a look at them here , here and here . Microsoft with .Net 3.0 Framework, introduced WCF. WCF is Microsoft's...(read more)

    Read the article

  • Quick ways to boost performance and scalability of ASP.NET, WCF and Desktop Clients

    - by oazabir
    There are some simple configuration changes that you can make on machine.config and IIS to give your web applications significant performance boost. These are simple harmless changes but makes a lot of difference in terms of scalability. By tweaking system.net changes, you can increase the number of parallel calls that can be made from the services hosted on your servers as well as on desktop computers and thus increase scalability. By changing WCF throttling config you can increase number of simultaneous calls WCF can accept and thus make most use of your hardware power. By changing ASP.NET process model, you can increase number of concurrent requests that can be served by your website. And finally by turning on IIS caching and dynamic compression, you can dramatically increase the page download speed on browsers and and overall responsiveness of your applications. Read the CodeProject article for more details. http://www.codeproject.com/KB/webservices/quickwins.aspx Please vote for me if you find the article useful.

    Read the article

  • WCF or ASMX WebService

    - by karthi
    I have been asked to create a web service that communicates with Auth.NET CIM and Shipsurance API. This web service will be used by multiple applications (one a desktop and another a web application). Am confused whether to go for WCF or asmx web service . Auth.NET CIM and Shipsurance API have asmx webservices which i would be calling in my newly created web service.So is WCF the right way to Go or can i stay with asmx? Can Some one please guide. Let me know if this question is inappropriate here and needs to be moved to stackoverflow or somewhere else.

    Read the article

  • 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

  • Hosting WCF over internet

    - by user1876804
    I am pretty new to exposing the WCF services hosted on IIS over internet. I will be deploying a WCF service over IIS(6 or 7) and would like to expose this service over the internet. This will be hosted in a corporate network having firewall, I want this service to be accessible over the internet(should be able to pass through the firewall) I did some research on this and some of the pointers I got: 1. I could use wsHTTPBinding or nettcpbinding (the client is intended to be .net client). Which of the bindings is preferable. 2. To overcome the corporate I came across DMZ server, what is the purpose of this and do I really need to use this). 3. I will be passing some files between the client and server, and the client needs to know the progress of the processing on server and the end result. I know this is a very broad question to ask, but could anyone give me pointers where I could start on this and what approach to take for this problem.

    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

  • Custom binding with WCF

    - by user67240
    I have a wcf service where i have to implement the call backs and also i need to host the wcf service on the IIS 6.0, since IIS6.0 doesnot support the net.tcp binding, i decided to go for the custom binding. The reasons for going for custom binding is that the service is accessed by different clients in different timezones. Using custom binding i can set the allowed clock skew time to other values other than the default one. I have problem making the custom binding work for me. here is the server config file <bindings> <customBinding> <binding name="pscNetBinding" openTimeout="00:10:00"> <reliableSession acknowledgementInterval="00:00:00.2000000" flowControlEnabled="true" inactivityTimeout="23:59:59" maxPendingChannels="128" maxRetryCount="8" maxTransferWindowSize="128" ordered="true" /> <compositeDuplex /> <oneWay maxAcceptedChannels="128" packetRoutable="false"> <channelPoolSettings idleTimeout="00:10:00" leaseTimeout="00:10:00" maxOutboundChannelsPerEndpoint="10" /> </oneWay> <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16" messageVersion="Default" writeEncoding="utf-8"> <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> </textMessageEncoding> <httpTransport manualAddressing="false" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" allowCookies="false" authenticationScheme="Anonymous" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" keepAliveEnabled="true" maxBufferSize="2147483647" proxyAuthenticationScheme="Anonymous" realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false" useDefaultWebProxy="true"/> </binding> </customBinding> </bindings> <services> <service name="SchneiderElectric.PSCNet.Server.Services.PSCNetWCFService" behaviorConfiguration="Behaviors1"> <host> <baseAddresses> <add baseAddress ="http://10.155.18.18:2000/PSCNet"/> </baseAddresses> </host> <endpoint address="" binding="customBinding" bindingConfiguration="pscNetBinding" contract="SchneiderElectric.PSCNet.Server.Contracts.IPSCNetWCFService"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="Behaviors1"> <serviceMetadata httpGetEnabled = "true"/> <!--<serviceThrottling maxConcurrentCalls="2048" maxConcurrentSessions="2048" maxConcurrentInstances="2048" /> <dataContractSerializer maxItemsInObjectGraph="2147483647" />--> </behavior> </serviceBehaviors> </behaviors> and here the client config file <bindings> <customBinding> <binding name="pscNetBinding" openTimeout="00:10:00"> <reliableSession acknowledgementInterval="00:00:00.2000000" flowControlEnabled="true" inactivityTimeout="23:59:59" maxPendingChannels="128" maxRetryCount="8" maxTransferWindowSize="128" ordered="true" /> <compositeDuplex /> <oneWay maxAcceptedChannels="128" packetRoutable="false"> <channelPoolSettings idleTimeout="00:10:00" leaseTimeout="00:10:00" maxOutboundChannelsPerEndpoint="10" /> </oneWay> <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16" messageVersion="Default" writeEncoding="utf-8" > <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> </textMessageEncoding > <httpTransport manualAddressing="false" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" allowCookies="false" authenticationScheme="Anonymous" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" keepAliveEnabled="true" maxBufferSize="2147483647" proxyAuthenticationScheme="Anonymous" realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false" useDefaultWebProxy="true" /> </binding> </customBinding> </bindings> <client> <endpoint address="http://10.155.18.18:2000/PSCNet" binding="customBinding" bindingConfiguration="pscNetBinding" contract="PSCNetWCFService.IPSCNetWCFService" name="pscNetBinding" /> </client> if i use the server and client on the same machine everything works fine. But as soon as i run the server and client on different machine i get the following error "Could not connect to http://10.155.18.198:9000/e60ba5b3-f979-4922-b9f8-c820caaa04c2. TCP error code 10060: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 10.155.18.198:9000." Can anyone in the community help me in this regard.

    Read the article

  • MEX issues using WCF Test Client over net.pipe

    - by Beaud.
    I'm trying to make use of WCF Test Client along with named pipes but I get the following error: Error: Cannot obtain Metadata from net.pipe://localhost/MyService Here's my web.config: <system.serviceModel> <services> <service name="MyNamespace.MyService" behaviorConfiguration="MEX"> <endpoint address="net.pipe://localhost/MyService" binding="netNamedPipeBinding" contract="MyNamespace.MyService.IMyService" /> <endpoint address="net.pipe://localhost/MEX" binding="mexNamedPipeBinding" contract="IMetadataExchange" /> </service> </services> <client> <endpoint address="net.pipe://localhost/MyService" binding="netNamedPipeBinding" contract="MyNamespace.MyService.IMyService" /> </client> <behaviors> <serviceBehaviors> <behavior name="MEX"> <serviceMetadata /> </behavior> </serviceBehaviors> </behaviors> What's wrong? I have tried both net.pipe://localhost/MyService and net.pipe://localhost/MEX. Any help would be appreciated, thanks!

    Read the article

  • WCF service The maximum array length quota (16384) has been exceeded

    - by dmitry.baranovsky
    I have a wsf service and a client application. While trying to communicate the client and the service I've gotten the following message: "The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:blob. The InnerException message was 'There was an error deserializing the object of type FileBlob. The maximum array length quota (16384) has been exceeded while reading XML data. This quota may be increased by changing the MaxArrayLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader. Line 1, position 25931.'. Please see InnerException for more details." I have the customBinding element and it doesn't allow me to insert "readerQuotas" section. In both the client and service configs I have the following binding element: <customBinding> <binding name="LicenseServiceBinding" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"> <security authenticationMode="UserNameOverTransport"> <localClientSettings maxClockSkew="00:07:00" /> <localServiceSettings maxClockSkew="00:07:00" /> </security> <windowsStreamSecurity /> <httpsTransport maxReceivedMessageSize="2147483646"/> </binding> </customBinding> Thanks in advance for any help:)

    Read the article

  • Client-Server Networking Between PHP Client and Java Server

    - by Muhammad Yasir
    Hi there, I have a university project which is already 99% completed. It consists of two parts-website (PHP) and desktop (Java). People have their accounts on the website and they wish to query different information regarding their accounts. They send an SMS which is received by desktop application which queries database of website (MySQL) and sends the reply accordingly. This part is working superbly. The problem is that some times website wishes to instruct the desktop application to send a specific SMS to a particular number. Apparently there seems no way other than putting all the load to the DB server... This is how I made it work. Website puts SMS jobs in a specific table. Java application polls this table again and again and if it finds a job, it executes it. Even this part is working correctly but unfortunately it is not acceptable by my university to poll the DB like this. :( The other approach I could think of is to use client-server one. I tried making Java server and its PHP client. So that whenever an SMS is to be sent, the website opens a socket connection to desktop application and sends two strings (cell # and SMS message). Unfortunately I am unable to do this. I was successfully to make a Java server which works fine when connected by a Java client, similarly my PHP client connects correctly to a PHP server, but when I try to cross them, they start hating each other... PHP shows no error but Java gives StreamCorruptedException when it tries to read header of input stream. Could someone please tell what I can try to make PHP client and Java server work together? Or if the said purpose can be achieved by another means, how? Regards, Yasir

    Read the article

  • WCF 3.5 to 3.0 backwards compatibility with callback services

    - by Miral
    I have a set of existing WCF services hosted in a .NET 3.0 app. They're using the WSHttp bindings and no security. I need to connect to these from a .NET 3.5 client. This seems to be working fine for the one-way services, but I also have some callback services (with CallbackContract and SessionMode = Required, using WSDualHttpBinding); these fail to connect with a timeout somewhere in the ReliableSession code. The service side cannot be changed (it's a historic version issue). Can I modify something on the client side to get this working? (I can connect with a .NET 3.0 client just fine, but I'd rather not be forced to try that path.) The open operation did not complete within the allotted timeout of 00:00:09.9410000. The time allotted to this operation may have been a portion of a longer timeout. Server stack trace: at System.ServiceModel.Channels.ReliableRequestor.ThrowTimeoutException() at System.ServiceModel.Channels.ReliableRequestor.Request(TimeSpan timeout) at System.ServiceModel.Channels.ClientReliableSession.Open(TimeSpan timeout) at System.ServiceModel.Channels.ClientReliableDuplexSessionChannel.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)

    Read the article

  • WCF Http Bindings, Require SSL

    - by JoshKraker
    I have the following binding I'm using with my wsHttpBinding webservice. <binding name="wsHttpConfig"> <security> <transport clientCredentialType="None"/> </security> </binding> The issue is that it allows for the client to connect using either Http or Https. I would like to require them to use SSL. I tried adding the following: <system.web.extensions> <scripting> <webServices> <authenticationService enabled="true" requireSSL = "true"/> </webServices> </scripting> </system.web.extensions> But it had no effect; client could still connect with Http. I then tried checking the "Require SSL" in the IIS7 SSL Settings and had client certificates radio set to Accept. Now, when I try to view the service I am getting the error "Could not find a base address that matches scheme http for the endpoint with binding WSHttpBinding. Registered base address schemes are [https]." Anyone know exactly how to fix this error? I have been googling for the last 3 hours trying 500 different combinations (not 500, but too many to list) and could not get anything to run.

    Read the article

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