Search code examples
f#type-providersc#-to-f#

System.Linq.Enumerable.OfType<T> - is there a F# way?


I'm looking to use the F# WSDL Type Provider. To call the web service I am using, I need to attach my client credentials to the System.ServiceModel.Description.ClientCredentials.

This is the C# code I have:

var serviceClient = new InvestmentServiceV1Client.InvestmentServiceV1Client();

foreach (ClientCredentials behaviour in serviceClient.Endpoint.Behaviors.OfType<ClientCredentials>())
{
    (behaviour).UserName.UserName = USERNAME;
    (behaviour).UserName.Password = PASSWORD;
    break;
}

This is the F# code I have so far:

let client = new service.ServiceTypes.InvestmentServiceV1Client()
let xxx = client.Endpoint.Behaviors
|> Seq.choose (fun p -> 
    match box p with   
    :?   System.ServiceModel.Description.ClientCredentials as x -> Some(x) 
    _ -> None) 
|> (System.ServiceModel.Description.ClientCredentials)p.UserName.UserName = USERNAME

Is there an F# equivalent of System.Linq.Enumerable.OfType<T> or should I just use raw OfType<T> ?


Solution

  • I suppose the question is mainly about the break construct, which is not available in F#. Well, the code really just sets the user name and password for the first element of the collection (or none, if the collection is empty). This can be done easily using pattern matching, if you turn the collection to an F# list:

    // Get behaviours as in C# and convert them to list using 'List.ofSeq'
    let sc = new InvestmentServiceV1Client.InvestmentServiceV1Client()
    let behaviours = sc.Endpoint.Behaviors.OfType<ClientCredentials>() |> List.ofSeq
    
    // Now we can use pattern matching to see if there is something in the list
    match behaviours with
    | behaviour::_ ->
        // And if the list is non-empty, set the user name and password
        behaviour.UserName.UserName <- USERNAME
        behaviour.UserName.Password <- PASSWORD
    | _ -> ()