European Silverlight Hosting BLOG

BLOG about Latest Silverlight Hosting and Its Techologies - Dedicated to European Windows Hosting Customer

European WCF 4.5 Hosting - Amsterdam :: Improvement Windows Communication Foundation (WCF) in .NET 4.5

clock October 1, 2013 09:03 by author Scott

New versions of the Windows Workflow Foundation (WF) and Windows Communication Foundation (WCF) are available in the .NET Framework 4.5, which is included with Windows Server 2012 and Windows 8. The upgrades improve the developer experience and the manageability of applications built using the foundations, while adding new capabilities. Some benefits, such as WF performance improvements and WCF configuration simplification can be realized for existing applications without requiring developers to make modifications. However, a majority of the enhancements are most helpful when writing new code.

WF 4.5 Brings Better Designer, Versioning

WF offers a specialized programming environment for business processes, called workflows. WF 4.5 improves on the previous version, WF 4, while providing backward compatibility.

WF Simplifies Business Process Programming

WF consists of programming interfaces, design and debugging tools, and a runtime engine (which is separate from the common language runtime included with the .NET Framework) that enable the implementation and execution of workflow processes, reducing the amount of code a developer must write.

Workflows are specialized programs that automate custom, often long-running, business processes and enforce business rules in applications. Using software to automate workflows can relieve workers from having to perform repetitive and mechanical tasks, ensure that required procedures are consistently followed, and improve the reliability, tracking, and transparency of those procedures. Several Microsoft products, including SharePoint Server, Dynamics CRM, Dynamics AX, and Team Foundation Server employ WF for workflows.

Developers build workflows in WF by assembling groups of activities, which represent the tasks and logic that comprise a business process, using the WF visual designer which generates XAML script, or by writing C# or Visual Basic (VB) code. WF includes a base set of activities that help build the basic structure of workflows, such as control loops and parallel execution paths, and developers can write custom activities that execute code specific to an application's needs. Microsoft applications integrate with WF by offering custom activities that can be used in workflows to deliver product functionality (such as checking an item into a SharePoint document library).

WF 4.5 Improves on WF 4, Maintains Compatibility

WF 4.5 builds on WF 4, which was a major upgrade that wasn't entirely backward compatible with its predecessor, WF 3.5. Microsoft calls WF 4.5 an additive update, implying that it is fully backward compatible with WF 4. WF 4.5 and WF 4 cannot coexist in a Windows installation, since installing .NET 4.5 replaces .NET 4.

Enhancements in WF 4.5 continue on themes addressed in WF 4, such as simplified development and better performance, and include the following:

Contract-first development. WF is often used in combination with WCF to implement workflows that communicate with remote Web services. Contract-first development in WF automatically generates activity objects for existing WCF services, and developers can use these in the WF designer, reducing the work required to create workflows that use Web services.

C# expressions. Code expressions can be included within workflow activities for tasks such as creating output strings. Previously, only VB could be used to write these expressions (even within C# workflow projects), but now C# is supported as well.

More state machine support. A state machine defines a process that exists within one of multiple possible states until an event causes it to move to a different state. States can be revisited indefinitely, or the process can reach a final state. State machines can describe many types of processes, such as order fulfillment for businesses or chemical reactions for scientific research. WF 4.5 adds features for building state machines, including new activities, designer tools that reduce manual steps, and debugging capabilities.

