Learning WCF

Michele Bustamante

Mentioned 32

Provides information and examples on using Windows Communication Foundation to build service-oriented applications.

More on Amazon.com

Mentioned in questions and answers.

Might seem like a silly question, but everything in WCF seems a lot more complicated than in asmx, how can I increase the timeout of an svc service?

Here is what I have so far:

<bindings>
      <basicHttpBinding>
        <binding name="IncreasedTimeout" 
          openTimeout="12:00:00" 
          receiveTimeout="12:00:00" closeTimeout="12:00:00"
          sendTimeout="12:00:00">
        </binding>
      </basicHttpBinding>
</bindings>

And then my endpoint gets mapped like this:

<endpoint address="" 
  binding="basicHttpBinding" bindingConfiguration="IncreasedTimeout"
             contract="ServiceLibrary.IDownloads">
             <identity>
                <dns value="localhost" />
             </identity>
          </endpoint>

The exact error I am getting:

The request channel timed out while waiting for a reply after 00:00:59.9990000. Increase the timeout value passed to the call to Request or increase the SendTimeout value on the Binding. The time allotted to this operation may have been a portion of a longer timeout.

In the WCF Test Client, there is a config icon that contains the run time configuration of my service:

As you can see its not the same values as I've set for it? What am I doing wrong?

<bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IDownloads" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                    useDefaultWebProxy="true">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <security mode="None">
                        <transport clientCredentialType="None" proxyCredentialType="None"
                            realm="">
                            <extendedProtectionPolicy policyEnforcement="Never" />
                        </transport>
                        <message clientCredentialType="UserName" algorithmSuite="Default" />
                    </security>
                </binding>
            </basicHttpBinding>
        </bindings>

In your binding configuration, there are four timeout values you can tweak:

<bindings>
  <basicHttpBinding>
    <binding name="IncreasedTimeout"
             sendTimeout="00:25:00">
    </binding>
  </basicHttpBinding>

The most important is the sendTimeout, which says how long the client will wait for a response from your WCF service. You can specify hours:minutes:seconds in your settings - in my sample, I set the timeout to 25 minutes.

The openTimeout as the name implies is the amount of time you're willing to wait when you open the connection to your WCF service. Similarly, the closeTimeout is the amount of time when you close the connection (dispose the client proxy) that you'll wait before an exception is thrown.

The receiveTimeout is a bit like a mirror for the sendTimeout - while the send timeout is the amount of time you'll wait for a response from the server, the receiveTimeout is the amount of time you'll give you client to receive and process the response from the server.

In case you're send back and forth "normal" messages, both can be pretty short - especially the receiveTimeout, since receiving a SOAP message, decrypting, checking and deserializing it should take almost no time. The story is different with streaming - in that case, you might need more time on the client to actually complete the "download" of the stream you get back from the server.

There's also openTimeout, receiveTimeout, and closeTimeout. The MSDN docs on binding gives you more information on what these are for.

To get a serious grip on all the intricasies of WCF, I would strongly recommend you purchase the "Learning WCF" book by Michele Leroux Bustamante:

Learning WCF

and you also spend some time watching her 15-part "WCF Top to Bottom" screencast series - highly recommended!

For more advanced topics, you should definitely check out Juwal Lovy's Programming WCF Services book.

Programming WCF

I'm starting to work with my model almost exclusively in WCF and wanted to get some practical approaches to versioning these services over time. Can anyone point me in the right direction?

While not an instant answer for you, I found the book Learning WCF very useful; in it there's a small section on versioning (which is similar to Craig McMurtry's advice posted by Espo). If you're looking for a general intro book, it's very good. Her website has lots of good stuff too: Das Blonde

Edit: No sure why her site isn't responding; it's been a while since I've visited, so maybe she shut it down. No sure.

For those just starting to learn WCF, what are the major/basic things I should look at and learn first?

What concepts would you recommend to learn first, to be productive in WCF?

What resources/articles/training/books would you recommend to someone learning WCF?

In C#, for example, one can learn LINQ at a later stage. Along similar lines, in WCF also there should be basics to learn first, and then later invest time in advanced features to enhance productivity.

The book I always recommend to get up and running in WCF quickly is Learning WCF by Michele Leroux Bustamante. She covers all the necessary topics, and in a very understandable and approachable way. This will teach you everything - basics, intermediate topics, security, transaction control and so forth - that you need to know to write high quality, useful WCF services.

alt text

Besides that book, I also really learned a lot from these two one-hour screencasts on WCF:

Don't miss this GREAT Book:

alt text
Ron Jacobs, (Senior Technical Evangelist for WCF at Microsoft) wrote on its forewords that "The best testament to this is to wander the halls of building 42 in Redmond (where the WCF team works); in many of the offices you will see Programming WCF Services on the shelf."
So from that I gathered that the team at Microsoft first wrote WCF and then they bought this book to understand what they actually have written!!

But seriously, I strongly recommend this book not to only understand WCF but also to learn how Juval Löwy - one of the most prominent distributed systems experts in the world today - thinks and looks at WCF and the concept of designing Enterprise SOA applications in general.

Just wondering what are the most useful resources you've seen for learning about WCF?

I've created a few prototypes and understand the basics, however I'm starting a fairly high-profile project and would like to fill in as many gaps in my knowledge as possible.

Books:

Learning WCF: A Hands-on Guide by Michele Bustamante - very nice kick-off book with step-by-step tutorials. Michelle also has a series of webcasts published on MSDN.

Programming WCF Services by Juval Lowy - more systematic approach, for experienced web developers.

IDesign WCF Coding Standard

WCF Security Guidance from Microsoft P&P

Websites:

Getting Started Tutorial on MSDN

and offcourse TheBestProgrammersQandASiteEver :-)

