Exemplo n.º 1
0
        static string GetDynamicsMetadata(IConfiguration Configuration)
        {
            string dynamicsOdataUri = Configuration["DYNAMICS_ODATA_URI"];

            ServiceClientCredentials serviceClientCredentials = DynamicsSetupUtil.GetServiceClientCredentials(Configuration);

            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(dynamicsOdataUri + "$metadata");

            string result = null;


            //request.Accept = "application/json;odata=verbose";
            //request.ContentType =  "application/json";
            CancellationToken cancellationToken = default(CancellationToken);

            serviceClientCredentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).GetAwaiter().GetResult();

            HttpClient httpClient = new HttpClient();

            _httpResponse = httpClient.SendAsync(_httpRequest, cancellationToken).GetAwaiter().GetResult();

            result = _httpResponse.Content.ReadAsStringAsync().GetAwaiter().GetResult();

            return(result);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Setup the Hangfire jobs.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="loggerFactory"></param>
        private void SetupHangfireJobs(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            Microsoft.Extensions.Logging.ILogger log = loggerFactory.CreateLogger(typeof(Startup));
            log.LogInformation("Starting setup of Hangfire jobs ...");

            try
            {
                using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
                {
                    log.LogInformation("Creating Hangfire job for Send Results jobs ...");
                    RecurringJob.AddOrUpdate(() => new CarlaUtils(Configuration, loggerFactory, serviceScope.ServiceProvider.GetRequiredService <FileManager>()).ProcessResults(null), "*/5 * * * *"); // Run every 5 minutes
                    // Process Results in Dynamics
                    IDynamicsClient dynamics = DynamicsSetupUtil.SetupDynamics(Configuration);
                    RecurringJob.AddOrUpdate(() => new DynamicsUtils(Configuration, loggerFactory, dynamics).ProcessBusinessResults(null), Cron.MinuteInterval(5)); // Run every 5 minutes
                    RecurringJob.AddOrUpdate(() => new DynamicsUtils(Configuration, loggerFactory, dynamics).ProcessWorkerResults(null), Cron.MinuteInterval(5));   // Run every 5 minutes
                    log.LogInformation("Hangfire Send Results jobs created.");
                }
            }
            catch (Exception e)
            {
                StringBuilder msg = new StringBuilder();
                msg.AppendLine("Failed to setup Hangfire job.");
                log.LogCritical(new EventId(-1, "Hangfire job setup failed"), e, msg.ToString());
            }
        }
Exemplo n.º 3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });


            if (!string.IsNullOrEmpty(Configuration["DYNAMICS_ODATA_URI"]))
            {
                // Add Dynamics
                services.AddTransient(new Func <IServiceProvider, IDynamicsClient>((serviceProvider) =>
                {
                    IDynamicsClient client = DynamicsSetupUtil.SetupDynamics(Configuration);
                    return(client);
                }));
            }

            if (!string.IsNullOrEmpty(Configuration["SHAREPOINT_ODATA_URI"]))
            {
                // add SharePoint.

                services.AddTransient <SharePointFileManager>(_ => new SharePointFileManager(Configuration));
            }
        }
Exemplo n.º 4
0
 public GeocodeUtils(IConfiguration Configuration, ILogger logger)
 {
     this.Configuration = Configuration;
     _dynamics          = DynamicsSetupUtil.SetupDynamics(Configuration);
     _logger            = logger;
     _geocoder          = GeocoderSetupUtil.SetupGeocoder(Configuration);
 }
Exemplo n.º 5
0
 public OneStopUtils(IConfiguration Configuration, ILogger logger)
 {
     this.Configuration = Configuration;
     _dynamics          = DynamicsSetupUtil.SetupDynamics(Configuration);
     _onestopRestClient = OneStopUtils.SetupOneStopClient(Configuration, logger);
     _logger            = logger;
 }
Exemplo n.º 6
0
        /// <summary>
        /// Hangfire job to send Change Address message to One stop.
        /// </summary>
        public async Task SendChangeAddressRest(PerformContext hangfireContext, string licenceGuidRaw, string queueItemId)
        {
            IDynamicsClient dynamicsClient = DynamicsSetupUtil.SetupDynamics(_configuration);

            if (hangfireContext != null)
            {
                hangfireContext.WriteLine("Starting OneStop REST ChangeAddress Job.");
            }

            string licenceGuid = Utils.ParseGuid(licenceGuidRaw);

            //prepare soap content
            var req     = new ChangeAddress();
            var licence = dynamicsClient.GetLicenceByIdWithChildren(licenceGuid);

            if (hangfireContext != null && licence != null)
            {
                hangfireContext.WriteLine($"Got Licence {licenceGuid}.");
            }

            if (licence == null || licence.AdoxioEstablishment == null)
            {
                if (hangfireContext != null)
                {
                    hangfireContext.WriteLine($"Unable to get licence {licenceGuid}.");
                }

                if (Log.Logger != null)
                {
                    Log.Logger.Error($"Unable to get licence {licenceGuid}.");
                }
            }
            else
            {
                var innerXml = req.CreateXML(licence);
                innerXml = _onestopRestClient.CleanXML(innerXml);

                if (Log.Logger != null)
                {
                    Log.Logger.Information(innerXml);
                }

                if (hangfireContext != null)
                {
                    hangfireContext.WriteLine(innerXml);
                }

                //send message to Onestop hub

                var outputXML = await _onestopRestClient.ReceiveFromPartner(innerXml);

                UpdateQueueItemForSend(dynamicsClient, hangfireContext, queueItemId, innerXml, outputXML);

                if (hangfireContext != null)
                {
                    hangfireContext.WriteLine(outputXML);
                    hangfireContext.WriteLine("End of OneStop REST ChangeAddress  Job.");
                }
            }
        }
Exemplo n.º 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            // determine if we wire up Dynamics.
            if (!string.IsNullOrEmpty(Configuration["DYNAMICS_ODATA_URI"]))
            {
                services.AddTransient(serviceProvider =>
                {
                    IDynamicsClient client = DynamicsSetupUtil.SetupDynamics(Configuration);
                    return(client);
                });

                // add SharePoint.

                services.AddTransient(_ => new FileManager(Configuration));
            }
            services.AddMvc(config =>
            {
                config.EnableEndpointRouting = false;
            }).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
        }
