Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 839923
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T05:32:28+00:00 2026-05-15T05:32:28+00:00

I am a newbie with F# and SL and playing with getting asynchronous HttpResponse

  • 0

I am a newbie with F# and SL and playing with getting asynchronous HttpResponse through Silverlight. The following is the F# code pieces, which is tested on VS2010 and Window7 and works well, but the improvement is necessary. Any advices and discussion, especially the callback part, are welcome and great thanks.

module JSONExample
open System
open System.IO 
open System.Net 
open System.Text 
open System.Web 
open System.Security.Authentication 
open System.Runtime.Serialization 


[<DataContract>] 
type Result<'TResult> = { 
    [<field: DataMember(Name="code") >] 
    Code:string 
    [<field: DataMember(Name="result") >] 
    Result:'TResult array
    [<field: DataMember(Name="message") >] 
    Message:string 
    } 

// The elements in the list
[<DataContract>] 
type ChemicalElement = { 
    [<field: DataMember(Name="name") >] 
    Name:string 
    [<field: DataMember(Name="boiling_point") >] 
    BoilingPoint:string 
    [<field: DataMember(Name="atomic_mass") >] 
    AtomicMass:string 
} 



//http://blogs.msdn.com/b/dsyme/archive/2007/10/11/introducing-f-asynchronous-workflows.aspx
//http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!194.entry
type System.Net.HttpWebRequest with
    member x.GetResponseAsync() =
        Async.FromBeginEnd(x.BeginGetResponse, x.EndGetResponse)


type RequestState () = 
    let mutable request : WebRequest = null
    let mutable response : WebResponse = null
    let mutable responseStream : Stream = null
    member this.Request with get() = request and set v = request <- v
    member this.Response with get() = response and set v = response <- v
    member this.ResponseStream with get() = responseStream and set v = responseStream <- v

let allDone = new System.Threading.ManualResetEvent(false)


let getHttpWebRequest (query:string) = 
    let query = query.Replace("'","\"") 
    let queryUrl = sprintf "http://api.freebase.com/api/service/mqlread?query=%s" "{\"query\":"+query+"}" 

    let request : HttpWebRequest = downcast WebRequest.Create(queryUrl) 
    request.Method <- "GET" 
    request.ContentType <- "application/x-www-form-urlencoded" 
    request


let GetAsynResp (request : HttpWebRequest) (callback: AsyncCallback) = 
    let myRequestState = new RequestState()
    myRequestState.Request <- request
    let asyncResult = request.BeginGetResponse(callback, myRequestState)
    ()


// easy way to get it to run syncrnously w/ the asynch methods
let GetSynResp (request : HttpWebRequest) : HttpWebResponse  =      
    let response = request.GetResponseAsync() |> Async.RunSynchronously  
    downcast response

let RespCallback (finish: Stream -> _) (asynchronousResult : IAsyncResult) =
        try
            let myRequestState : RequestState = downcast asynchronousResult.AsyncState 
            let myWebRequest1 : WebRequest = myRequestState.Request
            myRequestState.Response <- myWebRequest1.EndGetResponse(asynchronousResult)
            let responseStream = myRequestState.Response.GetResponseStream()
            myRequestState.ResponseStream <- responseStream
            finish responseStream
            myRequestState.Response.Close() 
            ()
        with 
        | :? WebException as e
            -> printfn "WebException raised!"
               printfn "\n%s" e.Message
               printfn "\n%s" (e.Status.ToString())
               ()
        | _ as e
            -> printfn "Exception raised!"
               printfn "Source : %s" e.Source
               printfn "Message : %s" e.Message
               ()

let printResults (stream: Stream)= 
    let result = 
        try 
            use reader = new StreamReader(stream) 
            reader.ReadToEnd(); 
        finally 
            ()

    let data = Encoding.Unicode.GetBytes(result); 
    let stream = new MemoryStream() 
    stream.Write(data, 0, data.Length); 
    stream.Position <- 0L 

    let JsonSerializer = Json.DataContractJsonSerializer(typeof<Result<ChemicalElement>>) 
    let result = JsonSerializer.ReadObject(stream) :?> Result<ChemicalElement> 

    if result.Code<>"/api/status/ok" then 
        raise (InvalidOperationException(result.Message)) 
    else 
        result.Result |> Array.iter(fun element->printfn "%A" element) 

