/// <summary>
        /// Reads the headers from App.config.
        /// </summary>
        /// <param name="config">The configuration class.</param>
        protected override void ReadHeadersFromConfig(AppConfig config)
        {
            DfpAppConfig dfpConfig = (DfpAppConfig)config;

            this.requestHeader                 = new RequestHeader();
            this.requestHeader.networkCode     = dfpConfig.NetworkCode;
            this.requestHeader.applicationName = dfpConfig.GetUserAgent();
        }
    private void DoAuth2Configuration(DfpAppConfig config) {
      // Since we use this page for OAuth callback also, we set the callback
      // url as the current page. For a non-web application, this will be null.
      config.OAuth2RedirectUri = Request.Url.GetLeftPart(UriPartial.Path);

      // Create an OAuth2 object for handling OAuth2 flow.
      OAuth2ProviderForApplications oAuth = new OAuth2ProviderForApplications(config);

      if (Request.Params["state"] == null) {
        // This is the first time this page is being loaded.
        // Set the state variable to any value that helps you recognize
        // when this url will be called by the OAuth2 server.
        oAuth.State = "callback";

        // Create an authorization url and redirect the user to that page.
        Response.Redirect(oAuth.GetAuthorizationUrl());
      } else if (Request.Params["state"] == "callback") {
        // This page was loaded because OAuth server did a callback.
        // Retrieve the authorization code from the url and use it to fetch
        // the access token. This call will also fetch the refresh token if
        // your mode is offline.
        oAuth.FetchAccessAndRefreshTokens(Request.Params["code"]);

        // Save the OAuth2 provider for future use. If you wish to save only
        // the values and restore the object later, then save
        // oAuth.RefreshToken, oAuth.AccessToken, oAuth.UpdatedOn and
        // oAuth.ExpiresIn.
        //
        // You can later restore the values as
        // DfpUser user = new DfpUser();
        // user.Config.OAuth2Mode = OAuth2Flow.APPLICATION;
        // OAuth2ProviderForApplications oAuth =
        //     (user.OAuthProvider as OAuth2ProviderForApplications);
        // oAuth.RefreshToken = xxx;
        // oAuth.AccessToken = xxx;
        // oAuth.UpdatedOn = xxx;
        // oAuth.ExpiresIn = xxx;
        //
        // Note that only oAuth.RefreshToken is mandatory. If you leave
        // oAuth.AccessToken as empty, or if oAuth.UpdatedOn + oAuth.ExpiresIn
        // is in the past, the access token will be refreshed by the library.
        // You can listen to this event as
        //
        // oAuth.OnOAuthTokensObtained += delegate(AdsOAuthProvider provider) {
        //    OAuth2ProviderForApplications oAuth =
        //        (provider as OAuth2ProviderForApplications);
        //    // Save oAuth.RefreshToken, oAuth.AccessToken, oAuth.UpdatedOn and
        //    // oAuth.ExpiresIn.
        //};
        Session["OAuthProvider"] = oAuth;
        // Redirect the user to the main page.
        Response.Redirect("Default.aspx");
      } else {
        throw new Exception("Unknown state for OAuth callback.");
      }
    }
 /// <summary>
 /// Handles the Load event of the Page control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="System.EventArgs"/> instance containing
 /// the event data.</param>
 protected void Page_Load(object sender, EventArgs e) {
   // Create an DfpAppConfig object with the default settings in
   // App.config.
   DfpAppConfig config = new DfpAppConfig();
   if (config.AuthorizationMethod == DfpAuthorizationMethod.OAuth2) {
     if (config.OAuth2Mode == OAuth2Flow.APPLICATION &&
         string.IsNullOrEmpty(config.OAuth2RefreshToken)) {
       DoAuth2Configuration(config);
     }
   }
 }
        /// <summary>
        /// Initializes the service before MakeApiCall.
        /// </summary>
        /// <param name="methodName">Name of the method.</param>
        /// <param name="parameters">The method parameters.</param>
        protected override void InitForCall(string methodName, object[] parameters)
        {
            DfpAppConfig  config      = this.User.Config as DfpAppConfig;
            string        oAuthHeader = null;
            RequestHeader header      = GetRequestHeader();

            if (header == null)
            {
                throw new DfpApiException(null, DfpErrorMessages.FailedToSetAuthorizationHeader);
            }

            if (!(this.GetType().Name == "NetworkService" && (methodName == "getAllNetworks" ||
                                                              methodName == "makeTestNetwork")))
            {
                if (string.IsNullOrEmpty(header.networkCode))
                {
                    throw new SoapHeaderException("networkCode header is required in all API versions. " +
                                                  "The only exceptions are NetworkService.getAllNetworks and " +
                                                  "NetworkService.makeTestNetwork.", XmlQualifiedName.Empty);
                }
            }

            if (string.IsNullOrEmpty(header.applicationName) || header.applicationName.Contains(
                    DfpAppConfig.DEFAULT_APPLICATION_NAME))
            {
                throw new ApplicationException(DfpErrorMessages.RequireValidApplicationName);
            }

            if (config.AuthorizationMethod == DfpAuthorizationMethod.OAuth2)
            {
                if (this.User.OAuthProvider != null)
                {
                    oAuthHeader = this.User.OAuthProvider.GetAuthHeader();
                }
                else
                {
                    throw new DfpApiException(null, DfpErrorMessages.OAuthProviderCannotBeNull);
                }
            }
            else if (config.AuthorizationMethod == DfpAuthorizationMethod.ClientLogin)
            {
                string authToken = (!string.IsNullOrEmpty(config.AuthToken)) ? config.AuthToken :
                                   new AuthToken(config, SERVICE_NAME).GetToken();
                ClientLogin clientLogin = (header.authentication as ClientLogin) ?? new ClientLogin();
                clientLogin.token     = authToken;
                header.authentication = clientLogin;
            }

            ContextStore.AddKey("OAuthHeader", oAuthHeader);
            base.InitForCall(methodName, parameters);
        }