Exemplo n.º 8
0
        public async Task SendProgramAccountRequestREST(PerformContext hangfireContext, string licenceGuidRaw, string suffix, string queueItemId)
        {
            hangfireContext?.WriteLine("Starting OneStop ProgramAccountRequest Job.");

            IDynamicsClient dynamicsClient = DynamicsSetupUtil.SetupDynamics(_configuration);

            string licenceGuid = Utils.ParseGuid(licenceGuidRaw);

            // prepare soap message
            var req = new ProgramAccountRequest();

            hangfireContext?.WriteLine($"Getting Licence {licenceGuid}");


            var licence = dynamicsClient.GetLicenceByIdWithChildren(licenceGuid);

            if (hangfireContext != null && licence != null)
            {
                hangfireContext.WriteLine($"Got Licence {licenceGuid}.");
            }

            if (licence == null)
            {
                hangfireContext?.WriteLine($"Unable to get licence {licenceGuid}.");


                Log.Logger?.Error($"Unable to get licence {licenceGuid}.");
            }
            else
            {
                // only send the request if Dynamics says the licence is not sent yet.
                if (licence.AdoxioOnestopsent == null || licence.AdoxioOnestopsent == false)
                {
                    var innerXml = req.CreateXML(licence, suffix);

                    innerXml = _onestopRestClient.CleanXML(innerXml);

                    Log.Logger?.Information(innerXml);
                    // send message to Onestop hub
                    var outputXml = await _onestopRestClient.ReceiveFromPartner(innerXml);

                    UpdateQueueItemForSend(dynamicsClient, hangfireContext, queueItemId, innerXml, outputXml);

                    if (hangfireContext != null)
                    {
                        hangfireContext.WriteLine(outputXml);
                    }
                }
                else
                {
                    hangfireContext?.WriteLine($"Skipping ProgramAccountRequest for Licence {licence.AdoxioName} {licenceGuid} as the record is marked as sent to OneStop.");

                    Log.Logger?.Error($"Skipping ProgramAccountRequest for Licence {licence.AdoxioName} {licenceGuid} as the record is marked as sent to OneStop.");
                }
            }


            hangfireContext?.WriteLine("End of OneStop ProgramAccountRequest  Job.");
        }
Exemplo n.º 9
0
        public OneStopUtils(IConfiguration Configuration, IMemoryCache cache)
        {
            this.Configuration = Configuration;
            _cache             = cache;
            _dynamics          = DynamicsSetupUtil.SetupDynamics(Configuration);

            _onestopRestClient = OneStopUtils.SetupOneStopClient(Configuration, Log.Logger);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Hangfire job to send LicenceDetailsMessage to One stop.
        /// </summary>
        public async Task SendProgramAccountDetailsBroadcastMessageRest(PerformContext hangfireContext, string licenceGuidRaw)
        {
            IDynamicsClient dynamicsClient = DynamicsSetupUtil.SetupDynamics(_configuration);

            if (hangfireContext != null)
            {
                hangfireContext.WriteLine("Starting OneStop REST ProgramAccountDetailsBroadcast Job.");
            }

            string licenceGuid = Utils.ParseGuid(licenceGuidRaw);

            //prepare soap content
            var req     = new ProgramAccountDetailsBroadcast();
            var licence = dynamicsClient.GetLicenceByIdWithChildren(licenceGuid);

            if (hangfireContext != null && licence != null)
            {
                hangfireContext.WriteLine($"Got Licence {licenceGuid}.");
            }

            if (licence == null)
            {
                if (hangfireContext != null)
                {
                    hangfireContext.WriteLine($"Unable to get licence {licenceGuid}.");
                }

                if (Log.Logger != null)
                {
                    Log.Logger.Error($"Unable to get licence {licenceGuid}.");
                }
            }
            else
            {
                var innerXml = req.CreateXML(licence);

                innerXml = _onestopRestClient.CleanXML(innerXml);

                if (Log.Logger != null)
                {
                    Log.Logger.Information(innerXml);
                }

                if (hangfireContext != null)
                {
                    hangfireContext.WriteLine(innerXml);
                }

                //send message to Onestop hub
                var outputXML = await _onestopRestClient.ReceiveFromPartner(innerXml);

                if (hangfireContext != null)
                {
                    hangfireContext.WriteLine(outputXML);
                    hangfireContext.WriteLine("End of OneStop REST ProgramAccountDetailsBroadcast  Job.");
                }
            }
        }
Exemplo n.º 11
0
 public FederalReportingController(IConfiguration configuration, ILoggerFactory loggerFactory, FileManagerClient fileClient)
 {
     _configuration = configuration;
     if (_configuration["DYNAMICS_ODATA_URI"] != null)
     {
         _dynamicsClient = DynamicsSetupUtil.SetupDynamics(_configuration);
     }
     _fileManagerClient = fileClient;
     _logger            = loggerFactory.CreateLogger(typeof(FederalReportingController));
 }
Exemplo n.º 12
0
 public OrgBookUtils(IConfiguration Configuration, ILogger logger)
 {
     this.Configuration = Configuration;
     if (Configuration["DYNAMICS_ODATA_URI"] != null)
     {
         _dynamics = DynamicsSetupUtil.SetupDynamics(Configuration);
     }
     _logger        = logger;
     _orgbookClient = new OrgBookClient(new HttpClient(), Configuration["ORGBOOK_URL"]);
 }
 public OrgBookController(IConfiguration configuration, ILoggerFactory loggerFactory)
 {
     Configuration = configuration;
     if (Configuration["DYNAMICS_ODATA_URI"] != null)
     {
         _dynamics = DynamicsSetupUtil.SetupDynamics(Configuration);
     }
     _orgbookClient = new OrgBookClient(new HttpClient(), Configuration["ORGBOOK_URL"]);
     _logger        = loggerFactory.CreateLogger("OrgbookController");
 }
Exemplo n.º 14
0
        private void SetupDynamics(IServiceCollection services)
        {
            services.AddTransient(serviceProvider =>
            {
                IDynamicsClient client = DynamicsSetupUtil.SetupDynamics(Configuration);
                return(client);
            });

            // add SharePoint.

            services.AddTransient(_ => new FileManager(Configuration));
        }
Exemplo n.º 15
0
 public FederalReportingController(IConfiguration configuration, ILoggerFactory loggerFactory)
 {
     _configuration = configuration;
     if (_configuration["DYNAMICS_ODATA_URI"] != null)
     {
         _dynamicsClient = DynamicsSetupUtil.SetupDynamics(_configuration);
     }
     if (_configuration["SHAREPOINT_ODATA_URI"] != null)
     {
         _sharepoint = new SharePointFileManager(_configuration);
     }
     _logger = loggerFactory.CreateLogger(typeof(FederalReportingController));
 }
Exemplo n.º 16
0
 public CarlaUtils(IConfiguration Configuration, ILoggerFactory loggerFactory, FileManager sharepoint)
 {
     this.Configuration = Configuration;
     _logger            = loggerFactory.CreateLogger(typeof(CarlaUtils));
     if (!string.IsNullOrEmpty(Configuration["DYNAMICS_ODATA_URI"]))
     {
         _dynamics = DynamicsSetupUtil.SetupDynamics(Configuration);
     }
     else
     {
         _dynamics = null;
     }
     CarlaClient      = SetupCarlaClient();
     _carlaSharepoint = new CarlaSharepoint(Configuration, loggerFactory, sharepoint, CarlaClient);
 }
Exemplo n.º 17
0
        private void SetupDynamics(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                                  builder =>
                {
                    builder.WithOrigins("https://localhost",
                                        "https://dev.justice.gov.bc.ca",
                                        "https://test.justice.gov.bc.ca",
                                        "https://justice.gov.bc.ca");
                });
            });



            services.AddTransient(serviceProvider =>
            {
                IDynamicsClient client = DynamicsSetupUtil.SetupDynamics(Configuration);
                return(client);
            });

            // add SharePoint.

            if (!string.IsNullOrEmpty(Configuration["SHAREPOINT_ODATA_URI"]))
            {
                services.AddTransient <SharePointFileManager>(_ => new SharePointFileManager(Configuration));
            }

            // add BCeID Web Services

            string bceidUrl    = Configuration["BCEID_SERVICE_URL"];
            string bceidSvcId  = Configuration["BCEID_SERVICE_SVCID"];
            string bceidUserid = Configuration["BCEID_SERVICE_USER"];
            string bceidPasswd = Configuration["BCEID_SERVICE_PASSWD"];

            services.AddTransient <BCeIDBusinessQuery>(_ => new BCeIDBusinessQuery(bceidSvcId, bceidUserid, bceidPasswd, bceidUrl));
        }
