Example #1
0
        public static void TestToken()
        {
            ApiEnvironment apiEnv = new ApiEnvironment();

            apiEnv.init(APIUrl, APICode);
            if (string.IsNullOrEmpty(apiEnv.Token))
            {
                Thread.Sleep(2000);
            }
        }
Example #2
0
        public static void EnsureInitialized(TogglPresenter viewPresenter, ApiEnvironment environment, Platform platform, string version)
        {
            if (Instance != null)
            {
                return;
            }

            Instance = new IosDependencyContainer(viewPresenter, environment, platform, version);
            UIDependencyContainer.Instance = Instance;
        }
        public static void EnsureInitialized(ApiEnvironment environment, Platform platform, string version)
        {
            if (Instance != null)
            {
                return;
            }

            Instance = new AndroidDependencyContainer(environment, platform, version);
            UIDependencyContainer.Instance = Instance;
        }
Example #4
0
        protected DependencyContainer(ApiEnvironment apiEnvironment, UserAgent userAgent)
        {
            this.userAgent = userAgent;

            ApiEnvironment = apiEnvironment;

            database                    = new Lazy <ITogglDatabase>(CreateDatabase);
            apiFactory                  = new Lazy <IApiFactory>(CreateApiFactory);
            syncManager                 = new Lazy <ISyncManager>(CreateSyncManager);
            timeService                 = new Lazy <ITimeService>(CreateTimeService);
            dataSource                  = new Lazy <ITogglDataSource>(CreateDataSource);
            platformInfo                = new Lazy <IPlatformInfo>(CreatePlatformInfo);
            googleService               = new Lazy <IGoogleService>(CreateGoogleService);
            ratingService               = new Lazy <IRatingService>(CreateRatingService);
            calendarService             = new Lazy <ICalendarService>(CreateCalendarService);
            keyValueStorage             = new Lazy <IKeyValueStorage>(CreateKeyValueStorage);
            licenseProvider             = new Lazy <ILicenseProvider>(CreateLicenseProvider);
            rxActionFactory             = new Lazy <IRxActionFactory>(CreateRxActionFactory);
            userPreferences             = new Lazy <IUserPreferences>(CreateUserPreferences);
            analyticsService            = new Lazy <IAnalyticsService>(CreateAnalyticsService);
            backgroundService           = new Lazy <IBackgroundService>(CreateBackgroundService);
            interactorFactory           = new Lazy <IInteractorFactory>(CreateInteractorFactory);
            onboardingStorage           = new Lazy <IOnboardingStorage>(CreateOnboardingStorage);
            schedulerProvider           = new Lazy <ISchedulerProvider>(CreateSchedulerProvider);
            stopwatchProvider           = new Lazy <IStopwatchProvider>(CreateStopwatchProvider);
            shortcutCreator             = new Lazy <IApplicationShortcutCreator>(CreateShortcutCreator);
            notificationService         = new Lazy <INotificationService>(CreateNotificationService);
            remoteConfigService         = new Lazy <IRemoteConfigService>(CreateRemoteConfigService);
            errorHandlingService        = new Lazy <IErrorHandlingService>(CreateErrorHandlingService);
            lastTimeUsageStorage        = new Lazy <ILastTimeUsageStorage>(CreateLastTimeUsageStorage);
            backgroundSyncService       = new Lazy <IBackgroundSyncService>(CreateBackgroundSyncService);
            intentDonationService       = new Lazy <IIntentDonationService>(CreateIntentDonationService);
            automaticSyncingService     = new Lazy <IAutomaticSyncingService>(CreateAutomaticSyncingService);
            accessRestrictionStorage    = new Lazy <IAccessRestrictionStorage>(CreateAccessRestrictionStorage);
            syncErrorHandlingService    = new Lazy <ISyncErrorHandlingService>(CreateSyncErrorHandlingService);
            privateSharedStorageService = new Lazy <IPrivateSharedStorageService>(CreatePrivateSharedStorageService);
            suggestionProviderContainer = new Lazy <ISuggestionProviderContainer>(CreateSuggestionProviderContainer);

            api = apiFactory.Select(factory => factory.CreateApiWith(Credentials.None));
            UserAccessManager = new UserAccessManager(
                apiFactory,
                database,
                googleService,
                privateSharedStorageService);

            UserAccessManager
            .UserLoggedIn
            .Subscribe(recreateLazyDependenciesForLogin)
            .DisposedBy(disposeBag);

            UserAccessManager
            .UserLoggedOut
            .Subscribe(_ => recreateLazyDependenciesForLogout())
            .DisposedBy(disposeBag);
        }
        public static string GetScenesAPIUrl(ApiEnvironment env, int x1, int y1, int width, int height)
        {
            width  = Mathf.Max(0, width - 1);
            height = Mathf.Max(0, height - 1);

            string baseUrl = GetBaseUrl(env);
            string result  = $"{baseUrl}/scenes?x1={x1}&x2={x1 + width}&y1={y1}&y2={y1 + height}";

            Debug.Log($"Using scenes API url {result}");
            return(result);
        }