I really liked Inside Windows Communication Foundation. It tells you a few things that most other books don't:

  1. What the design goals of WCF are
  2. Different messaging and coordination patterns and what support WCF has for them
  3. The organization of WCF (Relationship between bindings, channels, etc). A few other books have this, but I found this book to have the most hands-on explanation of them - which I like.

Highly recommended.

Are there good books for learning WCF in C#? What do you recommend and why?

There's the MSDN WCF Developer Center which has everything from beginner's tutorials to articles and sample code.

Also, check out the screen cast library up on MSDN for some really useful, 10-15 minute chunks of information on just about any topic related to WCF you might be interested in.

The book I always recommend to get up and running in WCF quickly is Learning WCF by Michele Leroux Bustamante. She covers all the necessary topics, and in a very understandable and approachable way. This will teach you everything - basics, intermediate topics, security, transaction control and so forth - that you need to know to write high quality, useful WCF services.

Learning WCF

The more advanced topics and more in-depth look at WCF will be covered by Programming WCF Services by Juval Lowy. He really dives into all technical details and topics and presents "the bible" for WCF programming.

Programming WCF Services

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 = "MyUsername";
        _serviceClient.ClientCredentials.UserName.Password = "MyPassword";

        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...

You're on the right track, I'd say ;-)

Basically, creating the WCF client proxy is a two-step process:

  • create the channel factory
  • from the channel factory, create the actual channel

Step #1 is quite "expensive" in terms of time and effort needed - so it's definitely a good idea to do that once and then cache the instance of ProjectWcfServiceFactory somewhere in your code.

Step #2 is actually pretty lightweight, and since a channel between a client and a service can fall into a "faulted state" when an exception happens on the server (and then needs to be re-created from scratch), caching the actual channel per se is less desirable.

So the commonly accepted best practice would be:

  • create the ChannelFactory<T> (in your case: ProjectWcfServiceFactory) once and cache it for as long as possible; do that heavy lifting only once

  • create the actual Channel (here: IProjectWcfService) as needed, before every call. That way, you don't have to worry about checking its state and recreating it as needed

UPDATE: "what about closing the channel?" asks Burt ;-) Good point!!

The acccepted best practice for this is to wrap your service call in a try....catch....finally block. The tricky part is: upon disposing of the channel, things can do wrong, too, so you could get an exception - that's why wrapping it in a using(....) block isn't sufficient.

So basically you have:

IProjectWcfService client = ChannelFactory.CreateChannel();
try
{
   client.MakeYourCall();
}
catch(CommunicationException ce)
{
    // do any exception handling of your own
}
finally
{
    ICommunicationObject comObj = ((ICommunicationObject)client);

    if(comObj.State == CommunicationState.Faulted)
    {
       comObj.Abort();
    }   
    else
    {
       comObj.Close();
    }
}

And of course, you could definitely nicely wrap this into a method or an extension method or something in order not to have to type this out every time you make a service call.

UPDATE:

The book I always recommend to get up and running in WCF quickly is Learning WCF by Michele Leroux Bustamante. She covers all the necessary topics, and in a very understandable and approachable way. This will teach you everything - basics, intermediate topics, security, transaction control and so forth - that you need to know to write high quality, useful WCF services.

Learning WCF

The more advanced topics and more in-depth look at WCF will be covered by Programming WCF Services by Juval Lowy. He really dives into all technical details and topics and presents "the bible" for WCF programming.

Programming WCF Services

Other posts are outdated. Please don't close my post or vote it down.

Could anyone recommend a good quality WCF book for beginner/intermediate/expert?

Belows are the books I read, but I feel that the first book is good for the first few chapters.

The second book is really good. But it does NOT have separated code example for most of the example mentioned in the book. Thus, it is difficult to test them individually. It only shows the main code on the book, and combine all code in one solution.

Essential Windows Communication Foundation (WCF): For .NET Framework 3.5

Programming WCF Services: Mastering WCF and the Azure AppFabric Service Bus Juval Lowy

Edit

Is there anyone who created the code example from the second book (Juval Lowy), and would like to share it.

Or

I need to wait for the second version for this book: Learning WCF: A Hands-on Guide

I don't think she has updated it for WCF 4, but Michele Bustamante's Learning WCF is a great beginner's book. She has step by step exercises and explanations and writing style is a tad easier to read imo.

My first few attempts at creating a self hosted service. Trying to make something up which will accept a query string and return some text but have have a few issues:

  • All the documentation talks about endpoints being created automatically for each base address if they are not found in a config file. This doesn't seem to be the case for me, I get the "Service has zero application endpoints..." exception. Manually specifying a base endpoint as below seems to resolve this:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    using System.ServiceModel.Description;
    
    namespace TestService
    {
        [ServiceContract]
        public interface IHelloWorldService
        {
           [OperationContract]
           string SayHello(string name);
        }
    
        public class HelloWorldService : IHelloWorldService
        {
            public string SayHello(string name)
            {
               return string.Format("Hello, {0}", name);
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                string baseaddr = "http://localhost:8080/HelloWorldService/";
                Uri baseAddress = new Uri(baseaddr);
    
                // Create the ServiceHost.
                using (ServiceHost host = new ServiceHost(typeof(HelloWorldService), baseAddress))
                {
                    // Enable metadata publishing.
                    ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                    smb.HttpGetEnabled = true;
                    smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                    host.Description.Behaviors.Add(smb);
    
                    host.AddServiceEndpoint(typeof(IHelloWorldService), new BasicHttpBinding(), baseaddr);
                    host.AddServiceEndpoint(typeof(IHelloWorldService), new BasicHttpBinding(), baseaddr + "SayHello");
    
                    //for some reason a default endpoint does not get created here
                    host.Open();
    
                    Console.WriteLine("The service is ready at {0}", baseAddress);
                    Console.WriteLine("Press <Enter> to stop the service.");
                    Console.ReadLine();
    
                    // Close the ServiceHost.
                    host.Close();
                }
             }
         }
    }
    
  • How would I go about setting this up to return the value of name in SayHello(string name) when requested thusly: localhost:8080/HelloWorldService/SayHello?name=kyle

