문제

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

도움이 되었습니까?

해결책

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
| _ -> ()

다른 팁

I think you've already implemented the F# equivalent of .OfType(). For emulating the break statement you can do as Tomas does in his answer (matching on list), or you call Seq.head (throws if there are no elements left), or you can do this:

let xxx = 
    client.Endpoint.Behaviors
    |> Seq.choose (function
        | :? System.ServiceModel.Description.ClientCredentials as x -> Some x
        | _ -> None ) 
    |> Seq.tryPick Some

match xxx with
| Some behavior -> ... // First element of required type found
| None -> ...          // No elements of required type at all in sequence
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top