Showing posts with label F#. Show all posts
Showing posts with label F#. Show all posts

Monday, November 7, 2011

i++ kind of functionality in F#

As F# is immutable language, we will not be able to use i++ kind of functionality directly. You will have to combine the "mutable" and "module" feature of F# to achieve the i++ kind of functionality. Below here is the simple demonstration of this;

module Foo
       let mutable m_field = 0
       let next () =
             m_field <- m_field + 1; m_field

Just use Foo.next () whereever you need i++ kind of functionality.

Wednesday, October 19, 2011

Consume WCF REST service in F#

Today I successfully implemented the code for consuming WCF REST service in F#. Funny part here is that, this is my first program in F#.. LOL

Ok.. Here is the code for consuming WCF REST in F#.

module FSModule

#light

open System
open System.Text
open System.Net
open System.IO
open System.Web

// F# uses indenting to define scope. So ensure that you indent properly to get it working
let GetDataFromRest =
     let buffer = Encoding.ASCII.GetBytes("<HelloService_SayHello><input>Hello from F#</input></HelloService_SayHello>") //This is needed if its a POST call
     let req = WebRequest.Create(new Uri("http://localhost/HelloService.svc/SayHello")) :?> HttpWebRequest
     req.Method <- "POST"
     req.ContentType <- "application/xml" //Use accordingly XML or JSON
     req.ContentLength <- int64 buffer.Length
     let reqSt = req.GetRequestStream()
     reqSt.Write(buffer,0,buffer.Length)
     reqSt.Flush()
     req.Close()

     let res = req.GetResponse () :?> HttpWebResponse
     let resSt = res.GetResponseStream()
     let sr = new StreamReader(resSt)
     let x = sr.ReadToEnd()
     sr.Close()
     x.ToString()

Done... To invoke this, you can either use F# or C# or even VB.NET :)

F#

let result = GetDataFromRest()
printfn result

C#

string result = FSModule.GetDataFromRest()