I'm trying to walk before running, but this just seems like crawling...

As for books - here's my recommendation: the book I always recommend to get up and running in WCF quickly is Learning WCF by Michele Leroux Bustamante. She covers all the necessary topics, and in a very understandable and approachable way. This will teach you everything - basics, intermediate topics, security, transaction control and so forth - that you need to know to write high quality, useful WCF services.

Learning WCF

The more advanced topics and more in-depth look at WCF will be covered by Programming WCF Services by Juval Lowy. He really dives into all technical details and topics and presents "the bible" for WCF programming.

Programming WCF Services

Good and easy books/tutorials to learn WCF latest stuff

The best book for beginner to intermediate level has to be:

Michele Leroux Bustamante, Learning WCF

Learning WCF

For more intermediate to advanced topics, Juval Lowy's Programming WCF Services is definitely THE book to check out.

Programming WCF Services

As for online tutorial - I don't really know many good ones. Lots of people blog about WCF, including Michele Leroux Bustamante.

Check out some of those links here for tutorials on WCF:

Marc

As the title allready explains I want to secure my webservice. I've read that you can do this using an soap authentication header, but then the username en password are passed as plain text.

I was wondering what I should do to secure my webservice? Examples would be great.

I have an example of a company we work with that has 2 webservices. One to do the security and one to get the needed data but I don't have their side of the code the system looks great though:

bool loginSuccessFull = false;

/// knooppunt
string loginID = ConfigurationManager.AppSettings["WebServiceLogin"];
string password = ConfigurationManager.AppSettings["WebServicePass"];


//A. The m_SecurityService object is created and initialised
Security securityService = new Security();
securityService.CookieContainer = new System.Net.CookieContainer();


string challenge = securityService.InitializeLogin(loginID);
string pwd = password;
string response = pwd + challenge;


System.Security.Cryptography.SHA1CryptoServiceProvider SHA1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
SHA1.Initialize();
byte[] hash = SHA1.ComputeHash(System.Text.Encoding.Default.GetBytes(response));

System.Text.StringBuilder builder = new System.Text.StringBuilder();
foreach (byte b in hash)
    builder.Append(b.ToString("x2"));

//2. A login is done with the m_SecurityService object
if (securityService.Login(builder.ToString()))
{
    string ssoToken = Request.QueryString["SSOTOKEN"];
    string ssoID = Request.QueryString["SSOID"];
    if (!String.IsNullOrEmpty(ssoToken) && !String.IsNullOrEmpty(ssoID))
    {
        // Check with webserice if the token is valid.
        Knooppunt.SSO.GenericSSO sso = new Knooppunt.SSO.GenericSSO();
        sso.CookieContainer = securityService.CookieContainer;
        try
        {
            if (sso.validateSSOToken(Convert.ToInt32(ssoID), ssoToken))
            {
                loginSuccessFull = true;
                FormsAuthentication.RedirectFromLoginPage("default user", false);
            }
        }
        catch
        { }
    }
}

If it truly is a webservice, you should be using Windows Communication Foundation to generate the proxy and make the call. It makes a lot of this code much, much easier.

Honestly, it looks like the package that is used to connect to the web service that you are using (SSO?) is pretty non-standard, and does nothing more than derive from HttpWebRequest, which is VERY low-level, and too complex to use.

If you are going to secure your own web service (and you are exposing it over an HTTP channel), the easiest way is to get a digital certificate for your host and then use basic HTTP authentication over HTTPS.

You could also use other aspects of the WS-Security specifications (e.g. encoding the message, etc, etc) to secure your service.

Note that WCF supports all of these options, so you don't have to do any of this coding out of the box, and you can host it in IIS as well.

A good beginners reference to WCF is Michelle Bustamante's "Learning WCF: A Hands-On Guide".

After that, for more advanced WCF content (especially if you want to learn about concepts revolving around security in WCF and WS-* in general) I highly recommend "Programming WCF Services" by Juval Lowy.

I have ASDService.svc:

 namespace StatusSimulator
 {
      [ServiceContract]
      public class ASDService
      {
           [OperationContract]
           public void DoWork()
      }

      [ServiceContract]
      public interface IScheduleTables
      {
            [OperatonContract]
            string getTable(string l, int r, int c)
            [OperatonContract]
            string getTable(string test)
            [OperatonContract]
            string createTable(List<string> lst, int r, int bal)
      }

      public class ScheduleTables:IScheduleTables
      {
               //Interface Implementation
      }
 }

web.config:

  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="NewBehavior0">
          <serviceMetadata httpGetEnabled="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <basicHttpBinding>
        <binding name="NewBinding0" />
      </basicHttpBinding>
    </bindings>
    <services>
      <service behaviorConfiguration="NewBehavior0" name="StatusSimulator.ASDService">
        <endpoint address="http://localhost:2405/ASDService.svc" binding="basicHttpBinding"
          bindingConfiguration="NewBinding0" name="ASDEndpoint" contract="StatusSimulator.ASDService" />
        <endpoint address="http://localhost:2405/ASDService.svc" binding ="basicHttpBinding"
          bindingConfiguration="NewBinding0" name="ScheduleTableEndPoint" contract="StatusSimulator.IScheduleTables" />
      </service>
    </services>
  </system.serviceModel>

Absolutely nothing I've tried will expose the interface to the service. The only thing I can see is ASDService.DoWork. How does one implement other classes or interfaces inside a pre-existing service?

I've tried two services in the config, multiple endpoints. I've tried nesting the interface inside ASDService. I've read more tutorials and posts on here than I care to mention. As it sits I am getting the error

The contract name 'StatusSimulator.IScheduleTables' could not be found in the list of contracts implemented by the service 'ASDService'.

I'm baffled, out of ideas and am going to need professional help if this continues.