Example #6
0
        /// <summary>
        /// Utility method for setting the customer and account identifiers within the global
        /// <see cref="_authorizationData"/> instance.
        /// </summary>
        /// <param name="authentication">The OAuth authentication credentials.</param>
        /// <returns></returns>
        private static async Task SetAuthorizationDataAsync(Authentication authentication)
        {
            _authorizationData = new AuthorizationData
            {
                Authentication = authentication,
                DeveloperToken = Settings.Default["DeveloperToken"].ToString()
            };

            ApiEnvironment environment = ((OAuthDesktopMobileAuthCodeGrant)_authorizationData.Authentication).Environment;

            BingAdsExamplesLibrary.V12.CustomerManagementExampleHelper CustomerManagementExampleHelper =
                new BingAdsExamplesLibrary.V12.CustomerManagementExampleHelper(null);
            CustomerManagementExampleHelper.CustomerManagementService =
                new ServiceClient <ICustomerManagementService>(_authorizationData, environment);

            var getUserResponse = await CustomerManagementExampleHelper.GetUserAsync(null, true);

            var user = getUserResponse.User;

            var predicate = new Predicate
            {
                Field    = "UserId",
                Operator = PredicateOperator.Equals,
                Value    = user.Id.ToString()
            };

            var paging = new Paging
            {
                Index = 0,
                Size  = 10
            };

            var request = new SearchAccountsRequest
            {
                Ordering   = null,
                PageInfo   = paging,
                Predicates = new[] { predicate }
            };

            var accounts = (await CustomerManagementExampleHelper.SearchAccountsAsync(
                                new[] { predicate },
                                null,
                                paging)).Accounts.ToArray();

            if (accounts.Length <= 0)
            {
                return;
            }

            _authorizationData.AccountId  = (long)accounts[0].Id;
            _authorizationData.CustomerId = (int)accounts[0].ParentCustomerId;

            return;
        }
Example #7
0
        public static void RegisterSwaggerInStartup(string solutionDirectory, ApiEnvironment env, string projectBaseName = "")
        {
            try
            {
                var classPath = ClassPathHelper.StartupClassPath(solutionDirectory, $"{Utilities.GetStartupName(env.EnvironmentName)}.cs", projectBaseName);

                if (!Directory.Exists(classPath.ClassDirectory))
                {
                    throw new DirectoryNotFoundException($"The `{classPath.ClassDirectory}` directory could not be found.");
                }

                if (!File.Exists(classPath.FullClassPath))
                {
                    throw new FileNotFoundException($"The `{classPath.FullClassPath}` file could not be found.");
                }

                var tempPath = $"{classPath.FullClassPath}temp";
                using (var input = File.OpenText(classPath.FullClassPath))
                {
                    using (var output = new StreamWriter(tempPath))
                    {
                        string line;
                        while (null != (line = input.ReadLine()))
                        {
                            var newText = $"{line}";
                            if (line.Contains("Dynamic Services"))
                            {
                                newText += $"{Environment.NewLine}            services.AddSwaggerExtension(_config);";
                            }
                            else if (line.Contains("Dynamic App"))
                            {
                                newText += $"{Environment.NewLine}            app.UseSwaggerExtension(_config);";
                            }

                            output.WriteLine(newText);
                        }
                    }
                }

                // delete the old file and set the name of the new one to the original name
                File.Delete(classPath.FullClassPath);
                File.Move(tempPath, classPath.FullClassPath);
            }
            catch (FileAlreadyExistsException e)
            {
                WriteError(e.Message);
                throw;
            }
            catch (Exception e)
            {
                WriteError($"An unhandled exception occurred when running the API command.\nThe error details are: \n{e.Message}");
                throw;
            }
        }
 internal OAuthWebAuthCodeGrant(
     string clientId,
     string clientSecret,
     Uri redirectionUri,
     IOAuthService oauthService,
     ApiEnvironment env,
     bool requireLiveConnect,
     string tenant = "common")
     : base(clientId, clientSecret, redirectionUri, oauthService, env, requireLiveConnect, tenant)
 {
 }