Designer improvements. A graphical designer for building WF workflows is available in Visual Studio (VS), allowing developers to visually create workflows rather than defining them entirely within code (which is also supported). The WF 4.5 designer adds search features (although not replace), an outline view (similar to Word's Navigation pane), and a pan mode, which will help developers work with large workflows. The newest designer also allows annotations to be added to activities to assist search and enable better commenting of intended functionality. Auto-connect simplifies attaching new activities into a workflow, and auto-insert helps when placing an activity between two existing activities in a workflow.

The designer can also be hosted within other applications so that users don't need to run VS to work with workflows targeted for specific solution spaces, and so that users are limited to workflow elements that are relevant to an application domain. However, not all features available in the designer in VS are available when it is hosted elsewhere (for example, C# expressions and some search capabilities are not available).

Workflow versioning. Workflow processes are prone to revisions, but WF has not previously offered versioning support, leaving the task to developers and IT personnel. WF 4.5 introduces workflow identities, which allow the assignment of names and version numbers to workflow definitions. Multiple definitions can be deployed side by side, and running instances of a workflow can be identified by the definition they are using. This allows new workflow definitions to be deployed and used by new instances while old instances run to completion using an older definition. Further, a dynamic update feature allows existing instances to convert to a later workflow definition, provided the developer defines how the conversion should be handled.

Partial trust hosting. Previously, workflow code would have access to all permissions available to the host application, but in WF 4.5, workflows can run in a partially trusted AppDomain, limiting their capabilities to work with the system. Partial trust can reduce the security risk of using workflows obtained from third parties and can make using workflows safer in hosted multitenant deployments.

Better performance. VB expression support has been modified to deliver better runtime performance, which will improve the efficiency of workflows implemented with such expressions by upgrading to WF 4.5 without rewriting code.

WCF 4.5 Eases Configuration, Adds Communications Options

WCF provides developers with a message-oriented API that can be used to communicate over local networks or across the Internet using protocols such as HTTP, TCP, and Microsoft Message Queuing (MSMQ), reducing the amount of code and time required to integrate applications and enabling the implementation of service-oriented architectures.

The power of WCF is its ability to decouple a Web service's internal logic from the protocols used to send and receive messages, allowing either to be modified without affecting the other. The Web service logic is contained in the source code, while the communications protocol information is contained in a separate configuration file. This allows developers to create business logic and IT administrators to determine the best way to access that logic. The model also allows Microsoft to focus development on a single infrastructure and tool set that handles multiple messaging protocols, rather than developing separate solutions for each protocol.

WCF 4.5 aims to reduce configuration complexity and developer effort while improving performance and adding new communications options with enhancements that include the following:

Configuration file simplification. WCF uses XML-based configuration files to separate connection protocol information from code, but these files can be tedious to edit. Properties set to default values can be excluded in WCF 4.5 configuration files, shortening the files and reducing the complexity of working with them. Also, the VS XML editor now provides tooltips when working with a WCF configuration file to help developers understand elements and properties without opening separate documentation.

Asynchronous methods. .NET 4.5 has new elements that simplify the development effort required to write applications that perform tasks in parallel. Methods can be called asynchronously (so they run in a separate thread while the calling code path continues) with much less coding overhead than previously. WCF 4.5 supports methods that take advantage of the new .NET 4.5 asynchronous capabilities, helping developers create better performing WCF applications.

Portable libraries. A portable .NET Framework class library can run on different platforms such as Windows 8, Windows Phone 8, and the Windows Store, eliminating the need to write multiple versions of code for tasks that run the same way on each platform. WCF 4.5 code (with some exceptions) can be used in portable class libraries, so an application's WCF code doesn't have to be rewritten for each platform.

Better message streaming. WCF 4.5 offers improved performance when messages are streamed by using asynchronous streaming, which allows process threads to be closed and reused while waiting on a response (previously, threads would hold system resources while waiting for a response). Also, performance is improved when messages are streamed by a service hosted in IIS, since ASP.NET will now send the message to WCF before the entire message is received (previously, ASP.NET would wait until the full message was received and buffered). This reduces memory usage and enables WCF to respond more quickly.

UDP and WebSocket bindings. WCF uses bindings to define how services communicate. Several binding types, such as HTTP, TCP, and MSMQ are included with WCF, and developers can define custom binding types for other communication mechanisms. WCF 4.5 adds bindings for UDP (which supports message broadcasting to multiple clients without soliciting a response) and WebSocket (which provides two-way TCP communication using HTTP or HTTPS ports with reduced overhead and better performance than HTTP).

 



European WCF 4.5 Hosting - Amsterdam :: WCF 4.5 ChannelFactory Caching

clock October 19, 2012 10:59 by author Scott

Today I explain what ChannelFactory caching in the WCF 4.5 framework is. With the help of this new feature in .NET we can cache the service instance. Microsoft has introduced a new property for the ClientBase<T> class; the property name is CacheSetting. We can set the cachesetting with the help of the CacheSetting enum.

Here are the values of the Enum:

Name

Description

System.ServiceModel.CacheSetting.AlwaysOn

All instances of Client will use the same channel factory.

System.ServiceModel.CacheSetting.AlwaysOff

All instances of the Client would use different channel factories. This is useful when each endpoint has different security requirements and it makes no sense to cache.

System.ServiceModel.CacheSetting.Default

All instances of Client would use the same channel factory except instance #4. Instance #4 would use a channel factory that is created specifically for its use. This setting would work for scenarios where a particular endpoint needs different security settings from the other endpoints of the same ChannelFactory type (in this case IService).


Here is sample code for the Default CacheSetting:


class Program
    {
        static void Main(string[] args)
        {
             ClientBase<IService1>.CacheSetting = System.ServiceModel.CacheSetting.Default;
             using (ServiceReference1.Service1Client client = new Service1Client()) {


             }
        }
}


Here is sample code for the AlwaysOn CacheSetting:


static void Main(string[] args)

{

  ClientBase<IService1>.CacheSetting = System.ServiceModel.CacheSetting.AlwaysOn;

using (ServiceReference1.Service1Client client = new Service1Client()) {

   }
}


Here is sample code for the AlwaysOff CacheSetting:

static void Main(string[] args)
{
   ClientBase<IService1>.CacheSetting = System.ServiceModel.CacheSetting.AlwaysOff;


   using (ServiceReference1.Service1Client client = new Service1Client()) {

   }
}

 

 



European WCF 4.5 Hosting - Amsterdam :: Implementing WebSockets in WCF 4.5

clock October 15, 2012 06:59 by author Scott

Web Services have one great virtue: they're completely interoperable. They also have one great failing: in order to be interoperable, Web Services use a set of technologies that are guaranteed to give you, at best, adequate performance. Fortunately, WCF 4.5 has a solution: support for WebSockets.

Ever since Web Services appeared, developers have been trying to make them run faster. REST and JSON can be seen as a way of speeding things up by reducing the overhead in the messaging format used by Web Services. However, even with REST and JSON you're still moving and parsing text, which is the bulkiest and slowest data transfer mechanism; you'd get better performance if you could move binary data around. And REST and JSON don't tackle another reason for why Web Services give poor performance: HTTP, the network protocol used by Web Services. There are slower protocols than HTTP around, but no one is using them.


But performance isn't the only issue that using HTTP creates: HTTP in Web Services is tied to a request/response cycle. The reason Ajax applications make all their requests asynchronously is because if you call a service that takes a long time to complete, your request has to wait for that response before you can get your result.


On top of that, if your service has something else to tell your client after that initial response (an ongoing set of updates, for instance), then either your client has to make repeated polling calls to the service to get the result (another performance burden) or, in a non-Ajax application, you have to set up a complementary Web Service that the service can call with the updates.


A far better arrangement would be for the client to submit its request in a "fire and forget" kind of arrangement and then for the service to call back to the client when it has the data (and keep calling back if there are updates to send).


WebSockets addresses all of those issues, while still being an industry standard and therefore interoperable (confusions in vendor's implementations of the standard may interfere). In fact, your browser probably already supports WebSockets.


For most processing, WebSockets uses TCP to communicate, giving you the benefit of a faster protocol. WebSockets also supports sending both binary (for speed) and text (for interoperability). But in many ways, the best part of WebSockets is that it supports two-way communication: The client can call the service just to open communication; and after that, the service can call the client whenever it has information to share. And WCF 4.5 provides support for WebSockets.


So in the next few columns, I'm going to look at WebSockets in WCF 4.5. I'll look at the two ways you can implement WebSockets (one complicated and flexible, one simpler and less flexible) and create client a JavaScript client. Along the way I'll also discuss some of the issues you should consider in creating a WebSocket application.


Configuring the Server

One warning: You may not be able to use the code in this series, yet. As I write this (April 2012), WebSockets is only supported on Windows 8 (I worked on the 64-bit
beta ISO for Windows 8 Server); even then, you'll need to configure Windows 8 to support WebSockets.

To configure Windows 8, in Server Manager, from the Manage menu, run the Add Server Roles and Features wizard. In the Wizard, you'll need to add the Web Server (IIS) role. After that, under Features, select ASP.NET 4.5 (if it isn't already selected) and, under Web Services, select HTTP Activation. Finally, under Web Services (IIS)/Role Services, select WebSockets. After finishinb the Wizard, select Local Server and set IIS Enhanced Security Configuration to off.


To work with WCF 4.5, you'll need
Visual Studio 11 (again, in beta, as I write this). The first time you run it, Visual Studio 11 will probably offer to download an update; if so, take the update (I took the update and I won't guarantee that the following code will work without it).

Second warning: This may be a frustrating set of columns if you're reading them as soon as I post them. I've got a fair amount of ground to cover so, in this column, I'll only be setting up to write the code that a WebSocket service requires. But hang tough; the next column will have the code and subsequent columns will show you how to build the clients and provide an alternative way to build a WebSocket service.


Building the Service

I did my testing with a WCF Service Application Project. To take advantage of IIS's support for WebSockets that I'd just finished configuring, I went to the Web tab of my Project Properties and unchecked the Use IIS Express option so that I was testing with the "real" IIS.


Once you've set up your server and project, the first step in creating your WebSocket service is to define two interfaces: one with a single method that accepts requests from clients and another interface with a single method to send results.


For the first interface, I'll define a method that accepts an Order Id (I call the method OrderStatusById method and the interface IRequestOrderStatusUpdates). In the ServiceContract attribute on the interface that accepts requests, you need to use the attribute's CallbackContract to specify the second interface (the one with the method used to send data back to the client is ISendOrderStatus in this example). The method must accept a Message as its only input parameter and the method's OperationContract attribute must set its IsOneWay property to True and its Action property to an asterisk.


The result for my Order status example looks like this:


<ServiceContract(CallbackContract:=GetType(ISendOrderStatus))>
Public Interface IRequestOrderStatusUpdate

  <OperationContract(IsOneWay:=True, Action:="*")>
  Sub OrderStatusByID(OrderStatusMessage  As Channels.Message)

End Interface


The definition for the return method is similar, except that you don't need any special specifications for the ServiceContract attribute. I've called my method SendOrderStatus:


<ServiceContract()>
Public Interface ISendOrderStatus

  <OperationContract(IsOneWay:=True, Action:="*")>
  Sub SendOrderStatus(OrderStatusMessage  As Channels.Message)

End Interface


At this point you're ready to write the code for these methods, which I'll look at in my next column (the column after that will look at building a client).

 



European WCF 4.5 Hosting - Amsterdam :: Beyond Configuring Web Services in WCF 4.5

clock April 27, 2012 10:34 by author Scott

In previous post, you can see how easy it was to add a basic HTTP Web Service to a Web site in the beta of the .NET Framework 4.5 through code: Just add a shared/static method called Configure to your service and put some code in it to configure the ServiceConfiguration object passed to the method. In fact, because of the defaults that WCF 4.5 takes for a WCF service in a Web Site you don’t really need to add any code at all. In my example I did add some code to explicitly enable my service as a basic HTTP Web Service. I also chose to configure the service to return a contract and verbose error messages (both of which are turned off by default) to support testing.

But the power of WCF is in providing multiple ways of accessing the same code–as a basic Web Service or as a high performance TCP-based service. Adding TCP access requires a change in the project type: Testing a TCP-based service from Visual Studio is awkward (at best). Instead, you’ll want to create a WCF Service library where you service is hosted by WAS rather than IIS. While that makes testing your TCP access is simplified, the defaults don’t give you a service automatically and you’ll need to use a few more lines of code.


After creating your WCF Service library project add a new WCF Service to it, giving the service some meaningful name (I used “CustomerService”). Then, to demonstrate the power of configuring by code, go to your app.config file and delete the entire system.model element. You’re now ready to control your service from code.


These two lines of code make your service available as a Web Service and as a TCP-based service (which will have orders-of-magnitude better performance than the HTTP-based Web service):


PublicSharedSub Configure(sc AsServiceConfiguration)

sc.EnableProtocol(
New BasicHttpBinding
sc.EnableProtocol(
New NetTcpBinding)

While that (in theory) makes your service accessible, it doesn’t make the information about the service (the metadata) available. As a result, you won’t be able to either use Visual Studio’s WCF Test Client or be able add a service reference for your service to another project by using the Add Service Reference dialog’s Discover button. To enable the metadata you use the same code that I had in my previous post but with one extra line of code that specifies the address where the metadata is available. In that line you create a System.URI object specifying the address (the address must reference your computer name but the port and service name are up to you) and use it to set the HttpGetUrl property:


Dim behavior As New Description.ServiceMetadataBehavior

behavior.HttpGetEnabled =
True
behavior.HttpGetUrl = New System.Uri("http://localhost:1868/Customers")

sc.Description.Behaviors.Add(behavior)

You also need to add endpoints for HTTP and TCP access to your service. For that, you use the AddServiceEndpoint method on the ServiceConfiguration object passed to your Configure method. The first parameter to the AddServiceEndpoint is the type of the interface that your service implements (“ICustomers” in this example), the second parameter is the binding class for the endpoint, and the final parameter is the address itself (make sure that you use different addresses for each endpoint):


sc.AddServiceEndpoint(GetType(ICustomerService),

         New BasicHttpBinding(),
         "http://localhost:1868/Customers")
sc.AddServiceEndpoint(GetType(ICustomer),

         New NetTcpBinding(),  
         "net.tcp://localhost:1867/Customers")

There is an annoyance when you go to test your service: In a Service Library, in the absence of any entries in the config file, the test client can’t retrieve the information about the service. You’ll first get a dialog that the “WCF Service Host cannot find any service metadata”–just click the No button to continue. When the Test Client appears, it won’t display any services. You’ll need to go to the Test Client’s File menu and select Add Service to display the Add Service dialog box. In the box, enter the URL you used to set the HttpGetUrl property followed by “?wsdl” (e.g. “http://localhost:1868/Customers?wsdl”—and make sure you type the URL exactly the way it appears in your code). When you click the OK button, the Test Client will finally grab the service information and you’ll be able to test your service. The good news here is that, once you enter the URL with ?wsdl successfully, you won’t have to enter it again (you will still need to go through all the dialogs, though).

And there you go: With less than a dozen lines of code you’ve configured a service as both a basic HTTP service and TCP-based service. Adding additional access methods (e.g. named pipes, advanced web services, https) should just consist of enabling the protocol with the EnableProtocol method and adding a compatible endpoint.

 



European WCF 4.5 Hosting - Amsterdam :: One Line of Code to Configure WCF 4.5

clock April 10, 2012 11:47 by author Scott

The WCF 4.5 beta simplifies configuring WCF, provides better support for code-based configuration, and makes it easier to do code-based configuration in Web sites. Don’t get me wrong: I like the WCF configuration files but, I gather, I may be in a minority. Many developers prefer to configure their WCF services from code where possible. Unfortunately, one of the places where that isn’t possible is the most common place to host WCF services: in a Web application (well, I’m told it was possible but only in the sense that it’s possible to remove your own appendix).

WCF 4.5 (at least, in the beta) provides a simple solution: Add a static/shared method called Configure to your service class and fill it with the code required to configure your service. WCF will call that Configure method at the appropriate moment and pass the method an instance of the ServiceHost class. In your Configure method, you can work with that ServiceHost to configure your service.


What’s especially impressive is how simple it is. The default settings alone mean that if you add an svc file to your Web site then you have a Web Service. You can make that explicit, however, with a single line of code. This example makes the service containing this method available as a Web Service with no WCF-related tags required in the config file at all:


Public Shared Sub Configure(sc AsServiceConfiguration)

 sc.EnableProtocol(NewBasicHttpBinding())
End Sub

You can configure these services by instantiating behavior classes, configuring them, and adding them to the ServiceConfiguration’s Description property’s Behaviors collection. That’s a good thing because, while my previous example was all the code you need (in fact one more line than you needed), it’s probably not all the code you want, for two reasons.


Configuring the Service

First, with just that code you won’t be able to retrieve the WSDL contract for this service (what WCF refers to as service’s “metadata”) so you won’t be able to use Visual Studio’s WCF test client (you also won’t be able to use the Discover button in Visual Studio’s Add Service Reference dialog). For testing purposes, and until you can save to a separate file the WSDL contract that you can give to the developers building the clients/consumers for this service, you’ll want to configure your service to return a WSDL contract. To tell your service to make its metadata available you add code like the following to your Configure method. This code creates a ServiceMetadataBehavior object, sets its HttpGetEnabled property to True (that actually turns on the feature), and add the configured behavior to the Behaviors collection:

Dim behavior As New Description.ServiceMetadataBehavior
behavior.HttpGetEnabled = True
sc.Description.Behaviors.Add(behavior)


Second, by default, WCF services don’t return a lot of information in their exception messages. That’s a good thing: While that information is very useful in debugging, it probably isn’t something you want to share with the general public. However, in testing, you probably do want that those chattier error messages and you can enable the with this code in the Configure method:

Dim debugBehavior As New Description.ServiceDebugBehavior
debugBehavior.IncludeExceptionDetailInFaults = True
sc.Description.Behaviors.Add(debugBehavior)

But both of these changes highlight an issue with code-based configuration. In production, you probably don’t want your service freely giving up its contract to whoever asks for it. Instead you probably want to control access to your service’s contracts so that you have some idea who’s using your service and can contact those users when you’re making changes to your service. And you certainly don’t want to send out those verbose error messages from your production system. So, before moving your service to production you’re going to want to change the values used in this code.

The problem is that, with the code I’ve used here, there’s no simple way to inspect the assembly you’re deploying to production to determine if the settings are correct: the code is compiled and is unreadable. One of the nice features of the config files is that you could inspect them (and even change them) with Notepad. The right answer is probably to move settings that will change from one installation to another (e.g. test and production) into your AppSettings where you’ll still have visibility to them.

Please visit our site at
http://www.hostforlife.eu if you need Silverlight 5 WCF RIA hosting. Starts from only €2.45/month.

 



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in