You shouldn't be mixing a service contract (defined on the concrete class ADsService) with the implementation of another service contract (IScheduleTables).

I would recommend that you have two distinct service contracts as interfaces (IASDService and IScheduleTables), and then one concrete class that implements both interfaces - something like this:

namespace StatusSimulator
{
      [ServiceContract]
      public interface IASDService
      {
           [OperationContract]
           public void DoWork()
      }

      [ServiceContract]
      public interface IScheduleTables
      {
            [OperatonContract]
            string getTable(string l, int r, int c)
            [OperatonContract]
            string getTable(string test)
            [OperatonContract]
            string createTable(List<string> lst, int r, int bal)
      }

      public class ServiceImplementation : IADSService, IScheduleTables
      {
         // implement both interfaces here...
      }
 }

As for resources: I would use these for starters:

Then there's a couple of good books - most notably Learning WCF by Michele Leroux Bustamante. She covers all the necessary topics, and in a very understandable and approachable way. This will teach you everything - basics, intermediate topics, security, transaction control and so forth - that you need to know to write high quality, useful WCF services.

I'm working on a software solution to for a group of applications running on the same server.

The applications are loosely related, and share an event log. The problem that we are running into is performance, with each application making calls to the database every time they need to log an event.

What I'm trying to do is decouple the entire process by removing the applications direct calls to the database, and routing them through a service running on the machine whos sole purpose is processing events from the multiple applications on the machine.

Event Helper Service - Image

Ultimately my goal is to implement some sort of system in the "Event" Helper Object that would allow those objects to communicate directly with the "Event" Service.

My first instinct was to use your typical "event", but it would appear from the research that I've done that it is not possible to invoke an event in one process to be handled in another process.

As a part of my research I came across Listen for events in another application and C# Win32 messaging with SendMessage.

Sendmessage looks like a promising solution, but I wanted to be sure so I spoke with one of my colleagues who was close to the project (the original developer who was moved on to a new project before the completion of this one) and he imparted some additional information as to the situation. They had apparently attmped to use WCF and build it as a web service. This probably would have worked except for the location and security level of the server itself.

He believes it MAY be possible to implement a WCF system at the OS level without having to use it in a web service environment.

My question is... "Is using WCF possible at the OS level?" and "Which of the options listed would be the most efficent under the scenario?" Keeping in mind that this MUST be decoupled and the applications cannot have any interaction with the event log in the database itself.

WCF Update:

So I started putting something together and this is what I came up with..

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace SelfHost
{
    [ServiceContract]
    public interface ISelfHostingService
    {
        [OperationContract]
        string SelfHost(string name);
    }
    public class SelfHostingService : ISelfHostingService
    {
        public string SelfHost(string name)
        {
            return string.Format("Hello, {0}", name);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8080/SelfHost");
            ServiceHost host = new ServiceHost(typeof(SelfHostingService), baseAddress);
            host.AddServiceEndpoint(typeof(SelfHost.ISelfHostingService), new BasicHttpBinding(), baseAddress);
                host.Open();
                Console.WriteLine("The service is ready at {0}", baseAddress);
                Console.WriteLine("Press <Enter> to stop the service.");
                Console.ReadLine();
        }
    }
}

But there is a problem. This line:

Uri baseAddress = new Uri("http://localhost:8080/SelfHost");

I guarantee that the server will not allow the service to register that local address (its been tried already and it was a flop).

So my new question is... "Is there a way around that that does not involve changing configuration settings on the server itself?"

MSMQ Update:

This is deffinately an option but... [pregnant pause] We do use the message queue for other pieces of functionality. My only hesitation is the overhead. I'd rather that it was completely decoupled I'm looking for an application to application solution. I'd rather that the service was "listening" instead of going to get.

Finale

I did a lot more research and I've decided that using WCF is in my best interest. As a part of the windows service I plan on adding an app.config for the event logging service and then configuring the service to use named pipes over localhost.

thanks for all the help

Follow-Up

For anyone who might be interested. This works beautifuly. The net.pipe is active and I am able to create events and send them to the service from multiple apps with little or no processing time.

The wcf service is encased in a very simple windows service that simply opens the service pipe. on the client side i was able to discover and implement the service easily. All i have to do is make a call to the client class and it shows my events in real time in the database.

Thanks again.

I think you want a self-hosted WCF application. This is a great book on WCF and chapter four talks about self-hosting.

I like my learning projects to also be useful. If not to me then to somebody around me.

What are some good projects I could code using WCF (to learn it) that I will be able to put to use for myself, or for someone or some organization I may know?

What I am not interested in tutorials, or books on how to learn it.

Thanks.

-----Recommendation:
Hate to say it, but I used to do the "kill two birds with one stone". You'll find that it's too hard to do. You'll spend countless hours learning the technology and making a lot of mistakes/lessons learned. You may end up with a useful app...but it wont be as "pretty" as you'd like it to be and you'll end up wishing you could rewrite it. Especially if you are trying to learn WCF, there is so much to the technology....either way.....here is an app:

-----Application
I did a WCF chat application. I created a web version (thin client) and a WPF version (thick client). By doing the chat application:

-----Thin Client web app
teaches you how WCF works with ajax
teaches you how to use the BasicHttpBinding
teaches you how to host WCF in IIS
teaches you about how WCF will scale given multiple users
teaches you "pull" architectures

-----Thick Client Winforms/WPF app
teaches you how WCF works in a thick client (duh)
teaches you how to use a Duplex binding
teaches you how to host you WCF app in either a windows service, console app, or IIS7
gives you insight on security/firewall requirements when dealing with thick clients
teaches you "push" architectures
gives you insight on thread safety when dealing with OneWay calls

-----How to make it useful
It would be great if there was a "plug-able" chat application out there that I could put on my websites. You can provide it as a service to other developers.