Example #5
0
        /// <summary>
        /// Initializes the service before MakeApiCall.
        /// </summary>
        /// <param name="methodName">Name of the method.</param>
        /// <param name="parameters">The method parameters.</param>
        protected override void InitForCall(string methodName, object[] parameters)
        {
            DfpAppConfig  config      = this.User.Config as DfpAppConfig;
            string        oAuthHeader = null;
            RequestHeader header      = GetRequestHeader();

            if (header == null)
            {
                throw new DfpApiException(null, DfpErrorMessages.FailedToSetAuthorizationHeader);
            }

            if (!(this.GetType().Name == "NetworkService" && (methodName == "getAllNetworks" ||
                                                              methodName == "makeTestNetwork")))
            {
                if (string.IsNullOrEmpty(header.networkCode))
                {
                    throw new SoapHeaderException("networkCode header is required in all API versions. " +
                                                  "The only exceptions are NetworkService.getAllNetworks and " +
                                                  "NetworkService.makeTestNetwork.", XmlQualifiedName.Empty);
                }
            }

            // TODO: (cseeley) add tests for this MOE:strip_line
            if (string.IsNullOrWhiteSpace(header.applicationName) || header.applicationName.Contains(
                    DfpAppConfig.DEFAULT_APPLICATION_NAME))
            {
                throw new ApplicationException(DfpErrorMessages.RequireValidApplicationName);
            }

            if (config.AuthorizationMethod == DfpAuthorizationMethod.OAuth2)
            {
                if (this.User.OAuthProvider != null)
                {
                    oAuthHeader = this.User.OAuthProvider.GetAuthHeader();
                }
                else
                {
                    throw new DfpApiException(null, DfpErrorMessages.OAuthProviderCannotBeNull);
                }
            }
            else
            {
                throw new DfpApiException(null, DfpErrorMessages.UnsupportedAuthorizationMethod);
            }

            ContextStore.AddKey("OAuthHeader", oAuthHeader);
            base.InitForCall(methodName, parameters);
        }
        /// <summary>
        /// Create a service object.
        /// </summary>
        /// <param name="signature">Signature of the service being created.</param>
        /// <param name="user">The user for which the service is being created.
        /// <param name="serverUrl">The server to which the API calls should be
        /// made.</param>
        /// </param>
        /// <returns>An object of the desired service type.</returns>
        public override AdsClient CreateService(ServiceSignature signature, AdsUser user,
                                                Uri serverUrl)
        {
            DfpAppConfig dfpConfig = (DfpAppConfig)Config;

            if (serverUrl == null)
            {
                serverUrl = new Uri(dfpConfig.DfpApiServer);
            }

            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            CheckServicePreconditions(signature);

            DfpServiceSignature dfpapiSignature = signature as DfpServiceSignature;

            AdsClient    service  = (AdsClient)Activator.CreateInstance(dfpapiSignature.ServiceType);
            PropertyInfo propInfo = dfpapiSignature.ServiceType.GetProperty("RequestHeader");

            if (propInfo != null)
            {
                RequestHeader clonedHeader = (RequestHeader)requestHeader.Clone();
                clonedHeader.Version = dfpapiSignature.Version;
                propInfo.SetValue(service, clonedHeader, null);
            }

            if (dfpConfig.Proxy != null)
            {
                service.Proxy = dfpConfig.Proxy;
            }
            service.Timeout = dfpConfig.Timeout;
            service.Url     = string.Format("{0}apis/ads/publisher/{1}/{2}",
                                            serverUrl, dfpapiSignature.Version, dfpapiSignature.ServiceName);
            service.UserAgent = dfpConfig.GetUserAgent();

            service.Signature = signature;
            service.User      = user;
            return(service);
        }
        /// <summary>
        /// Checks preconditions of the service signature and throws and exception if the service
        /// cannot be generated.
        /// </summary>
        /// <param name="signature">the service signature for generating the service</param>
        protected override void CheckServicePreconditions(ServiceSignature signature)
        {
            if (signature == null)
            {
                throw new ArgumentNullException("signature");
            }
            if (!(signature is DfpServiceSignature))
            {
                throw new InvalidCastException(string.Format(CultureInfo.InvariantCulture,
                                                             DfpErrorMessages.SignatureIsOfWrongType, typeof(DfpServiceSignature)));
            }
            DfpAppConfig        dfpConfig    = (DfpAppConfig)Config;
            DfpServiceSignature dfpSignature = signature as DfpServiceSignature;
            String version = dfpSignature.Version;

            if (dfpConfig.AuthorizationMethod == DfpAuthorizationMethod.ClientLogin &&
                version.CompareTo(FINAL_CLIENT_LOGIN_VERSION) > 0)
            {
                throw new DfpException(string.Format(DfpErrorMessages.ClientLoginNotSupported, version));
            }
        }
        /// <summary>
        /// Create a service object.
        /// </summary>
        /// <param name="signature">Signature of the service being created.</param>
        /// <param name="user">The user for which the service is being created.
        /// <param name="serverUrl">The server to which the API calls should be
        /// made.</param>
        /// </param>
        /// <returns>An object of the desired service type.</returns>
        public override AdsClient CreateService(ServiceSignature signature, AdsUser user,
                                                Uri serverUrl)
        {
            DfpAppConfig dfpConfig = (DfpAppConfig)Config;

            if (serverUrl == null)
            {
                serverUrl = new Uri(dfpConfig.DfpApiServer);
            }

            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            CheckServicePreconditions(signature);

            DfpServiceSignature dfpapiSignature = signature as DfpServiceSignature;
            EndpointAddress     endpoint        = new EndpointAddress(string.Format(ENDPOINT_TEMPLATE,
                                                                                    serverUrl, dfpapiSignature.Version, dfpapiSignature.ServiceName));

            // Create the binding for the service
            BasicHttpBinding binding = new BasicHttpBinding();

            binding.Security.Mode = BasicHttpSecurityMode.Transport;
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
            binding.MaxReceivedMessageSize = int.MaxValue;
            binding.TextEncoding           = Encoding.UTF8;

            AdsClient service = (AdsClient)Activator.CreateInstance(
                dfpapiSignature.ServiceType,
                new object[] { binding, endpoint });

            ServiceEndpoint serviceEndpoint =
                (ServiceEndpoint)service.GetType().GetProperty("Endpoint").GetValue(service, null);

            AdsServiceInspectorBehavior inspectorBehavior = new AdsServiceInspectorBehavior();

            inspectorBehavior.Add(new OAuth2ClientMessageInspector(user.OAuthProvider));

            RequestHeader clonedHeader = (RequestHeader)requestHeader.Clone();

            clonedHeader.Version = dfpapiSignature.Version;
            inspectorBehavior.Add(new DfpSoapHeaderInspector()
            {
                RequestHeader = clonedHeader,
                Config        = dfpConfig
            });
            inspectorBehavior.Add(new SoapListenerInspector(user, dfpapiSignature.ServiceName));
            inspectorBehavior.Add(new SoapFaultInspector <DfpApiException>()
            {
                ErrorType = dfpapiSignature.ServiceType.Assembly.GetType(
                    dfpapiSignature.ServiceType.Namespace + ".ApiException"),
            });
#if NET452
            serviceEndpoint.Behaviors.Add(inspectorBehavior);
#else
            serviceEndpoint.EndpointBehaviors.Add(inspectorBehavior);
#endif

            if (dfpConfig.Proxy != null)
            {
                service.Proxy = dfpConfig.Proxy;
            }
            service.EnableDecompression = dfpConfig.EnableGzipCompression;
            service.Timeout             = dfpConfig.Timeout;
            service.UserAgent           = dfpConfig.GetUserAgent();

            service.Signature = signature;
            service.User      = user;
            return(service);
        }
 private void ConfigureForClientLogin() {
   DfpAppConfig config = new DfpAppConfig();
   config.AuthorizationMethod = DfpAuthorizationMethod.ClientLogin;
   serviceFactory.Config = config;
 }
 private void ConfigureForOAuth2() {
   DfpAppConfig config = new DfpAppConfig();
   config.AuthorizationMethod = DfpAuthorizationMethod.OAuth2;
   serviceFactory.Config = config;
 }
 /// <summary>
 /// Public constructor. Use this version if you want to construct
 /// a DfpUser with a custom configuration.
 /// </summary>
 public DfpUser(DfpAppConfig config)
     : base(config)
 {
 }