Beispiel #1
0
        private void ConfigureForOAuth2()
        {
            DfpAppConfig config = new DfpAppConfig();

            config.AuthorizationMethod = DfpAuthorizationMethod.OAuth2;
            serviceFactory.Config      = config;
        }
Beispiel #2
0
        private void ConfigureForClientLogin()
        {
            DfpAppConfig config = new DfpAppConfig();

            config.AuthorizationMethod = DfpAuthorizationMethod.ClientLogin;
            serviceFactory.Config      = config;
        }
Beispiel #3
0
        /// <summary>
        /// The main method.
        /// </summary>
        /// <param name="args">Command line arguments.</param>
        static void Main(string[] args)
        {
            DfpUser      user   = new DfpUser();
            DfpAppConfig config = (user.Config as DfpAppConfig);

            if (config.AuthorizationMethod == DfpAuthorizationMethod.OAuth2)
            {
                if (config.OAuth2Mode == OAuth2Flow.APPLICATION &&
                    string.IsNullOrEmpty(config.OAuth2RefreshToken))
                {
                    DoAuth2Authorization(user);
                }
            }
            else
            {
                throw new Exception("Authorization mode is not OAuth.");
            }

            // Get the UserService.
            UserService userService = (UserService)user.GetService(DfpService.v201802.UserService);

            // Create a Statement to get all users.
            StatementBuilder statementBuilder = new StatementBuilder().OrderBy("id ASC")
                                                .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);

            // Sets defaults for page and Statement.
            UserPage page = new UserPage();

            try
            {
                do
                {
                    // Get users by Statement.
                    page = userService.getUsersByStatement(statementBuilder.ToStatement());

                    if (page.results != null && page.results.Length > 0)
                    {
                        int i = page.startIndex;
                        foreach (User usr in page.results)
                        {
                            Console.WriteLine(
                                "{0}) User with ID = '{1}', email = '{2}', and role = '{3}'" +
                                " was found.", i, usr.id, usr.email, usr.roleName);
                            i++;
                        }
                    }

                    statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                } while (statementBuilder.GetOffset() < page.totalResultSetSize);

                Console.WriteLine("Number of results found: {0}", page.totalResultSetSize);
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to get all users. Exception says \"{0}\"", e.Message);
            }
        }
Beispiel #4
0
        /// <summary>
        /// Builds an HTTP request for downloading reports.
        /// </summary>
        /// <param name="downloadUrl">The download url.</param>
        /// <returns></returns>
        private HttpWebRequest BuildRequest(string downloadUrl)
        {
            DfpAppConfig   config  = this.reportService.User.Config as DfpAppConfig;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(downloadUrl);

            request.Method    = "GET";
            request.Proxy     = config.Proxy;
            request.Timeout   = config.Timeout;
            request.UserAgent = config.GetUserAgent();
            return(request);
        }
        public void Init()
        {
            listener = DfpTraceListener.Instance;

            // Set static values for testing
            DfpAppConfig config = (DfpAppConfig)listener.Config;

            config.GetType().GetProperty("NetworkCode").SetValue(config, TestNetwodeCode, null);
            config.GetType().GetProperty("MaskCredentials").SetValue(config, true, null);

            ((TraceListener)listener).DateTimeProvider = new MockDateTimeProvider();
        }
Beispiel #6
0
        /// <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);
                }
            }
        }
Beispiel #7
0
        private void ConfigureUserForOAuth()
        {
            DfpAppConfig config = (user.Config as DfpAppConfig);

            if (config.AuthorizationMethod == DfpAuthorizationMethod.OAuth2)
            {
                if (config.OAuth2Mode == OAuth2Flow.APPLICATION &&
                    string.IsNullOrEmpty(config.OAuth2RefreshToken))
                {
                    user.OAuthProvider = (OAuth2ProviderForApplications)Session["OAuthProvider"];
                }
            }
            else
            {
                throw new Exception("Authorization mode is not OAuth.");
            }
        }
        public void TestValidHeaderApplied()
        {
            DfpSoapHeaderInspector inspector = new DfpSoapHeaderInspector();
            RequestHeader          header    = new RequestHeader()
            {
                networkCode = "12345",
            };
            DfpAppConfig config = new DfpAppConfig();

            config.ApplicationName  = "Unit test application";
            inspector.Config        = config;
            inspector.RequestHeader = (RequestHeader)header.Clone();
            inspector.BeforeSendRequest(ref this.message, this.channel);
            Assert.AreEqual(1, this.message.Headers.Count);
            foreach (RequestHeader appliedHeader in this.message.Headers)
            {
                Assert.AreEqual("12345", appliedHeader.networkCode);
                Assert.AreEqual(config.GetUserAgent(), appliedHeader.applicationName);
            }
        }
        /// <summary>
        /// Handles the Click event of the btnAuthorize 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 OnAuthorizeButtonClick(object sender, EventArgs e)
        {
            // This code example shows how to run an DFP API web application
            // while incorporating the OAuth2 web application flow into your
            // application. If your application uses a single Google login to make calls
            // to all your accounts, you shouldn't use this code example. Instead, you
            // should run Common\Util\OAuth2TokenGenerator.cs to generate a refresh
            // token and set that in user.Config.OAuth2RefreshToken field, or set
            // OAuth2RefreshToken key in your App.config / Web.config.
            DfpAppConfig config = user.Config as DfpAppConfig;

            if (config.AuthorizationMethod == DfpAuthorizationMethod.OAuth2)
            {
                if (user.Config.OAuth2Mode == OAuth2Flow.APPLICATION &&
                    string.IsNullOrEmpty(config.OAuth2RefreshToken))
                {
                    Response.Redirect("OAuthLogin.aspx");
                }
            }
            else
            {
                throw new Exception("Authorization mode is not OAuth.");
            }
        }
Beispiel #10
0
        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.");
            }
        }