Exemplo n.º 18
0
        private void SetupDynamics(IServiceCollection services)
        {
            services.AddTransient(serviceProvider =>
            {
                IDynamicsClient client = DynamicsSetupUtil.SetupDynamics(Configuration);
                return(client);
            });

            // add SharePoint.

            if (!string.IsNullOrEmpty(Configuration["SHAREPOINT_ODATA_URI"]))
            {
                services.AddTransient <SharePointFileManager>(_ => new SharePointFileManager(Configuration));
            }

            // add BCeID Web Services

            string bceidUrl    = Configuration["BCEID_SERVICE_URL"];
            string bceidSvcId  = Configuration["BCEID_SERVICE_SVCID"];
            string bceidUserid = Configuration["BCEID_SERVICE_USER"];
            string bceidPasswd = Configuration["BCEID_SERVICE_PASSWD"];

            services.AddTransient <BCeIDBusinessQuery>(_ => new BCeIDBusinessQuery(bceidSvcId, bceidUserid, bceidPasswd, bceidUrl));
        }
        private string HandleSBNErrorNotification(string inputXML)
        {
            IDynamicsClient dynamicsClient = DynamicsSetupUtil.SetupDynamics(_configuration);

            string result = "200";
            // deserialize the inputXML
            var serializer = new XmlSerializer(typeof(SBNErrorNotification1));
            SBNErrorNotification1 errorNotification;

            using (TextReader reader = new StringReader(inputXML))
            {
                errorNotification = (SBNErrorNotification1)serializer.Deserialize(reader);
            }


            // check to see if it is simply a problem with an old account number.
            if (errorNotification.body.validationErrors[0].errorMessageNumber.Equals("11845")) // Transaction not allowed - Duplicate Client event exists )
            {
                Log.Logger.Error($"CRA has rejected the message due to an incorrect business number.  The business in question may have had multiple business numbers in the past and the number in the record is no longer valid.  Please correct the business number for record with partnernote of {errorNotification.header.partnerNote}");
            }
            else if (errorNotification.body.validationErrors[0].errorMessageNumber.Equals("11409")) // Old account number.
            {
                Log.Logger.Information("Error is old account number is already associated with another account.  Retrying.");
                // retry the request with a higher increment.

                string licenceGuid   = OneStopUtils.GetGuidFromPartnerNote(errorNotification.header.partnerNote);
                int    currentSuffix = OneStopUtils.GetSuffixFromPartnerNote(errorNotification.header.partnerNote, Log.Logger);

                string cacheKey = "_BPAR_" + licenceGuid;

                Log.Logger.Information($"Reading cache value for key {cacheKey}");

                if (!_cache.TryGetValue(cacheKey, out int suffixLimit))
                {
                    suffixLimit = 10;
                }

                // sanity check
                if (currentSuffix < suffixLimit)
                {
                    currentSuffix++;
                    Log.Logger.Information($"Starting resend of send program account request message, with new value of {currentSuffix}");

                    var patchRecord = new MicrosoftDynamicsCRMadoxioLicences()
                    {
                        AdoxioBusinessprogramaccountreferencenumber = currentSuffix.ToString()
                    };
                    dynamicsClient.Licenceses.Update(licenceGuid, patchRecord);

                    BackgroundJob.Schedule(() => new OneStopUtils(_configuration, _cache).SendProgramAccountRequestREST(null, licenceGuid, currentSuffix.ToString("D3")) // zero pad 3 digit.
                                           , TimeSpan.FromSeconds(30));                                                                                                  // Try again after 30 seconds
                }
                else
                {
                    Log.Logger.Error($"Skipping resend of send program account request message as there have been too many tries({currentSuffix} - {suffixLimit}) Partner Note is partner note {errorNotification.header.partnerNote}");
                }
            }
            else
            {
                Log.Logger.Error($"Received error notification for record with partner note {errorNotification.header.partnerNote} Error Code is  {errorNotification.body.validationErrors[0].errorMessageNumber}. Error Text is {errorNotification.body.validationErrors[0].errorMessageText} {inputXML}");
            }

            return(result);
        }