-----Books (even though you don't want it)
Intro book:
http://www.amazon.com/Learning-WCF-Hands-Michele-Bustamante/dp/0596101627

Advanced book:
http://www.amazon.com/Programming-WCF-Services-Juval-Lowy/dp/0596521308/ref=sr_1_1?ie=UTF8&qid=1253113250&sr=1-1-fkmr0

I'm new to WCF. Let's say I have two asp.net apps, one that uses windows authentication (an intranet app), and one that uses forms authentication (an internet app). I want both of these applications to have a service reference to a physically separate machine where all my business logic will live (in WCF). So, the app is like this:

Browser --> ASP.NET --> WCF. When the call ends up in the WCF tier, I need to know the username that ASP.net obtained (User.Identity.Name).

With .NET Remoting, I created a custom principal that I stashed in the LogicalCallContext. Then with a custom remoting sink on the remoting server side, I set the current thread principal to the principal in the LogicalCallContext.

What is the correct way to do something like this with WCF? Again, my WCF service may only be called by the service account running ASP.NET, but I need to know who the call is ultimately on behalf of.

I guess you'll want to check WCF Membership provider. I posted a few months about it http://sgomez.blogspot.com/2007/12/wcf-membership-provider-sample.html follow the links and also I'd recommend the book Learning WCF by Michele LeRoux Bustamante.

Good luck! (you're gonna need it)

I'm planning to write a web service aka api for my application which was developed with .Net and SQLServer. .Net provides a simple way to create webservices by creating asmx files. But i need to know how best it can be designed or what are the best practices in creating a web service in .net or some pointers to good articles as this is my first experience in web services programming. Eventhough SF has many references to best practices in API (which are very good) i dont find much information oriented for .net webservices.

Update: After dariom's reply i would like to mention that i'm doing it in .net 2.0

If you're using .NET 3.0 or later I would encourage you to consider implementing your service using WCF.

The learning curve is steeper, but you'll benefit from the flexibility and features that WCF offers. With WCF you can make your service compatible with ASMX services (regular .NET web services) so other applications and other languages can consume the service as though it was a regular .NET web service.

There are lots of resources to help you get started. Try MSDN, Learning WCF and Programming WCF Services.

My project is split up into a typical 3 layer structure for a Silverlight app. That is:

  • A base layer, which is a class library that contains all my business objects, logic, data access etc.
  • A middle layer which is a WCF service which communicates with;
  • My Silverlight front end

The problem I have is that currently the BO's exposed through WCF to my UI only contain the private variables, and none of the propertys or methods.

Is there an easy way to expose the full object (via attributes or configuration)?

What is the best solution?

It seems that you are expecting internal classes used in the WCF service which you have marked as DataContracts to be exported as .NET objects to your client code (the Silverlight UI). WCF does not support this capability. A class marked as a DataContract is just that, a data structure with no methods. If you need a good resource for undestanding WCF, try Learning WCF: A Hands-on Guide by Michele Bustamente.

@John Fisher does sketch out a way of exposing .NET objects to both the client & service but this may not be an option for Silverlight. Here is a blog entry explaining how to access REST-based services from Silverlight.

Can any one suggest me a good book for .Net Web Services beginers (C#)

Try this book, very highly recommended and current

ASP.NET 4 in C# and VB.NET

If you're looking for WCF, this one is great:

Essential WCF

If you're only just starting to do web services, I would strongly recommend you go and check out WCF. It's the current and future standard for communications between machines - web services and a lot more.

The book I always recommend to get up and running in WCF quickly is Learning WCF by Michele Leroux Bustamante. She covers all the necessary topics, and in a very understandable and approachable way. This will teach you everything - basics, intermediate topics, security, transaction control and so forth - that you need to know to write high quality, useful WCF services.

Learning WCF

The more advanced topics and more in-depth look at WCF will be covered by Programming WCF Services by Juval Lowy. He really dives into all technical details and topics and presents "the bible" for WCF programming. He just recently completed a third edition, which covers WCF in .NET 4 and AppFabric and the Azure Service Bus, too.

Programming WCF Services including AppFabric and Azure ServiceBus

I am confused as to what is the best method for building a web service in .net. Giving the fact that it needs to be highly scalable. Any suggestions?

Use WCF.

It allows you to expose a service using multiple protocols and multiple security contexts.

A very good resource for learning WCF is Michele Bustamante's book Learning WCF.

http://www.amazon.com/Learning-Hands-Michele-LeRoux-Bustamante/dp/0596101627 Note: If you do get this book, she has an updated version of Chapter 1 and an appendix on her website.

Her website is also a good source of up-to-date information: http://www.dasblonde.net/default.aspx

I'm starting to get into WCF and Silverlight development and I've decided on a RESTful architecture. I need resources now and am looking for some good books. Can someone recommend any?

Does anyone know if this book: "Learning WCF" by Bustamante (http://www.amazon.com/Learning-WCF-Hands-Michele-Bustamante/dp/0596101627) has any REST implementations in there?

Restful.net I've not read it, but it rated well on Amazon.com

Also, Not a book, but I thought this was a great place to start.

My question is aimed more towards "etiquette" vs performance/technicalities.

What is considered good practice with client/server comms on a client's pc. My app "logs" certain things to a wcf server. My server can run locally on LAN, or somewhere on the internet (port forwarding on server side etc).

Overhead does not really concern me, as I am logging minuscule amounts of data, but I will be logging it frequently... lets say every 10 seconds or so.

Do I instantiate my WCF object once (connect from client to server on app startup), or do I instantiate a new wcf connection (wcf derived call) every 10 seconds.

What is considered good practice. I concerned with applying proper etiquette with client resources.

Any good reading material you can point me to?

The best practice that all the WCF gurus like Michele Leroux Bustamante (author of Learning WCF - A Hand's On Guide) and Juval Löwy (author of advanced Programming WCF Services) preach is to use the per-call activation: each request creates its own instance of the service class, handles the request, and throws away the service instance again after the call.

This is by far the most scalable scenario.

All other scenarios (per-session, using multi-threaded service classes, or using a singleton) have significant impact on overall system performance, or they cause significantly more complicated programming experiences (multi-threading safe service classes).

Unless you have a very compelling reason for another setup, I would recommend to use per-call WCF services.

I am involved in a project with UI comprising mainly of Action Script. My role as an ASP.NET programmer is to pull data from DB using Web Services and supply it as XML to the Action Script.

It would help me immensely if I could learn more about XML Web Services in ASP.NET. I searched for a new book in this topic but couldn't find any book completely dedicated to the topic. I have found many books published at around 2002 or so. I would like to know whether there is a good new book that would be handy for my project. It would be better if they use 3.5 technologies like Linq to XML and all.

Thank you.

If you're only just starting to do web services in ASP.NET, I would strongly recommend you go and check out WCF. It's the current and future standard for communications between machines - web services and a lot more. The "old-style" ASMX web services are on their way out.

The book I always recommend to get up and running in WCF quickly is Learning WCF by Michele Leroux Bustamante. She covers all the necessary topics, and in a very understandable and approachable way. This will teach you everything - basics, intermediate topics, security, transaction control and so forth - that you need to know to write high quality, useful WCF services.

alt text

Also, I'd strongly recommend the Pluralsight series of WCF screen casts. I love books and they are great to read up on stuff - but sometimes, I find it easier to actually see someone show how to really code the thing and see it work and run. Highly recommended, 10-20 minute for each video, very informative and useful indeed!

I know how to enable WCF tracing and view them in the trace viewer tool, but I don't understand what it all means. is there documentation somewhere that explains what each of those levels means and how to make scene of all the information that is being logged.

also what is a good source to learn about a WCF request/response life cycle. all the stages that a message goes through in the WCF internals.

Don't know any doc on the Service Trace Viewer - its help file and MSDN are probably the only source I would check for.

As for intro: see Juwal Lovy's excellent WCF Essentials article here - quite a good intro.

Or if you can, buy the Learning WCF book by Michele Leroux Bustamante - one of the best around, IMO.

alt text

Marc

I'm looking for any beyond basic resources that can help me to be proficient with WCF.

I found Microsoft Virtual Labs that are pretty good but I'm looking for more. I'd really appreciate if you point me to more resources.

Thanks a lot.

There's a really good book my Michele Leroux Bustamante called Learning WCF (something like a pre-cursor to Juwal Lowy's more advanced book). She goes into great detail on all topics of WCF, even some very advanced ones (like federated authentication).

Michele has also recorded a 15-part screencast series on MSDN called "WCF Top-to-Bottom" which is a really great way to get started into WCF programming. Check out her link collection for that series.

Marc

Is there any site from where I can get the most of the information about WCF configuration settings e.g. keyEntropyMode,maxStatefulNegotiations,sessionKeyRolloverInterval, negotiationTimeout etc.

I have started recently working in wcf but is facing many troubles in understanding the terms. There are to be honest huge. And whenever I get stuck, it takes a long time for me to solve it (searching and searching in google and after spending sometime hours I may get the solution).

Henceforth, I think it is better to know if not all astleast some of the terms and their usage and what they means.

It would be great help if anyone can point such a link. I searched in the net with " wcf configuration file elements" but with not much luck.

Thanks

That would be a very very large page! All the WCF settings..... don't know if you could have that "at a glance"....

WCF is a big beast - it has a ton of options and settings, and they do get almost overwhelming. Point is: do not try to know and master all of them - you won't be able to do that. Get to know what you need to know, build a solid foundation, and then go from there and learn more as you need to.

Also - do you know about the visual WCF Service Config Tool in Visual Studio?? Extremely helpful indeed! Invoke it from the Tools > WCF Service Configuration Editor menu or right-click on a app.config in your solution explorer and pick Edit WCF Configuration. You'll get something like this:

alt text

The great thing about this is:

  • it gives you dropdown lists for lots of stuff, like the bindings - you can pick your binding, so you always see your valid options
  • it will show you the properties on each item, so you can fill them out as needed (or even discover new properties)
  • it gives you nice tasks you can perform, like adding a new service or a new endpoint

That's probably as close as it gets to a "complete overview" of WCF. Other than that - check out the great books Learning WCF by Michele Leroux Bustamante for intro to intermediate level, and Programming WCF Services by Juval Lowy for really advanced stuff. Great references and great places to look up stuff!

Learning WCF

Programming WCF Services

I want to learn step by step how to create a WCF service, starting from something very simple.

Can anyone help me?

See this series of web casts by Michelle Bustamonte.

If you are a beginner, this is one of the best sources to learn WCF.

You can also start with the book Learning WCF.

Also take a look at these SO posts -

learning the basics of WCF

What is the best way to learn WCF?

Good and easy books/tutorials to learn WCF latest stuff

I found this webcast to be an excellent introduction to WCF.

I would also recommend anything by Juval Lowy, especially his book Programming WCF Services. His website, IDesign.net, has a lot of free code downloads that I find especially instructive.

I would like to access to multiple web services with a WPF application (Facebook, Twitter, etc...).

I'm not familiar at all with WCF and I was wondering what should I use and why (pros and cons) ? WCF or something else more traditional (like HttpWebRequest) ?

Go with WCF! It's the way to go, it's the present and future of Microsoft's "connected systems" strategy. You can attach to just about anything using WCF - and contrary to Khalid, I don't think it has a really high learning curve.

Get yourself a good book - I recommend Learning WCF by Michele Leroux Bustamante - check out her samples, play with those.

Also check out online resources:

That should easily get you started! There's a ton more stuff out there.

Watch those two DNR-TV screen casts - they show how to really understand what is needed in terms of WCF configuration. It's really not rocket science! But unfortunately, the "Add Service Reference" and svcutil.exe both have a tendency to create awfully and overly complicated configs - that's not necessary.

More online resources for WCF REST and Twitter:

Morning all,

I have been tasked with developing a client tool for a cloud web service API (A simple WSDL). I am not a seasoned or even qualified developer, I have an intermediate knowledge of C# and enough I believe to make this work, but I don't want a solution that just works, I want to build something clean and well coded which another dev can read and understand and which is intuitive.

You may want to stop me there and say "That is something you can only learn through experience." if that is the case then I can accept that and move on, but if you do have some advice the rest of the details are below.

The solution will be a C# Console application. I have produced a spec for this, it is below:

1.) Create a console application in .NET which has the following capabilities:

2.) Consume CSV file containing Processed Data OR ODBC Connection to staging SQL database and read records directly out of load table

3.) Make the following calls to Zuora Webservice (Asynchronous) ·
SubscribeWithExisitingAccount() · Create() ·
Login() · Subscribe() · Update() · Delete()

(*) Calls marked with this are possibly avoidable,

*it is possible to create a subscription, account and contact with a single call (Subscribe())

*Create() may be the exception as a scenario may occur where we need to create an instance of an object with no corresponding subscription.

4.) Report back the success and errors of every record into a CSV file.

 Mappings will be done on a 1 to 1 basis, where the input file

