Saturday, February 25, 2012

Wcf and Node.js, better together

@YaronNaveh

(get wcf.js on github!)

Take a look at the following code:


Do you see anything...um, special? Well c# already has the "var" keyword since version 3.0 so maybe it is some kind of a c#-ish dialect? Or maybe it is a CTP for javascript as a CLR language? Or something related to the azure sdk for node.js?

Not at all. This is a snippet from wcf.js - a pure javascript node.js module that makes wcf and node.js work together!

As node assumes its central place in modern web development, many developers build node apps that must consume downstream wcf services. Now if these services use WCF Web API ASP.NET Web API it is very easy. It is also a breeze if you are in a position to add a basic http binding to the Wcf service, and just a little bit of more work if you plan to employ a wcf router to do the protocol bridging. Wcf.js is a library that aims to provide a pure-javascript development experiece for such scenarios.

Note that building new node.js ws-* based services is a non-goal for this project. Putting aside all the religious wars, Soap is not the "node way", so you should stick to Rest where you'll get good language support (json) and built-in libraries.

"Hello, Wcf... from node"

You are closer than you think to consume your first Wcf service node.js:

1. Create a new wcf web site in VS and call it "Wcf2Node". If you use .Net 4 than BasicHttpBinding is the default, otherwise in web.config replace WsHttp with BasicHttp. No need to deploy, just run the service in VS using F5.

2. Create anywhere a folder for the node side and from the command line enter its root and execute:

$> npm install wcf.js

3. In the same folder create test.js:

var BasicHttpBinding = require('wcf.js').BasicHttpBinding
  , Proxy = require('wcf.js').Proxy
  , binding = new BasicHttpBinding()
  , proxy = new Proxy(binding, " http://localhost:12/Wcf2Node/Service.svc")
  , message = '<Envelope xmlns=' +
            '"http://schemas.xmlsoap.org/soap/envelope/">' +

                 '<Header />' +
                   '<Body>' +
                     '<GetData xmlns="http://tempuri.org/">' +
                       '<value>123</value>' +
                     '</GetData>' +
                    '</Body>' +
               '</Envelope>'

proxy.send(message, "http://tempuri.org/IService/GetData", function(response, ctx) {
  console.log(response)
});