Exemplo n.º 20
0
        public async Task CheckForLdbSales(PerformContext hangfireContext)
        {
            IDynamicsClient dynamicsClient = null;

            if (!string.IsNullOrEmpty(Configuration["DYNAMICS_ODATA_URI"]))
            {
                dynamicsClient = DynamicsSetupUtil.SetupDynamics(Configuration);
            }

            if (hangfireContext != null)
            {
                hangfireContext.WriteLine("Starting check for LDB sales");
            }

            byte[] data = TestGetFile(); //ScpGetData(hangfireContext);

            // parse the data.

            List <LdbOrderCsv> rows = GetOrderCsvs(data);

            foreach (var row in rows)
            {
                if (_debugMode && hangfireContext != null)
                {
                    hangfireContext.WriteLine($"Licence {row.Licence} DateStart {row.DateStart} DateEnd {row.DateEnd} OrderTotal {row.OrderAmount}");
                }
                // lookup the licence.
                if (dynamicsClient != null)
                {
                    var licence = dynamicsClient.GetLicenceByNumber(row.Licence.ToString());
                    if (licence != null)
                    {
                        // create a row for the ldb orders.
                        MicrosoftDynamicsCRMadoxioLdborder ldbOrder = new MicrosoftDynamicsCRMadoxioLdborder()
                        {
                            LicenceIdODataBind = dynamicsClient.GetEntityURI("adoxio_licenceses", licence.AdoxioLicencesid),
                            AdoxioMonthstart   = row.DateStart,
                            AdoxioMonthend     = row.DateEnd,
                            AdoxioMonth        = row.DateStart.Month,
                            AdoxioYeartext     = row.DateStart.Year.ToString(),
                            AdoxioTotalsales   = row.OrderAmount
                        };
                        try
                        {
                            dynamicsClient.Ldborders.Create(ldbOrder);
                            if (hangfireContext != null)
                            {
                                hangfireContext.WriteLine($"Added Order data for Licence {row.Licence} DateStart {row.DateStart} DateEnd {row.DateEnd}");
                            }
                        }
                        catch (Exception e)
                        {
                            if (hangfireContext != null)
                            {
                                hangfireContext.WriteLine($"Error adding Order data for Licence {row.Licence} DateStart {row.DateStart} DateEnd {row.DateEnd}");
                            }

                            Log.Error(e,
                                      $"Error adding Order data for Licence {row.Licence} DateStart {row.DateStart} DateEnd {row.DateEnd}");
                        }
                    }
                }
            }

            hangfireContext.WriteLine("End of check for new OneStop queue items");
        }
Exemplo n.º 21
0
 public SpdUtils(IConfiguration Configuration, ILoggerFactory loggerFactory)
 {
     this.Configuration = Configuration;
     _logger            = loggerFactory.CreateLogger(typeof(SpdUtils));
     _dynamics          = DynamicsSetupUtil.SetupDynamics(Configuration);
 }