Example #9
0
 /// <summary>
 /// Checks the environment and base address for validity
 /// </summary>
 /// <param name="environment"></param>
 /// <param name="apiBaseAddress"></param>
 private void ValidateEnvironment(ApiEnvironment environment, string apiBaseAddress)
 {
     if (environment == ApiEnvironment.Dev && string.IsNullOrWhiteSpace(apiBaseAddress))
     {
         throw new ArgumentNullException("When targeting Local, you must provide an apiBaseAddress", nameof(apiBaseAddress));
     }
     else if (environment == ApiEnvironment.Dev && !apiBaseAddress.EndsWith("/"))
     {
         throw new ArgumentException("apiBaseAddress must end with a trailing slash.", nameof(apiBaseAddress));
     }
 }
        private static string GetAppSettingsText(ApiEnvironment env, string dbName)
        {
            var jwtSettings     = GetJwtAuthSettings(env);
            var serilogSettings = GetSerilogSettings(env.EnvironmentName);

            if (env.EnvironmentName == "Development" || env.EnvironmentName == "FunctionalTesting")
            {
                return(@$ "{{
  " "AllowedHosts" ": " "*" ",
  " "UseInMemoryDatabase" ": true,
{serilogSettings}{jwtSettings}
}}
Example #11
0
 public static string GetBaseUrl(ApiEnvironment env)
 {
     if (env != ApiEnvironment.NONE)
     {
         string envString = GetEnvString(env);
         return($"https://content.decentraland.{envString}");
     }
     else
     {
         return(customBaseUrl);
     }
 }
Example #12
0
        public static void AddStartupEnvironmentsWithServices(
            string solutionDirectory,
            string solutionName,
            string dbName,
            List <ApiEnvironment> environments,
            SwaggerConfig swaggerConfig,
            int port,
            bool useJwtAuth,
            string projectBaseName = "")
        {
            // add a development environment by default for local work if none exists
            if (environments.Where(e => e.EnvironmentName == "Development").Count() == 0)
            {
                environments.Add(new ApiEnvironment {
                    EnvironmentName = "Development", ProfileName = $"{solutionName} (Development)"
                });
            }

            if (environments.Where(e => e.EnvironmentName == "Production").Count() == 0)
            {
                environments.Add(new ApiEnvironment {
                    EnvironmentName = "Production", ProfileName = $"{solutionName} (Production)"
                });
            }

            var sortedEnvironments = environments.OrderBy(e => e.EnvironmentName == "Development" ? 1 : 0).ToList(); // sets dev as default profile

            foreach (var env in sortedEnvironments)
            {
                // default startup is already built in cleanup phase
                if (env.EnvironmentName != "Production")
                {
                    StartupBuilder.CreateWebApiStartup(solutionDirectory, env.EnvironmentName, useJwtAuth, projectBaseName);
                }

                WebApiAppSettingsBuilder.CreateAppSettings(solutionDirectory, env, dbName, projectBaseName);
                WebApiLaunchSettingsModifier.AddProfile(solutionDirectory, env, port, projectBaseName);

                //services
                if (!swaggerConfig.IsSameOrEqualTo(new SwaggerConfig()))
                {
                    SwaggerBuilder.RegisterSwaggerInStartup(solutionDirectory, env, projectBaseName);
                }
            }

            // add an integration testing env to make sure that an in memory database is used
            var functionalEnv = new ApiEnvironment()
            {
                EnvironmentName = "FunctionalTesting"
            };

            WebApiAppSettingsBuilder.CreateAppSettings(solutionDirectory, functionalEnv, "", projectBaseName);
        }
Example #13
0
        public async Task <AuthorizationData> SetAuthorizationDataAsync(Authentication authentication)
        {
            _authorizationData = new AuthorizationData
            {
                Authentication = authentication,
                DeveloperToken = (DeveloperToken != null) ? DeveloperToken : null
            };


            ApiEnvironment environment = ((OAuthWebAuthCodeGrant)_authorizationData.Authentication).Environment;

            CustomerManagementExampleHelper CustomerManagementExampleHelper =
                new CustomerManagementExampleHelper(null);

            CustomerManagementExampleHelper.CustomerManagementService =
                new ServiceClient <ICustomerManagementService>(_authorizationData, environment);


            var getUserResponse = await CustomerManagementExampleHelper.GetUserAsync(null, true);

            var user = getUserResponse.User;

            var predicate = new Predicate
            {
                Field    = "UserId",
                Operator = PredicateOperator.Equals,
                Value    = user.Id.ToString()
            };

            var paging = new Paging
            {
                Index = 0,
                Size  = 10
            };


            var accounts = (await CustomerManagementExampleHelper.SearchAccountsAsync(
                                new[] { predicate },
                                null,
                                paging)).Accounts.ToArray();

            //var accounts = await SearchAccountsByUserIdAsync(user.Id);
            if (accounts.Length <= 0)
            {
                return(null);
            }

            _authorizationData.AccountId  = (long)accounts[0].Id;
            _authorizationData.CustomerId = (int)accounts[0].ParentCustomerId;

            return(_authorizationData);
        }
Example #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="apiEndpoint"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static HttpDecorator.HttpResponseResult HttpPost(string apiEndpoint, string postData)
        {
            var httpDecorator = new HttpDecorator();
            var headers       = new Dictionary <string, string>();

            headers.Add(JXTokenKey, AuthToken);
            headers.Add(JXDeviceKey, DeviceKey);
            var remoteApiEndpoint = ApiEnvironment.GetApiEndpoint(apiEndpoint);
            var responseResult    = httpDecorator.HttpPost(remoteApiEndpoint, postData, headers);

            Console.WriteLine("[POST]{0}", remoteApiEndpoint);
            return(responseResult);
        }
     private static string GetProfileText(ApiEnvironment env, int port)
     {
         return($@"
 ""{env.ProfileName ?? env.EnvironmentName ?? "Development"}"": {{
   ""commandName"": ""Project"",
   ""launchBrowser"": true,
   ""launchUrl"": ""swagger"",
   ""environmentVariables"": {{
     ""ASPNETCORE_ENVIRONMENT"": ""{env.EnvironmentName}""
   }},
   ""applicationUrl"": ""https://localhost:{port}""
 }},");
     }
Example #16
0
        public IChannelFactory <TClient> CreateChannelFactory <TClient>(ApiEnvironment env)
            where TClient : class
        {
            var endpoint = GetEndpointFromConfiguration(typeof(TClient));

            var factory = endpoint != null
                ? CreateChannelFactoryForCustomEndpoint <TClient>(endpoint)
                : CreateChannelFactoryForStandardEndpoint <TClient>(env);

            factory.Endpoint.Behaviors.Add(new UserAgentBehavior());

            return(factory);
        }
Example #17
0
        public static Foundation Create(
            string clientName,
            string version,
            ITogglDatabase database,
            ITimeService timeService,
            IScheduler scheduler,
            IMailService mailService,
            IGoogleService googleService,
            ApiEnvironment apiEnvironment,
            ILicenseProvider licenseProvider,
            IAnalyticsService analyticsService,
            IPlatformConstants platformConstants,
            IApplicationShortcutCreator shortcutCreator,
            ISuggestionProviderContainer suggestionProviderContainer)
        {
            Ensure.Argument.IsNotNull(version, nameof(version));
            Ensure.Argument.IsNotNull(database, nameof(database));
            Ensure.Argument.IsNotNull(clientName, nameof(clientName));
            Ensure.Argument.IsNotNull(timeService, nameof(timeService));
            Ensure.Argument.IsNotNull(scheduler, nameof(scheduler));
            Ensure.Argument.IsNotNull(mailService, nameof(mailService));
            Ensure.Argument.IsNotNull(googleService, nameof(googleService));
            Ensure.Argument.IsNotNull(licenseProvider, nameof(licenseProvider));
            Ensure.Argument.IsNotNull(shortcutCreator, nameof(shortcutCreator));
            Ensure.Argument.IsNotNull(analyticsService, nameof(analyticsService));
            Ensure.Argument.IsNotNull(platformConstants, nameof(platformConstants));
            Ensure.Argument.IsNotNull(suggestionProviderContainer, nameof(suggestionProviderContainer));

            var userAgent = new UserAgent(clientName, version.ToString());

            var foundation = new Foundation
            {
                Database                    = database,
                UserAgent                   = userAgent,
                TimeService                 = timeService,
                Scheduler                   = scheduler,
                MailService                 = mailService,
                GoogleService               = googleService,
                ApiEnvironment              = apiEnvironment,
                LicenseProvider             = licenseProvider,
                Version                     = Version.Parse(version),
                ShortcutCreator             = shortcutCreator,
                AnalyticsService            = analyticsService,
                PlatformConstants           = platformConstants,
                BackgroundService           = new BackgroundService(timeService),
                ApiFactory                  = new ApiFactory(apiEnvironment, userAgent),
                SuggestionProviderContainer = suggestionProviderContainer
            };

            return(foundation);
        }
Example #18
0
        private static OAuthEndpointType GetOAuthEndpointType(ApiEnvironment env, bool requireLiveConnect)
        {
            OAuthEndpointType endpointType;

            if (env == ApiEnvironment.Production)
            {
                endpointType = requireLiveConnect ? OAuthEndpointType.ProductionLiveConnect : OAuthEndpointType.ProductionMSIdentityV2;
            }
            else
            {
                endpointType = OAuthEndpointType.SandboxLiveConnect;
            }
            return(endpointType);
        }
Example #19
0
        private static Uri forEnvironment(ApiEnvironment environment, string prefix)
        {
            switch (environment)
            {
            case ApiEnvironment.Staging:
                return(new Uri(stagingBaseUrl, prefix));

            case ApiEnvironment.Production:
                return(new Uri(productionBaseUrl, prefix));

            default:
                throw new ArgumentOutOfRangeException(nameof(environment), environment, "Unknown api environment.");
            }
        }
        public void TestCheck(string APIUrl, string APICode)
        {
            ApiEnvironment apiEnv = new ApiEnvironment();

            apiEnv.init(APIUrl, APICode);
            string          loginUrl  = APIUrl + "Bill1002535/CheckBill?Token=" + apiEnv.Token;
            string          json      = " { \"data\": {   \"FBillNo\": \"ECN002350\"   }   }";
            string          htmlCode  = "";
            HttpWebResponse response  = HttpWebResponseUtility.CreatePostHttpResponse(loginUrl, json, null, null, Encoding.UTF8, null);
            Stream          resStream = response.GetResponseStream();
            StreamReader    sr        = new StreamReader(resStream, Encoding.UTF8);

            htmlCode = sr.ReadToEnd();//获取返回JSON
        }
Example #21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="apiEndpoint"></param>
        /// <param name="requestData"></param>
        /// <returns></returns>
        public static HttpDecorator.HttpResponseResult HttpGet(string apiEndpoint, IList <KeyValuePair <string, object> > requestData)
        {
            var httpDecorator = new HttpDecorator();
            var headers       = new Dictionary <string, string>();

            headers.Add(JXTokenKey, AuthToken);
            headers.Add(JXDeviceKey, DeviceKey);
            var remoteApiEndpoint = ApiEnvironment.GetApiEndpoint(apiEndpoint);

            remoteApiEndpoint = HttpDecorator.CombineRequest(remoteApiEndpoint, requestData);
            var responseResult = httpDecorator.HttpGet(remoteApiEndpoint, headers);

            Console.WriteLine("[GET]{0}", remoteApiEndpoint);
            return(responseResult);
        }
Example #22
0
        public static Uri GetAuthorizationEndpoint(OAuthUrlParameters parameters, ApiEnvironment env, bool requireLiveConnect, string tenant)
        {
            OAuthEndpointType endpointType = GetOAuthEndpointType(env, requireLiveConnect);

            var authorizationEndpointUrl = EndpointUrls[endpointType].AuthorizationEndpointUrl;

            if (endpointType == OAuthEndpointType.ProductionMSIdentityV2 && !(string.IsNullOrEmpty(tenant)))
            {
                authorizationEndpointUrl = authorizationEndpointUrl.Replace("common", tenant);
            }
            return(new Uri(string.Format(
                               authorizationEndpointUrl,
                               parameters.ClientId,
                               parameters.ResponseType,
                               parameters.RedirectUri) + (string.IsNullOrEmpty(parameters.State) ? "" : string.Format("&state={0}", parameters.State))));
        }
 public string GetUrl(ApiEnvironment environment)
 {
     switch (environment)
     {
         case ApiEnvironment.Sandbox:
             if (SandboxUrl == null)
             {
                 throw new InvalidOperationException("The service is not available in Sandbox");
             }
             return SandboxUrl;
         case ApiEnvironment.Production:
             return ProductionUrl;
         default:
             throw new ArgumentException("invalid environment name", "environment");
     }
 }
Example #24
0
        public string GetApiEndpointUrl(
            ApiEnvironment environment,
            bool apiManagement)
        {
            if (apiManagement)
            {
                switch (environment)
                {
                case ApiEnvironment.DEVELOPMENT:
                    return
                        (Protocol + "://" + Endpoint + "-dev.contidio.com:" + Port);

                case ApiEnvironment.STAGING:
                    return
                        (Protocol + "://" + Endpoint + "-staging.contidio.com:" + Port);

                case ApiEnvironment.DEMO:
                    return
                        (Protocol + "://" + Endpoint + "-demo.contidio.com");

                default:
                    return
                        (Protocol + "://" + Endpoint + ".contidio.com");
                }
            }
            else
            {
                switch (environment)
                {
                case ApiEnvironment.DEVELOPMENT:
                    return
                        (Protocol + "://" + Endpoint + "-dev.contidio.com:" + Port);

                case ApiEnvironment.STAGING:
                    return
                        (Protocol + "://" + Endpoint + "-staging.contidio.com:" + Port);

                case ApiEnvironment.DEMO:
                    return
                        (Protocol + "://" + Endpoint + "-demo.contidio.com");

                default:
                    return
                        (Protocol + "://" + Endpoint + ".contidio.com");
                }
            }
        }
Example #25
0
        public string GetUrl(ApiEnvironment environment)
        {
            switch (environment)
            {
            case ApiEnvironment.Sandbox:
                if (SandboxUrl == null)
                {
                    throw new InvalidOperationException("The service is not available in Sandbox");
                }
                return(SandboxUrl);

            case ApiEnvironment.Production:
                return(ProductionUrl);

            default:
                throw new ArgumentException("invalid environment name", "environment");
            }
        }
Example #26
0
        private void DetectApiEnvironment(AuthorizationData authorizationData, ApiEnvironment?environment)
        {
            var oauth = authorizationData.Authentication as OAuthAuthorization;

            if (oauth != null)
            {
                environment = oauth.Environment;
            }

            if (environment == null)
            {
                _environment = ApiEnvironment.Production;
            }
            else
            {
                _environment = environment.Value;
            }
        }
        /// <summary>
        /// Initializes a new instance of the OAuthAuthorization class with the specified <paramref name="clientId"/>.
        /// </summary>
        /// <param name="clientId">
        /// The client identifier corresponding to your registered application.
        /// </param>
        /// <param name="environment">Bing Ads API environment</param>
        /// <remarks>
        /// For more information about using a client identifier for authentication, see <see href="https://tools.ietf.org/html/rfc6749#section-3.1">Client Password Authentication section of the OAuth 2.0 spec</see>.
        /// </remarks>
        protected OAuthAuthorization(string clientId, ApiEnvironment?environment)
        {
            if (clientId == null)
            {
                throw new ArgumentNullException("clientId");
            }

            ClientId = clientId;

            if (environment == null)
            {
                _environment = ApiEnvironment.Production;
            }
            else
            {
                _environment = environment.Value;
            }
        }
Example #28
0
        public static void AddRmq(string solutionDirectory, ApiEnvironment env, string projectBaseName, IFileSystem fileSystem)
        {
            var appSettingFilename = Utilities.GetAppSettingsName();
            var classPath          = ClassPathHelper.WebApiAppSettingsClassPath(solutionDirectory, $"{appSettingFilename}", projectBaseName);

            if (!fileSystem.Directory.Exists(classPath.ClassDirectory))
            {
                fileSystem.Directory.CreateDirectory(classPath.ClassDirectory);
            }

            if (!fileSystem.File.Exists(classPath.FullClassPath))
            {
                throw new FileNotFoundException($"The `{classPath.FullClassPath}` file could not be found.");
            }

            List <string> lines = File.ReadAllLines(classPath.FullClassPath).ToList();

            lines[^ 2] = lines[^ 2].Replace(",", "") + GetRmqText(env); // lines[^2] == lines[lines.Count - 2]
Example #29
0
        internal OAuthWithAuthorizationCode(
            string clientId,
            string clientSecret,
            Uri redirectionUri,
            IOAuthService oauthService,
            ApiEnvironment env,
            bool requireLiveConnect)
            : base(clientId, env, requireLiveConnect)
        {
            if (redirectionUri == null)
            {
                throw new ArgumentNullException("redirectionUri");
            }

            _optionalClientSecret = clientSecret;
            _redirectionUri       = redirectionUri;
            _oauthService         = oauthService;
        }
Example #30
0
        public static string GetEnvString(ApiEnvironment env)
        {
            switch (env)
            {
            case ApiEnvironment.NONE:
                break;

            case ApiEnvironment.TODAY:
                return("today");

            case ApiEnvironment.ZONE:
                return("zone");

            case ApiEnvironment.ORG:
                return("org");
            }

            return("org");
        }
        /// <summary>
        /// ctor for AuthenticationTokenFactory
        /// </summary>
        /// <param name="applicationClientId">ClientId for AAD application that accesses BingAdsApi</param>
        /// <param name="usernameLoginHint">Username LoginHint to retrieve matching AccessToken from TokenCache</param>
        /// <param name="tokenCacheCorrelationId">
        ///   Used to identify persisted TokenCache location.
        ///   Provide a consistent non-null value across sessions for access to the same persisted cache.
        ///   If app must not need TokenCache persistence, just pass in null.
        /// </param>
        /// <param name="acesssTokenExpirationOffsetInSec">
        ///   Specifies when a new Token will be refreshed silently, based on AccessToken's expiresOn property.
        ///   If AccessToken.ExpiresOn = "09:30" and offset = "-600",
        ///     then call to fetch accessToken after "09:20" will try to get a refreshed accessToken.
        /// </param>
        /// <param name="apiEnvironment"></param>
        public AuthenticationTokenFactory(
            string applicationClientId,
            string usernameLoginHint             = null,
            string tokenCacheCorrelationId       = null,
            int acesssTokenExpirationOffsetInSec = Config.DefaultAccessTokenExpirationOffsetInSec,
            ApiEnvironment apiEnvironment        = ApiEnvironment.Production)
        {
            if (string.IsNullOrWhiteSpace(applicationClientId))
            {
                throw new ArgumentNullException(nameof(applicationClientId));
            }
            if (acesssTokenExpirationOffsetInSec > 0)
            {
                throw new ArgumentException($"value of {nameof(acesssTokenExpirationOffsetInSec)} must be negative");
            }

            this.apiEnvironment    = apiEnvironment;
            this.usernameLoginHint = usernameLoginHint;
            this.acesssTokenExpirationOffsetInSec = acesssTokenExpirationOffsetInSec;

            // create IPublicClientApplication for accessing BingAdsApi
            application = PublicClientApplicationBuilder.Create(applicationClientId)
                          .WithRedirectUri(Config.RedirectUri[apiEnvironment])
                          .Build();

            // try load TokenCache from persisted file storage
            if (tokenCacheCorrelationId != null)
            {
                var cacheFileName = $".msalcache.{tokenCacheCorrelationId}";
                Logger.Verbose($"TokenCache persistence at {Config.DefaultTokenCacheFileLocation}\\{cacheFileName}");

                var cacheStorageInfo = new StorageCreationPropertiesBuilder(
                    cacheFileName,
                    Config.DefaultTokenCacheFileLocation,
                    applicationClientId)
                                       .Build();

                var cacheHelper = MsalCacheHelper.CreateAsync(cacheStorageInfo).Result;

                cacheHelper.RegisterCache(application.UserTokenCache);
            }
        }
        /// <summary>
        /// Initializes a new instance of this class with the specified <see cref="AuthorizationData"/> and <paramref name="apiEnvironment"/>.
        /// </summary>
        /// <param name="authorizationData">Represents a user who intends to access the corresponding customer and account. </param>
        /// <param name="apiEnvironment">Bing Ads API environment</param>
        public ReportingServiceManager(AuthorizationData authorizationData, ApiEnvironment? apiEnvironment)
        {
            if (authorizationData == null)
            {
                throw new ArgumentNullException("authorizationData");
            }

            _authorizationData = authorizationData;

            HttpService = new HttpService();

            ZipExtractor = new ZipExtractor();

            FileSystem = new FileSystem();

            StatusPollIntervalInMilliseconds = DefaultStatusPollIntervalInMilliseconds;

            WorkingDirectory = Path.Combine(Path.GetTempPath(), "BingAdsSDK", "Reporting");

            if (apiEnvironment != null) _apiEnvironment = apiEnvironment.Value;
        }
 internal ReportingDownloadOperation(string requestId, AuthorizationData authorizationData, string trackingId, ApiEnvironment? apiEnvironment)
     : this(requestId, authorizationData, new ReportingStatusProvider(requestId), trackingId, apiEnvironment)
 {
 }
 /// <summary>
 /// Initializes a new instance of this class with the specified <paramref name="requestId"/>, <see cref="BingAds.AuthorizationData"/> and <paramref name="apiEnvironment"/>.
 /// </summary>
 /// <param name="requestId">The identifier of a download request that has previously been submitted.</param>
 /// <param name="authorizationData">
 /// Represents a user who intends to access the corresponding customer and account. 
 /// </param>
 /// <param name="apiEnvironment">Bing Ads API environment</param>
 public ReportingDownloadOperation(string requestId, AuthorizationData authorizationData, ApiEnvironment? apiEnvironment)
     : this(requestId, authorizationData, null, apiEnvironment)
 {
 }
        internal ReportingDownloadOperation(string requestId, AuthorizationData authorizationData, ReportingStatusProvider statusProvider, string trackingId, ApiEnvironment? apiEnvironment)
        {
            RequestId = requestId;

            AuthorizationData = authorizationData;

            _statusProvider = statusProvider;

            TrackingId = trackingId;

            StatusPollIntervalInMilliseconds = ReportingServiceManager.DefaultStatusPollIntervalInMilliseconds;

            _reportingServiceClient = new ServiceClient<IReportingService>(authorizationData, apiEnvironment);

            ZipExtractor = new ZipExtractor();

            HttpService = new HttpService();

            FileSystem = new FileSystem();
        }