will have the same column names as the target

Where I lack knowledge is following a design which will make this app make sense and work efficiently. I am not looking for someone to do this for me, what I am looking for is tips on how I can improve on what I am already doing

Currently I am just organically building the solution due to a lack of foresight on jobs like this, so I am also interested in things I can do post development.

ALL Advice and criticism is welcomed.

Thanks in advance,

Matt

I would recomend you read a book on webservices (this is a good one) They arent really something you can just pick up from playing about and can be quite frustraiting if you dont know what your doing.

As for development, I recomend you prototype it first. Hammer something out thats messy but lets you get an idea of how to do things. You can then use that as a reference for when your actually building your app.

The problem: I have a web service up and running ok, the problem I have is that i need to return more than one instance of a class and have no real idea how to do this.

I have a loop set up in the service:

If localtab.Rows.Count > 0 Then
            Do While i <= localtab.Rows.Count
                Mbr.Urn = localtab.Rows(i).Item(0) & vbNullString
                Mbr.Title = localtab.Rows(i).Item(1) & vbNullString
                Mbr.Initials = localtab.Rows(i).Item(2) & vbNullString
                Mbr.Surname = localtab.Rows(i).Item(3) & vbNullString
                Mbr.Address1 = localtab.Rows(i).Item(4) & vbNullString
                Mbr.Address2 = localtab.Rows(i).Item(5) & vbNullString
                Mbr.Address3 = localtab.Rows(i).Item(6) & vbNullString
                Mbr.Town = localtab.Rows(i).Item(7) & vbNullString
                Mbr.County = localtab.Rows(i).Item(8) & vbNullString
                Mbr.Country = localtab.Rows(i).Item(9) & vbNullString
                Mbr.Postcode = localtab.Rows(i).Item(10) & vbNullString
                Mbr.msg = "Success"

                i = i + 1
            Loop
        Else
            Mbr.msg = "Fail - no record found"
        End If 