Exemplo n.º 22
0
        private void SetupServices(IServiceCollection services)
        {
            string dynamicsOdataUri = _configuration["DYNAMICS_ODATA_URI"];
            string aadTenantId      = _configuration["DYNAMICS_AAD_TENANT_ID"];
            string serverAppIdUri   = _configuration["DYNAMICS_SERVER_APP_ID_URI"];
            string clientKey        = _configuration["DYNAMICS_CLIENT_KEY"];
            string clientId         = _configuration["DYNAMICS_CLIENT_ID"];

            string ssgUsername = _configuration["SSG_USERNAME"];
            string ssgPassword = _configuration["SSG_PASSWORD"];

            AuthenticationResult authenticationResult = null;



            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                                  builder =>
                {
                    builder.WithOrigins("https://localhost",
                                        "http://cannabis-licensing-dev.pathfinder.bcgov",
                                        "http://cannabis-licensing-test.pathfinder.bcgov",
                                        "http://cannabis-licensing-prod.pathfinder.bcgov",
                                        "https://dev.justice.gov.bc.ca",
                                        "https://test.justice.gov.bc.ca",
                                        "https://justice.gov.bc.ca");
                });
            });


            services.AddTransient(new Func <IServiceProvider, IDynamicsClient>((serviceProvider) =>
            {
                IDynamicsClient client = DynamicsSetupUtil.SetupDynamics(_configuration);

                return(client);
            }));


            // add BCeID Web Services

            string bceidUrl    = _configuration["BCEID_SERVICE_URL"];
            string bceidSvcId  = _configuration["BCEID_SERVICE_SVCID"];
            string bceidUserid = _configuration["BCEID_SERVICE_USER"];
            string bceidPasswd = _configuration["BCEID_SERVICE_PASSWD"];

            services.AddTransient <BCeIDBusinessQuery>(_ => new BCeIDBusinessQuery(bceidSvcId, bceidUserid, bceidPasswd, bceidUrl));

            // add BCEP services

            var bcep_svc_url       = _configuration["BCEP_SERVICE_URL"];
            var bcep_svc_svcid     = _configuration["BCEP_MERCHANT_ID"];
            var bcep_svc_alt_svcid = _configuration["BCEP_ALTERNATE_MERCHANT_ID"];
            var bcep_svc_hashid    = _configuration["BCEP_HASH_KEY"];
            var bcep_base_uri      = _configuration["BASE_URI"];
            var bcep_base_path     = _configuration["BASE_PATH"];
            var bcep_conf_path     = _configuration["BCEP_CONF_PATH"];

            services.AddTransient <BCEPWrapper>(_ => new BCEPWrapper(bcep_svc_url, bcep_svc_svcid, bcep_svc_alt_svcid, bcep_svc_hashid,
                                                                     bcep_base_uri + bcep_base_path + bcep_conf_path));

            // add the PDF client.
            string pdf_service_base_uri = _configuration["PDF_SERVICE_BASE_URI"];
            string bearer_token         = $"Bearer {_configuration["PDF_JWT_TOKEN"]}";

            services.AddTransient <PdfClient>(_ => new PdfClient(pdf_service_base_uri, bearer_token));

            // add the GeoCoder Client.

            services.AddTransient <GeocoderClient>(_ => new GeocoderClient(_configuration));

            // add the file manager.
            string fileManagerURI = _configuration["FILE_MANAGER_URI"];

            if (!_env.IsProduction()) // needed for macOS TLS being turned off
            {
                AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            }
            if (!string.IsNullOrEmpty(fileManagerURI))
            {
                var httpClientHandler = new HttpClientHandler();

                if (!_env.IsProduction()) // Ignore certificate errors in non-production modes.
                                          // This allows you to use OpenShift self-signed certificates for testing.
                {
                    // Return `true` to allow certificates that are untrusted/invalid
                    httpClientHandler.ServerCertificateCustomValidationCallback =
                        HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
                }

                var httpClient = new HttpClient(httpClientHandler);
                // set default request version to HTTP 2.  Note that Dotnet Core does not currently respect this setting for all requests.
                httpClient.DefaultRequestVersion = HttpVersion.Version20;

                var initialChannel = GrpcChannel.ForAddress(fileManagerURI, new GrpcChannelOptions {
                    HttpClient = httpClient
                });

                var initialClient = new FileManagerClient(initialChannel);
                // call the token service to get a token.
                var tokenRequest = new TokenRequest()
                {
                    Secret = _configuration["FILE_MANAGER_SECRET"]
                };

                var tokenReply = initialClient.GetToken(tokenRequest);

                if (tokenReply != null && tokenReply.ResultStatus == ResultStatus.Success)
                {
                    // Add the bearer token to the client.

                    httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {tokenReply.Token}");

                    var channel = GrpcChannel.ForAddress(fileManagerURI, new GrpcChannelOptions()
                    {
                        HttpClient = httpClient
                    });

                    services.AddTransient <FileManagerClient>(_ => new FileManagerClient(channel));
                }
            }
        }
Exemplo n.º 23
0
        static IDynamicsClient GetDynamicsConnection(IConfiguration Configuration)
        {
            var _dynamicsClient = DynamicsSetupUtil.SetupDynamics(Configuration);

            return(_dynamicsClient);
        }
Exemplo n.º 24
0
        private void SetupServices(IServiceCollection services)
        {
            string dynamicsOdataUri = Configuration["DYNAMICS_ODATA_URI"];
            string aadTenantId      = Configuration["DYNAMICS_AAD_TENANT_ID"];
            string serverAppIdUri   = Configuration["DYNAMICS_SERVER_APP_ID_URI"];
            string clientKey        = Configuration["DYNAMICS_CLIENT_KEY"];
            string clientId         = Configuration["DYNAMICS_CLIENT_ID"];

            string ssgUsername = Configuration["SSG_USERNAME"];
            string ssgPassword = Configuration["SSG_PASSWORD"];

            AuthenticationResult authenticationResult = null;

            // authenticate using ADFS.
            if (string.IsNullOrEmpty(ssgUsername) || string.IsNullOrEmpty(ssgPassword))
            {
                var authenticationContext = new AuthenticationContext(
                    "https://login.windows.net/" + aadTenantId);
                ClientCredential clientCredential = new ClientCredential(clientId, clientKey);
                var task = authenticationContext.AcquireTokenAsync(serverAppIdUri, clientCredential);
                task.Wait();
                authenticationResult = task.Result;
            }

            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                                  builder =>
                {
                    builder.WithOrigins("https://localhost",
                                        "http://cannabis-licensing-dev.pathfinder.bcgov",
                                        "http://cannabis-licensing-test.pathfinder.bcgov",
                                        "http://cannabis-licensing-prod.pathfinder.bcgov",
                                        "https://dev.justice.gov.bc.ca",
                                        "https://test.justice.gov.bc.ca",
                                        "https://justice.gov.bc.ca");
                });
            });


            services.AddTransient(new Func <IServiceProvider, IDynamicsClient>((serviceProvider) =>
            {
                IDynamicsClient client = DynamicsSetupUtil.SetupDynamics(Configuration);

                return(client);
            }));

            // add SharePoint.

            services.AddTransient <SharePointFileManager>(_ => new SharePointFileManager(Configuration));

            // add BCeID Web Services

            string bceidUrl    = Configuration["BCEID_SERVICE_URL"];
            string bceidSvcId  = Configuration["BCEID_SERVICE_SVCID"];
            string bceidUserid = Configuration["BCEID_SERVICE_USER"];
            string bceidPasswd = Configuration["BCEID_SERVICE_PASSWD"];

            services.AddTransient <BCeIDBusinessQuery>(_ => new BCeIDBusinessQuery(bceidSvcId, bceidUserid, bceidPasswd, bceidUrl));

            // add BCEP services

            var bcep_svc_url    = Configuration["BCEP_SERVICE_URL"];
            var bcep_svc_svcid  = Configuration["BCEP_MERCHANT_ID"];
            var bcep_svc_hashid = Configuration["BCEP_HASH_KEY"];
            var bcep_base_uri   = Configuration["BASE_URI"];
            var bcep_base_path  = Configuration["BASE_PATH"];
            var bcep_conf_path  = Configuration["BCEP_CONF_PATH"];

            services.AddTransient <BCEPWrapper>(_ => new BCEPWrapper(bcep_svc_url, bcep_svc_svcid, bcep_svc_hashid,
                                                                     bcep_base_uri + bcep_base_path + bcep_conf_path));

            // add the PDF client.
            string pdf_service_base_uri = Configuration["PDF_SERVICE_BASE_URI"];
            string bearer_token         = $"Bearer {Configuration["PDF_JWT_TOKEN"]}";

            services.AddTransient <PdfClient>(_ => new PdfClient(pdf_service_base_uri, bearer_token));

            // add the GeoCoder Client.

            services.AddTransient <GeocoderClient>(_ => new GeocoderClient(Configuration));
        }
 public LdbExport(IConfiguration Configuration)
 {
     this.Configuration = Configuration;
     _dynamics          = DynamicsSetupUtil.SetupDynamics(Configuration);
 }
