Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save mfloryan/1621399 to your computer and use it in GitHub Desktop.

Select an option

Save mfloryan/1621399 to your computer and use it in GitHub Desktop.

Revisions

  1. mfloryan created this gist Jan 16, 2012.
    69 changes: 69 additions & 0 deletions ServiceClientBaseHeaderInjectingExtension.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,69 @@
    using System;
    using System.Security.Principal;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using Adp.Shared.Security;

    namespace Adp.Shared.ServiceClient
    {
    public static class ServiceClientBaseHeaderInjectingExtension
    {
    /// <summary>
    /// Sets the OID and AOID headers and calls the service.
    /// First argument to action is OID
    /// </summary>
    public static TResult CallServiceSettingHeaders<TResult, TService>(
    this ClientBase<TService> serviceClient,
    IPrincipal user,
    Func<string, TResult> action) where TService : class
    {
    using (var scope = new OperationContextScope(serviceClient.InnerChannel))
    {
    AddHeaders(user);
    return action(user.Oid());
    }
    }

    /// <summary>
    /// Sets the OID and AOID headers and calls the service.
    /// First argument to action is OID and the second in AOID
    /// </summary>
    public static TResult CallServiceSettingHeaders<TResult, TService>(
    this ClientBase<TService> serviceClient,
    IPrincipal user,
    Func<string, string, TResult> action) where TService : class
    {
    using (var scope = new OperationContextScope(serviceClient.InnerChannel))
    {
    AddHeaders(user);
    return action(user.Oid(), user.Aoid());
    }
    }

    /// <summary>
    /// Sets the OID and AOID headers and calls the service.
    /// First argument to action is OID and the second in AOID
    /// Third argument is passed through
    /// </summary>
    public static TResult CallServiceSettingHeaders<TResult, TService, TArg>(
    this ClientBase<TService> serviceClient,
    IPrincipal user,
    Func<string, string, TArg, TResult> action,
    TArg arg) where TService : class
    {
    using (var scope = new OperationContextScope(serviceClient.InnerChannel))
    {
    AddHeaders(user);
    return action(user.Oid(), user.Aoid(), arg);
    }
    }

    private static void AddHeaders(IPrincipal user)
    {
    var headers = new HttpRequestMessageProperty();
    headers.Headers.Add("oid", user.Oid());
    headers.Headers.Add("aoid", user.Aoid());
    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = headers;
    }
    }
    }