let test =
    // Call Query (w/ generics telling it you wand an array of ChemicalElement back, the query string is wackyJSON too –I didn’t build it don’t ask me!
    let request = getHttpWebRequest "[{'type':'/chemistry/chemical_element','name':null,'boiling_point':null,'atomic_mass':null}]"
    //let response = GetSynResp request 
    let response = GetAsynResp request (AsyncCallback (RespCallback printResults))
    () 

ignore(test)
System.Console.ReadLine() |> ignore
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T05:32:28+00:00Added an answer on May 15, 2026 at 5:32 am

    The whole point of async is that you don’t have to deal with state and IAsyncResult and Callbacks and whatnot. Below is a somewhat cleaned-up version of your code…

    open System 
    open System.IO  
    open System.Net  
    open System.Text  
    open System.Web  
    open System.Security.Authentication  
    open System.Runtime.Serialization  
    
    [<DataContract>]  
    type Result<'TResult> = {  
        [<field: DataMember(Name="code") >]  
        Code:string  
        [<field: DataMember(Name="result") >]  
        Result:'TResult array 
        [<field: DataMember(Name="message") >]  
        Message:string  
        }  
    
    // The elements in the list 
    [<DataContract>]  
    type ChemicalElement = {  
        [<field: DataMember(Name="name") >]  
        Name:string  
        [<field: DataMember(Name="boiling_point") >]  
        BoilingPoint:string  
        [<field: DataMember(Name="atomic_mass") >]  
        AtomicMass:string  
    }  
    
    //http://blogs.msdn.com/b/dsyme/archive/2007/10/11/introducing-f-asynchronous-workflows.aspx 
    //http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!194.entry 
    type System.Net.HttpWebRequest with 
        member x.GetResponseAsync() = 
            Async.FromBeginEnd(x.BeginGetResponse, x.EndGetResponse) 
    
    let getHttpWebRequest (query:string) =  
        let query = query.Replace("'","\"")  
        let queryUrl = sprintf "http://api.freebase.com/api/service/mqlread?query=%s" "{\"query\":"+query+"}"  
    
        let request : HttpWebRequest = downcast WebRequest.Create(queryUrl)  
        request.Method <- "GET"  
        request.ContentType <- "application/x-www-form-urlencoded"  
        request 
    
    let printResults (stream: Stream)=  
        let result =  
            try  
                use reader = new StreamReader(stream)  
                reader.ReadToEnd();  
            finally  
                () 
    
        let data = Encoding.Unicode.GetBytes(result);  
        let stream = new MemoryStream()  
        stream.Write(data, 0, data.Length);  
        stream.Position <- 0L  
    
        let JsonSerializer = Json.DataContractJsonSerializer(typeof<Result<ChemicalElement>>)  
        let result = JsonSerializer.ReadObject(stream) :?> Result<ChemicalElement>  
    
        if result.Code<>"/api/status/ok" then  
            raise (InvalidOperationException(result.Message))  
        else  
            result.Result |> Array.iter(fun element->printfn "%A" element)  
    
    let test = async {
        // Call Query (w/ generics telling it you wand an array of ChemicalElement back, the query string is wackyJSON too –I didn’t build it don’t ask me! 
        let request = getHttpWebRequest "[{'type':'/chemistry/chemical_element','name':null,'boiling_point':null,'atomic_mass':null}]" 
        try 
            use! response = request.AsyncGetResponse()
            use responseStream = response.GetResponseStream() 
            printResults responseStream 
        with  
        | :? WebException as e 
            ->  printfn "WebException raised!" 
                printfn "\n%s" e.Message 
                printfn "\n%s" (e.Status.ToString()) 
        | _ as e 
            ->  printfn "Exception raised!" 
                printfn "Source : %s" e.Source 
                printfn "Message : %s" e.Message 
    }
    
    test |> Async.RunSynchronously 
    System.Console.ReadLine() |> ignore 
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm a newbie at Flash, so started playing with a pretty standard code sample:
Newbie to LINQ, and trying to write the following query... select f.Section_ID, f.Page_ID, f.SortOrder,
Newbie here...can I write one program which incorporates .NET LINQ and also various Java
I'm a newbie playing around with Lisp (actually, Emacs Lisp). It's a lot of
Complete newbie question here: I'm just playing with C# for the first time and
I'm playing around with the flash Video cam and I'm a real puppy-dog-level newbie
First of all I'm a python newbie. I'm playing with Django and I'm trying
I am a newbie to Android and playing around with the UI and SQLLite
Hey, one more newbie here, just playing around with .NET MVC. My main task
Newbie Scala Question: Say I want to do this [Java code] in Scala: public

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.