Exemplo n.º 26
0
        public async Task CheckForNewLicences(PerformContext hangfireContext)
        {
            IDynamicsClient dynamicsClient = DynamicsSetupUtil.SetupDynamics(_configuration);

            if (hangfireContext != null)
            {
                hangfireContext.WriteLine("Starting check for new OneStop queue items job.");
            }
            IList <MicrosoftDynamicsCRMadoxioOnestopmessageitem> result;

            try
            {
                string filter = "adoxio_datetimesent eq null";
                result = dynamicsClient.Onestopmessageitems.Get(filter: filter).Value;
            }
            catch (HttpOperationException odee)
            {
                if (hangfireContext != null)
                {
                    hangfireContext.WriteLine("Error getting Licences");
                    hangfireContext.WriteLine("Request:");
                    hangfireContext.WriteLine(odee.Request.Content);
                    hangfireContext.WriteLine("Response:");
                    hangfireContext.WriteLine(odee.Response.Content);
                }

                // fail if we can't get results.
                throw (odee);
            }

            int currentItem = 0;

            // now for each one process it.
            foreach (var queueItem in result)
            {
                if (!string.IsNullOrEmpty(queueItem._adoxioLicenceValue))
                {
                    var item = dynamicsClient.GetLicenceByIdWithChildren(queueItem._adoxioLicenceValue);

                    string licenceId = item.AdoxioLicencesid;

                    switch ((OneStopHubStatusChange)queueItem.AdoxioStatuschangedescription)
                    {
                    case OneStopHubStatusChange.Issued:
                    case OneStopHubStatusChange.TransferComplete:
                        if ((OneStopHubStatusChange)queueItem.AdoxioStatuschangedescription ==
                            OneStopHubStatusChange.TransferComplete)
                        {
                            // send a change status to the old licensee
                            await SendChangeStatusRest(hangfireContext, licenceId,
                                                       (OneStopHubStatusChange)queueItem.AdoxioStatuschangedescription, queueItem.AdoxioOnestopmessageitemid);
                        }
                        // Do not attempt to send licence records that have no establishment (for example, Marketer Licence records)
                        if (item.AdoxioEstablishment != null)
                        {
                            string programAccountCode = "001";
                            if (item.AdoxioBusinessprogramaccountreferencenumber != null)
                            {
                                programAccountCode = item.AdoxioBusinessprogramaccountreferencenumber;
                            }

                            // set the maximum code.
                            string cacheKey = "_BPAR_" + item.AdoxioLicencesid;
                            string suffix   = programAccountCode.TrimStart('0');
                            if (int.TryParse(suffix, out int newNumber))
                            {
                                newNumber += 10;     // 10 tries.
                            }
                            else
                            {
                                newNumber = 10;
                            }
                            _cache.Set(cacheKey, newNumber);

                            if (hangfireContext != null)
                            {
                                hangfireContext.WriteLine($"SET key {cacheKey} to {newNumber}");
                            }
                            await SendProgramAccountRequestREST(hangfireContext, licenceId, suffix, queueItem.AdoxioOnestopmessageitemid);
                        }

                        break;

                    case OneStopHubStatusChange.Cancelled:
                    case OneStopHubStatusChange.EnteredDormancy:
                    case OneStopHubStatusChange.DormancyEnded:
                    case OneStopHubStatusChange.Expired:
                    case OneStopHubStatusChange.CancellationRemoved:
                    case OneStopHubStatusChange.Renewed:
                    case OneStopHubStatusChange.Suspended:
                    case OneStopHubStatusChange.SuspensionEnded:

                        await SendChangeStatusRest(hangfireContext, licenceId,
                                                   (OneStopHubStatusChange)queueItem.AdoxioStatuschangedescription, queueItem.AdoxioOnestopmessageitemid);

                        break;

                    case OneStopHubStatusChange.ChangeOfAddress:
                        await SendChangeAddressRest(hangfireContext, licenceId, queueItem.AdoxioOnestopmessageitemid);

                        break;

                    case OneStopHubStatusChange.ChangeOfName:
                    case OneStopHubStatusChange.LicenceDeemedAtTransfer:
                        await SendChangeNameRest(hangfireContext, licenceId, queueItem.AdoxioOnestopmessageitemid);

                        break;
                    }

                    currentItem++;

                    if (currentItem > MAX_LICENCES_PER_INTERVAL)
                    {
                        break; // exit foreach
                    }
                }
            }

            hangfireContext.WriteLine("End of check for new OneStop queue items");
        }
        private string HandleSBNCreateProgramAccountResponse(string inputXML)
        {
            IDynamicsClient dynamicsClient = DynamicsSetupUtil.SetupDynamics(_configuration);

            Log.Logger.Information("Reached HandleSBNCreateProgramAccountResponse");
            if (!_env.IsProduction())
            {
                Log.Logger.Information($"InputXML is: {inputXML}");
            }

            string httpStatusCode = "200";

            // deserialize the inputXML
            var serializer = new XmlSerializer(typeof(SBNCreateProgramAccountResponse1));
            SBNCreateProgramAccountResponse1 licenseData;

            using (TextReader reader = new StringReader(inputXML))
            {
                licenseData = (SBNCreateProgramAccountResponse1)serializer.Deserialize(reader);
            }


            string licenceNumber = OneStopUtils.GetLicenceNumberFromPartnerNote(licenseData.header.partnerNote);

            Log.Logger.Information($"Getting licence with number of {licenceNumber}");

            // Get licence from dynamics

            string businessProgramAccountNumber = "1";
            MicrosoftDynamicsCRMadoxioLicences licence;

            string filter = $"adoxio_licencenumber eq '{licenceNumber}'";

            try
            {
                licence = dynamicsClient.Licenceses.Get(filter: filter).Value.FirstOrDefault();
                businessProgramAccountNumber = licenseData.body.businessProgramAccountNumber.businessProgramAccountReferenceNumber;
            }
            catch (Exception e)
            {
                Log.Logger.Error($"Unable to get licence data for licence number {licenceNumber} {e.Message}");
                licence = null;
            }


            if (licence == null)
            {
                Log.Logger.Information("licence is null - returning 400.");
                httpStatusCode = "400";
            }
            else
            {
                Log.Logger.Information("Licence record retrieved from Dynamics.");
                //save the program account number to dynamics

                int    tempBpan      = int.Parse(businessProgramAccountNumber);
                string sanitizedBpan = tempBpan.ToString();

                MicrosoftDynamicsCRMadoxioLicences pathLicence = new MicrosoftDynamicsCRMadoxioLicences()
                {
                    AdoxioBusinessprogramaccountreferencenumber = sanitizedBpan,
                    AdoxioOnestopsent = true
                };
                Log.Logger.Information("Sending update to Dynamics for BusinessProgramAccountNumber.");
                try
                {
                    dynamicsClient.Licenceses.Update(licence.AdoxioLicencesid, pathLicence);
                    Log.Logger.Information($"ONESTOP Updated Licence {licenceNumber} record {licence.AdoxioLicencesid} to {businessProgramAccountNumber}");
                }
                catch (HttpOperationException odee)
                {
                    Log.Logger.Error(odee, "Error updating Licence {licence.AdoxioLicencesid}");
                    // fail if we can't get results.
                    throw (odee);
                }

                //Trigger the Send ProgramAccountDetailsBroadcast Message
                BackgroundJob.Enqueue(() => new OneStopUtils(_configuration, _cache).SendProgramAccountDetailsBroadcastMessageRest(null, licence.AdoxioLicencesid));

                Log.Logger.Information("send program account details broadcast done.");
            }

            return(httpStatusCode);
        }