4. In test.js, change the port 12 (don't ask...) to the port your service runs on.

5. Now we can execute node:

$> node test.js

6. You should now see the output soap on the console.

Of course this sample is not very interesting and you may be better off sending the raw soap using request. Let's see something more interesting. If your service uses ssl + username token (transport with message credential), the config may look like this:

<wsHttpBinding>
    <binding name="NewBinding0">
        <security mode="TransportWithMessageCredential">
            <message clientCredentialType="UserName" />
        </security>
    </binding>
</wsHttpBinding>

The following modifications to the previous example will allow to consume it from node:

...
binding = new WSHttpBinding(
        { SecurityMode: "TransportWithMessageCredential"
        , MessageClientCredentialType: "UserName"
        })
...

proxy.ClientCredentials.Username.Username = "yaron";
proxy.ClientCredentials.Username.Password = "1234";
proxy.send(...)

And here is the wire soap:

<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">

<Header>
  <o:Security>
    <u:Timestamp>
      <u:Created>2012-02-26T11:03:40Z</u:Created>
      <u:Expires>2012-02-26T11:08:40Z</u:Expires>
    </u:Timestamp>
    <o:UsernameToken>
      <o:Username>yaron</o:Username>
      <o:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">1234</o:Password>
    </o:UsernameToken>
  </o:Security>
</Header>

<Body>
  <EchoString xmlns="http://tempuri.org/">
    <s>123</s>
  </EchoString>
</Body>


If you use Mtom check out this code:

(The formatting here is a bit strage due to my blog layout - it looks much better in github!)

var CustomBinding = require('wcf.js').CustomBinding

  , MtomMessageEncodingBindingElement = require('wcf.js').MtomMessageEncodingBindingElement

  , HttpTransportBindingElement = require('wcf.js').HttpTransportBindingElement

  , Proxy = require('wcf.js').Proxy
  , fs = require('fs')
  , binding = new CustomBinding(
        [ new MtomMessageEncodingBindingElement({MessageVersion: "Soap12WSAddressing10"}),
        , new HttpTransportBindingElement()
        ])

  , proxy = new Proxy(binding, "http://localhost:7171/Service/mtom")
  , message = '<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope">' +
                '<s:Header />' +
                  '<s:Body>' +
                    '<EchoFiles xmlns="http://tempuri.org/">' +
                      '<value xmlns:a="http://schemas.datacontract.org/2004/07/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">' +
                        '<a:File1 />' +                   
                      '</value>' +
                    '</EchoFiles>' +
                  '</s:Body>' +
              '</s:Envelope>'

proxy.addAttachment("//*[local-name(.)='File1']", "me.jpg");

proxy.send(message, "http://tempuri.org/IService/EchoFiles", function(response, ctx) {
  var file = proxy.getAttachment("//*[local-name(.)='File1']")
  fs.writeFileSync("result.jpg", file)    
});

Mtom is a little bit trickier since wcf.js needs to know which nodes are binary. Using simple xpath can help you achieve that.

Getting your hands dirty with Soap
Wcf.js uses soap in its raw format. Code generation of proxies does not resonate well with a dynamic language like javascript. I also assume you are consuming an existing service which already has working clients so you should be able to get a working soap sample. And if you do like some level of abstraction between you and your soap I recommend node-soap, though it still does not integrate with wcf.js.

If you will use raw soap requests and responses you would need a good xml library. And while node has plenty of dom / xpath libraries, they are not windows friendly. My next post will be on a good match here.

Supported standards
Wcf implements many of the ws-* standards and even more via proprietary extensions. The first version of wcf.js supports the following:

  • MTOM

  • WS-Security (Username token only)

  • WS-Addressing (all versions)

  • HTTP(S)

    The supported binding are:


  • BasicHttpBinding

  • WSHttpBinding

  • CustomBinding

    What do you want to see next? Let me know.

    Get the code
    Wcf.js is hosted in GitHub, and everyone is welcome to contribute features and fixes if needed.
    Wcf.js is powered by ws.js, the actual standards implementation, which I will introduce in an upcoming post.
  • @YaronNaveh

    What's next? get this blog rss updates or register for mail updates!

    15 comments:

    syed amjad said...

    Hi Yaron Naveh,

    Thanks for writing such good article for people like us, it is very appreciated.

    since last one week and i am trying to hard to consume both WCF normal services or WCF Restfull services, neither is getting executed.

    Some times wcf is either returning "Undefined" response or this big message
    ActionNotSupported</faultcode><faultstring xml:lang="en-US">The message with Act
    ion 'http://192.168.2.213:1234/RestFullService.svc' cannot be processed at the r
    eceiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be
    because of either a contract mismatch (mismatched Actions between sender and re
    ceiver) or a binding/security mismatch between the sender and the receiver.

    I used both wcf.js and ws.js, no success at all.

    I request you to help in this regard and get me out of this world.

    I am posting my complete code here, please let me know if you have any questions.

    var BasicHttpBinding = require('wcf.js').BasicHttpBinding
    , Proxy = require('wcf.js').Proxy
    , binding = new BasicHttpBinding()
    , proxy = new Proxy(binding, "http://localhost:3460/Service1.svc")
    , message = '' +
    '' +
    '' +
    '' +
    '' +
    '' +
    '';

    proxy.send(message, "http://tempuri.org/IService1/GetData", function (response, ctx) {
    console.log(response);
    });

    web config




















































































































    wcf service

    public string DoWork ()
    {
    return "Message from Wcf Node";
    }

    Yaron Naveh (MVP) said...

    Hi Syed

    You should not use Wcf.js for REST web services. It only works with soap services, and is recommended when ws-* settings are used. Please send me your wcf service config file (for the non-rest service). send it via mail since xml is not displayed here well.

    Moshe said...

    Brilliant (as usual :))!!! I feel wcf.js is going to be a "life buoy" for thousands of people whom unlucky destiny landed them on the ground of integrating heavy WCF-based systems with modern node.js code. Now they're free to relax - captain Yaron built a ship to cross this gulf (I hope I'm not too flatterer :)).

    Moshe said...

    Brilliant (as usual :))!!! I feel wcf.js is going to be a "life buoy" for thousands of people whom unlucky destiny landed them on the ground of integrating heavy WCF-based systems with modern node.js code. Now they're free to relax - captain Yaron built a ship to cross this gulf (I hope I'm not too flatterer :)).

    Unknown said...

    hi Yaron Naveh,
    I am very new to nodejs,i'm trying to consume WCF services from nodejs, when i'm trying like that i am getting an error like this
    "Error: Cannot find module wcf.js' at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object. (D:\Joshua\Nodejs\Wcf2Node\test.js:1:86)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    and i am following this process http://www.codeproject.com/Articles/379389/Wcf-js-Call-WCF-web-services-from-Node-js

    please help me

    Yaron Naveh (MVP) said...

    Hi Roopa

    Seems like the wcf.js installation is malformed. I suggest to create a new project and do a fresh "npm install wcf.js", watch out for any errors.

    Unknown said...

    I am trying to consume wcf service using NodeJS. i tried BasicHttpBinding with security mode="TransportWithMessageCredential". It is working fine. But if i try to consume the service with WsHttpBinding and security mode="TransportWithMessageCredential", following error is thrown

    "The message could not be processed. This is most likely because the action 'http://tempuri.org/IService1/GetData' is incorrect or because the message contains an invalid or expired security context token or because there is a mismatch between bindings. The security context token would be invalid if the service aborted the channel due to inactivity. To prevent the service from aborting idle sessions prematurely increase the Receive timeout on the service endpoint's binding."

    This is the link to my question on StackOverflow.com
    http://stackoverflow.com/questions/35891106/consuming-wcf-service-wshttp-binding-in-nodejs


    Can you please help me?.........

    Unknown said...

    Can you please help me???
    http://stackoverflow.com/questions/35891106/consuming-wcf-service-wshttp-binding-in-nodejs

    Deevo said...

    Hi. Great little library, well done. Is it possible to add an OperationTimeout to the binding, for occasions when the remote WCF service host is not available? Thanks.

    Yaron Naveh (MVP) said...

    Internally the message is sent with the node.jd request module (refered to in ws.js which wcf.js depends on) so the request module might have a timeout. Not sure when I can add this to wcf.js but meanwhile you hard code the timeout into thew request module settings (either by setting it in ws.js or maybe using request global default in your code can also work).

    Admin said...

    Hey Yaron!
    Thanks for the post and the package, very useful.

    I'm trying to implement this for Priority Web Service.
    In the SDK they say:
    "In order to call the Priority web service from a web service client project, the project must include:
    * A reference to the PriorityCommon .dll file supplied by Eshbel
    * The app.config file supplied by Eshbel"

    Is it possible to include a dll file in nodejs?

    Yaron Naveh (MVP) said...

    you cannot include a dll in node js - sdk level integration must be with .Net.

    Unknown said...

    Hi Yaron,
    do you know what can be causing this?
    this was asked earlier.
    Im not using any authentication



    a:ActionNotSupportedThe message with Action 'http://tempuri.org/IService/GetData' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver. Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None)
    .

    Yaron Naveh (MVP) said...

    Maybe you dont' specify the correct soap action. Compare the outgoing node request (header + body) to a working c# client

    Unknown said...

    Hi
    How do i set a content type for request
    i get error 415