And i know that this works fine as it returns the last member listed in the DB. Doing something like Mbr(i).urn etc... won't work as when I loop through i, it is only ever going to return the first instance, and once the service has returned once it will stop.

Below is the code from the client end calling the service - simple enough, all I am looking for just now is for a message box with each surname to be displayed.

Dim abMem As New ArdbegMember
    Dim retMem As ArdbegMember

    abMem.Downloaded = "N"

    Try
        cc.Open()
        retMem = cc.MbrReq(abMem)
        MesgBox(retMem.Surname)
        cc.Close()

What I need to know is how to pass a full recordset back to the client

EDIT

So based on the suggestions below, my code now looks like this -

Dim results As List(Of ArdbegMember)
            Dim i As Integer = 0

            'assign values from the table to the ArdbegMember object
            If localtab.Rows.Count > 0 Then
                Do While i <= localtab.Rows.Count
                    Mbr.Urn = localtab.Rows(i).Item(0) & vbNullString
                    Mbr.Title = localtab.Rows(i).Item(1) & vbNullString
                    Mbr.Initials = localtab.Rows(i).Item(2) & vbNullString
                    Mbr.Surname = localtab.Rows(i).Item(3) & vbNullString
                    Mbr.Address1 = localtab.Rows(i).Item(4) & vbNullString
                    Mbr.Address2 = localtab.Rows(i).Item(5) & vbNullString
                    Mbr.Address3 = localtab.Rows(i).Item(6) & vbNullString
                    Mbr.Town = localtab.Rows(i).Item(7) & vbNullString
                    Mbr.County = localtab.Rows(i).Item(8) & vbNullString
                    Mbr.Country = localtab.Rows(i).Item(9) & vbNullString
                    Mbr.Postcode = localtab.Rows(i).Item(10) & vbNullString
                    Mbr.msg = "Success"

                    i = i + 1

                    results.Add(Mbr)
                Loop
            Else
                Mbr.msg = "Fail - no record found"
            End If

            'Tidy up
            dataAdapter.Dispose()
            Cmd.Dispose()
            oConn.Close()

            'Return the ArdbegMember object
            Return results

And the error being thrown is now -

Value of type 'System.Collections.Generic.List(Of ArdbegWeb.ArdbegMember)' cannot be converted to 'ArdbegWeb.ArdbegMember'.

You can always create a service that returns a List<T> given you define a concrete type for <T>:

[ServiceContract]
public interface IYourService
{
   [OperationContract]
   public List<ArdbegMember> GetMembers();  
}

Assuming you have a data contract class:

[DataContract]
public class ArdbegMember
{
    [DataMember]
    public string Title { get; set; }
    [DataMember]
    public string Initials { get; set; }
    [DataMember]
    public string Surname { get; set; }
    .... (and so forth - define all the properties you need on your `ArdbegMember`)
}

In your service implementation, you could then write:

public class YourService : IYourService
{
   public List<ArdbegMember> GetMembers()
   {
       List<ArdbegMember> results = new List<ArdbegMember>();

       // load your `localtab` somehow
       foreach(DataRow row in localtab.Rows)
       {
           ArdbegMember member = new ArdbegMember();
           // set the properties, based on the "row"

           results.Add(member);
       }

       return results;
   }  
}

So now you have a WCF service with a single method called GetMembers() (you probably want to pass in some search criteria, etc. - in your real service) and returns back a list of ArdbegMember objects.

Some good WCF resources:

Interested in a book? I would recommend Learning WCF by Michele Leroux Bustamante. She covers all the necessary topics, and in a very understandable and approachable way. This will teach you everything - basics, intermediate topics, security, transaction control and so forth - that you need to know to write high quality, useful WCF services.

Learning WCF

(Yes, I'm disgruntled, irritated and argumentative, OK I'm venting a bit here at the top, but my actual question is objective, I promise <g>)

Venting

I've just spent the last 2 weeks touring many aspect of WCF and now ASP.NET web service. This was done via. the Get Error/Google Error/Fix Error (maybe)/Repeat cycle. After hours of that (mostly in the configuration section) I'm somewhat surprised that anyone even bothers using them. Enough Venting...

The Question

I need to have a client app call code on a web server over the internet. I want the Server side code to look something like this

interface I
{
  string GetFoo(int i);
  SomeType GetBar(OtherType ot);
}

[HostAsService<I>]
class Foo : I
{
    ....
}

and the client side to look something like this this

I i = new ServiceProxy<I>(new Uri("http://my.domain.com/some/path"));

the important bit is that the configuration for this is minimal and direct: no including the service name in 12 different places, no wizards generating code and web.config entries, no hidden URLs that I need to change when I switch from testing on my local machine to testing on out server. I just want it simple

Is there anything like that?

Note: I'd actually prefer a simpler, less flexible, fewer things to break model than a more complex, more flexible model. As long as I can stuff any serializable type down the pipe that's all the flexibility I need

note2: I'm not asking how to use WCF or ASMX services (if either can be made to work like I want/need, that's good, but I don't really care what's used at this point as long as it works)

You can definitely do all that in a very basic WCF scenario - if you like, you can do all your setup and configuration in code as opposed to configuration.

You need on the server side:

1) a service contract IMyService that defines the function calls 2) a service implementation MyService that implements that interface 3) a service host that will host your service - this is the part where you'll have to define things like bindings (what protocol to use) and endpoint (what address to use)

You need on the client side:

1) access to the IMyService interface (put that into its own, separate interface assembly) 2) Create a ChannelFactory 3) Have the channel factory give you a channel to communicate with the service

This can all be done in code - no external config to speak of.

Aaron Skonnard of Pluralsight has had a great series of 5-15min. screen casts on how to create your WCF services - usually showing both how to do it in code, as well as how to do it with config. The show "Endpoint.TV" on Channel 9 was actually intermixed with workflow stuff, too - but you should be able to find the basic WCF screencasts in there, too. Check it out!

Marc

PS: If you're serious about learning about WCF (and I would definitely recommend that!), you should check out Michèle Leroux Bustamante's book Learning WCF - A Hands On Guide - highly recommended.

I have a system in which I need bidirectional communication betwen the client and the server. In some instances the client needs to initiate communication with the server to ask a question, query status, get some data, etc. {We have an AI system that performs repetiative tasks, monitoring, report generation, alerting, etc. and clients apps that allow us to interactive with the server.} In other instances, the server needs to report some change in status or an alert to the client. We're using .NET to implement the system and have looked at a number of different architectures:

A) Open a TCP channel and manage the communications at a low level. This seems to meet our needs but has been rather unstable primarily because our teams lack good experienced in low level communications protocols.

B) Use .NET remoting in which both systems are acting as host - the client registeres the server as a remoting host and once a connection is established, the server goes ahead and registeres the client as a remoting host under a difference channel. This seems to work okay for basic messaging but there are instances in which we need to maintain a "conversation" between the client and the server. Having mutliple clients under this architecture seems to be a bit challenging.

C) Forget bidirectional communication and use a poll architecture to poll the server for new messages - works okay but creates an overly chatty system and makes "conversations" between client and server challenging.

Any thoughs on the best approach? Any different approaches recommended?

WCF would seem a good choice. There is a rather good tutorial on CodeProject that describes how to implement a client / server chat application.

There is also a series of webcasts here and the book by the same author

I was recently working on .net; now I want to learn WCF. Are there any topics required before going to WCF? Because somewhere I saw that WWF is necessary, is it? I want to go through the WCF tutorial.. please suggest me a right path

Thank you

The book I always recommend to get up and running in WCF quickly is Learning WCF by Michele Leroux Bustamante. She covers all the necessary topics, and in a very understandable and approachable way. This will teach you everything - basics, intermediate topics, security, transaction control and so forth - that you need to know to write high quality, useful WCF services.

Learning WCF

The more advanced topics and more in-depth look at WCF will be covered by Programming WCF Services by Juval Lowy. He really dives into all technical details and topics and presents "the bible" for WCF programming. He just recently completed a third edition, which covers WCF in .NET 4 and AppFabric and the Azure Service Bus, too.

Programming WCF Services

As for other resoures: there's the MSDN WCF Developer Center which has everything from beginner's tutorials to articles and sample code.

Also, check out the screen cast library up on MSDN for some really useful, 10-15 minute chunks of information on just about any topic related to WCF you might be interested in. Also, on CHannel9, check out the Endpoint TV Show - the older videos in this show are really good intros to WCF (create your first WCF service, create your first WCF client and so forth)