Exemplo n.º 28
0
        public void Execute(IConfiguration config, bool doRename)
        {
            // get a connection to Dynamics.
            IDynamicsClient dynamicsClient = DynamicsSetupUtil.SetupDynamics(config);

            // get the list of application files.
            SharePointFileManager sharePoint = new SharePointFileManager(config);

            string[] orderby = { "adoxio_licencenumber" };
            string[] expand  = { "adoxio_licences_SharePointDocumentLocations" };
            //var licences = dynamicsClient.Licenceses.Get(expand: expand).Value;


            var customHeaders = new Dictionary <string, List <string> >();
            var preferHeader  = new List <string>();

            preferHeader.Add($"odata.maxpagesize=5000");

            customHeaders.Add("Prefer", preferHeader);
            var odataVersionHeader = new List <string>();

            odataVersionHeader.Add("4.0");

            customHeaders.Add("OData-Version", odataVersionHeader);
            customHeaders.Add("OData-MaxVersion", odataVersionHeader);
            string odataNextLink = "1";
            bool   firstTime     = true;
            int    totalCount    = 5000;
            int    currentCount  = 0;
            int    renameCount   = 0;
            HttpOperationResponse <MicrosoftDynamicsCRMadoxioLicencesCollection> licencesQuery = new HttpOperationResponse <MicrosoftDynamicsCRMadoxioLicencesCollection>();

            while (odataNextLink != null)
            {
                if (firstTime)
                {
                    firstTime     = false;
                    licencesQuery = dynamicsClient.Licenceses.GetWithHttpMessagesAsync(expand: expand, customHeaders: customHeaders, count: true, orderby: orderby).GetAwaiter().GetResult();
                }
                else
                {
                    odataNextLink = licencesQuery.Body.OdataNextLink;
                    if (odataNextLink != null)
                    {
                        licencesQuery = dynamicsClient.Licenceses.GetNextLink(odataNextLink, customHeaders);

                        totalCount += licencesQuery.Body.Value.Count;
                    }
                    else
                    {
                        licencesQuery = new HttpOperationResponse <MicrosoftDynamicsCRMadoxioLicencesCollection>();
                    }
                }
                Console.Out.WriteLine($"Currently on licence {currentCount} of {totalCount}");
                if (licencesQuery?.Body?.Value != null)
                {
                    var licences = licencesQuery.Body.Value;


                    foreach (var licence in licences)
                    {
                        bool isInRange     = false;
                        int  licenceNumber = -1;
                        int.TryParse(licence.AdoxioLicencenumber, out licenceNumber);

                        if (licenceNumber >= 1114 && licenceNumber <= 18573)
                        {
                            isInRange = true;
                            //Console.Out.WriteLine($"Licence #{licenceNumber}");
                        }
                        currentCount++;
                        string folderName = licence.GetDocumentFolderName();
                        if (licence.AdoxioLicencesSharePointDocumentLocations != null &&
                            licence.AdoxioLicencesSharePointDocumentLocations.Count > 0 &&
                            licence.AdoxioLicencesSharePointDocumentLocations[0].Relativeurl != null)
                        {
                            folderName = licence.AdoxioLicencesSharePointDocumentLocations[0].Relativeurl;
                        }

                        List <FileDetailsList> fileList = null;
                        try
                        {
                            fileList = sharePoint.GetFileDetailsListInFolder(SharePointFileManager.LicenceDocumentUrlTitle,
                                                                             folderName, null)
                                       .GetAwaiter().GetResult();
                        }
                        catch (Exception e)
                        {
                            // Console.WriteLine($"Folder not found [{folderName}]");
                        }

                        if (fileList != null && fileList.Count > 0)
                        {
                            //Console.WriteLine($"Found {fileList.Count} Files.");
                            foreach (var file in fileList)
                            {
                                if (isInRange)
                                {
                                    // Console.Out.WriteLine($"Current filename: {file.Name}");
                                }

                                if (IsSuspect(file.Name))
                                {
                                    string newName = FixName(file.Name);
                                    if (newName != null)
                                    {
                                        Console.Out.WriteLine($"Filename {file.Name} is suspect.");
                                        Console.Out.WriteLine($"New name is {newName}");

                                        string oldFileName =
                                            $"/{SharePointFileManager.LicenceDocumentUrlTitle}/{folderName}/{file.Name}";
                                        string newFileName = $"{SharePointFileManager.LicenceDocumentUrlTitle}/{folderName}/{newName}";
                                        Console.Out.WriteLine($"Rename File {oldFileName} to {newFileName}");
                                        byte[] data = sharePoint.DownloadFile(oldFileName).GetAwaiter().GetResult();
                                        if (data != null)
                                        {
                                            var success = sharePoint.UploadFile(newName,
                                                                                SharePointFileManager.LicenceDocumentUrlTitle, folderName, data, "application/pdf").GetAwaiter().GetResult();
                                            if (success != null)
                                            {
                                                // cleanup the old file.
                                                sharePoint.DeleteFile(oldFileName).GetAwaiter().GetResult();
                                                Console.Out.WriteLine($"Rename File Complete");
                                            }
                                        }

                                        renameCount++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            Console.Out.WriteLine($"Licence count is {totalCount}");
            Console.Out.WriteLine($"Rename count is {renameCount}");
        }
Exemplo n.º 29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging(configure => configure.AddSerilog(dispose: true));

            // Adjust Kestrel options to allow sync IO
            services.Configure <KestrelServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });

            // Add a memory cache
            var x = services.AddMemoryCache();

            IDynamicsClient dynamicsClient = DynamicsSetupUtil.SetupDynamics(_configuration);

            services.AddSingleton <IReceiveFromHubService>(new ReceiveFromHubService(dynamicsClient, _configuration, _env));


            services.AddSingleton <Microsoft.Extensions.Logging.ILogger>(_loggerFactory.CreateLogger("OneStopUtils"));
            services.AddSingleton <Serilog.ILogger>(Log.Logger);

            services.AddMvc(config =>
            {
                config.EnableEndpointRouting = false;
                if (!string.IsNullOrEmpty(_configuration["JWT_TOKEN_KEY"]))
                {
                    var policy = new AuthorizationPolicyBuilder()
                                 .RequireAuthenticatedUser()
                                 .Build();
                    config.Filters.Add(new AuthorizeFilter(policy));
                }
            });

            // Other ConfigureServices() code...

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "JAG LCRB One Stop Service", Version = "v1"
                });
            });

            services.AddIdentity <IdentityUser, IdentityRole>()
            .AddDefaultTokenProviders();

            if (!string.IsNullOrEmpty(_configuration["JWT_TOKEN_KEY"]))
            {
                // Configure JWT authentication
                services.AddAuthentication(o =>
                {
                    o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    o.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                }).AddJwtBearer(o =>
                {
                    o.SaveToken                 = true;
                    o.RequireHttpsMetadata      = false;
                    o.TokenValidationParameters = new TokenValidationParameters()
                    {
                        RequireExpirationTime = false,
                        ValidIssuer           = _configuration["JWT_VALID_ISSUER"],
                        ValidAudience         = _configuration["JWT_VALID_AUDIENCE"],
                        IssuerSigningKey      = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT_TOKEN_KEY"]))
                    };
                });
            }

            services.AddHangfire(config =>
            {
                // Change this line if you wish to have Hangfire use persistent storage.
                config.UseMemoryStorage();
                // enable console logs for jobs
                config.UseConsole();
            });

            // health checks.
            services.AddHealthChecks()
            .AddCheck("one-stop-service", () => HealthCheckResult.Healthy("OK"));
        }
Exemplo n.º 30
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(config =>
            {
                if (!string.IsNullOrEmpty(Configuration["JWT_TOKEN_KEY"]))
                {
                    var policy = new AuthorizationPolicyBuilder()
                                 .RequireAuthenticatedUser()
                                 .Build();
                    config.Filters.Add(new AuthorizeFilter(policy));
                }
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            // Other ConfigureServices() code...

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "JAG SPICE to CARLA Transfer Service", Version = "v1"
                });
                c.DescribeAllEnumsAsStrings();
                c.SchemaFilter <EnumTypeSchemaFilter>();
            });

            services.AddIdentity <IdentityUser, IdentityRole>()
            .AddDefaultTokenProviders();

            if (!string.IsNullOrEmpty(Configuration["JWT_TOKEN_KEY"]))
            {
                // Configure JWT authentication
                services.AddAuthentication(o =>
                {
                    o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    o.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                }).AddJwtBearer(o =>
                {
                    o.SaveToken                 = true;
                    o.RequireHttpsMetadata      = false;
                    o.TokenValidationParameters = new TokenValidationParameters()
                    {
                        RequireExpirationTime = false,
                        ValidIssuer           = Configuration["JWT_VALID_ISSUER"],
                        ValidAudience         = Configuration["JWT_VALID_AUDIENCE"],
                        IssuerSigningKey      = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT_TOKEN_KEY"]))
                    };
                });
            }

            // Setup Dynamics
            if (!string.IsNullOrEmpty(Configuration["DYNAMICS_ODATA_URI"]))
            {
                services.AddTransient(serviceProvider =>
                {
                    IDynamicsClient client = DynamicsSetupUtil.SetupDynamics(Configuration);
                    return(client);
                });
            }

            if (!string.IsNullOrEmpty(Configuration["SHAREPOINT_ODATA_URI"]))
            {
                SetupSharePoint(services);
            }



            services.AddHangfire(config =>
            {
                // Change this line if you wish to have Hangfire use persistent storage.
                config.UseMemoryStorage();
                // enable console logs for jobs

                config.UseConsole();
            });

            // health checks.
            services.AddHealthChecks(checks =>
            {
                checks.AddValueTaskCheck("HTTP Endpoint", () => new
                                         ValueTask <IHealthCheckResult>(HealthCheckResult.Healthy("Ok")));
            });
        }