示例#1
0
        public static IDynamicsClient SetupDynamics(IConfiguration Configuration)
        {
            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;
            }

            ServiceClientCredentials serviceClientCredentials = null;

            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;
                string token = authenticationResult.CreateAuthorizationHeader().Substring("Bearer ".Length);
                serviceClientCredentials = new TokenCredentials(token);
            }
            else
            {
                serviceClientCredentials = new BasicAuthenticationCredentials()
                {
                    UserName = ssgUsername,
                    Password = ssgPassword
                };
            }

            IDynamicsClient client = new DynamicsClient(new Uri(Configuration["DYNAMICS_ODATA_URI"]), serviceClientCredentials);

            // set the native client URI
            if (string.IsNullOrEmpty(Configuration["DYNAMICS_NATIVE_ODATA_URI"]))
            {
                client.NativeBaseUri = new Uri(Configuration["DYNAMICS_ODATA_URI"]);
            }
            else
            {
                client.NativeBaseUri = new Uri(Configuration["DYNAMICS_NATIVE_ODATA_URI"]);
            }

            return(client);
        }
示例#2
0
        public async Task <IActionResult> Index(FeedbackViewModel feedback)
        {
            _logger.LogError("Testing Dynamics");

            var client = DynamicsClient.GenerateClient(Configuration);

            string url = "/api/data/v9.0/test_complaints";

            HttpRequestMessage _httpRequest = new HttpRequestMessage(HttpMethod.Post, url);

            ComplaintModel complaint = new ComplaintModel()
            {
                test_description = feedback.description,
                test_summary     = feedback.summary
            };

            string jsonString = JsonConvert.SerializeObject(complaint);

            _httpRequest.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
            _httpRequest.Headers.Add("PREFER", "return=representation");

            var _httpResponse2 = await client.SendAsync(_httpRequest);

            HttpStatusCode _statusCode = _httpResponse2.StatusCode;


            var _responseContent2 = await _httpResponse2.Content.ReadAsStringAsync();



            return(Ok("Result:\n" + _responseContent2));
        }
示例#3
0
        public static int?GetAttributeMaxLength(DynamicsClient client, IMemoryCache cache, ILogger logger, string entityName, string attributeName)
        {
            try
            {
                int?maxLength = null;
                if (!cache.TryGetValue("", out maxLength))
                {
                    maxLength = DynamicsAutorest.Extensions.ClientExtensions.GetEntityAttribute <MicrosoftDynamicsCRMMemoAttributeMetadata>(
                        (DynamicsClient)client, "Microsoft.Dynamics.CRM.MemoAttributeMetadata", entityName, attributeName)?.MaxLength;

                    // Set cache options.
                    var cacheEntryOptions = new MemoryCacheEntryOptions()
                                            .SetAbsoluteExpiration(TimeSpan.FromDays(1));

                    cache.Set(attributeName, maxLength, cacheEntryOptions);
                }
                return(maxLength);
            }
            catch (OdataerrorException odee)
            {
                logger.LogError("Error retrieving Entity Attribute");
                logger.LogError("Request:");
                logger.LogError(odee.Request.Content);
                logger.LogError("Response:");
                logger.LogError(odee.Response.Content);
            }
            catch (SerializationException se)
            {
                logger.LogError("Error retrieving Entity Attribute");
                logger.LogError("Message:");
                logger.LogError(se.Message);
            }
            return(null);
        }
        public void Clean(DynamicsClient _dynamicsClient)
        {
            // remove all Applications.
            var applications = _dynamicsClient.Applications.Get().Value;

            foreach (var application in applications)
            {
                try
                {
                    _dynamicsClient.Applications.Delete(application.AdoxioApplicationid);
                    Console.Out.WriteLine("Deleted Application " + application.AdoxioApplicationid);
                }
                catch (OdataerrorException odee)
                {
                    Console.Out.WriteLine("Error deleting application");
                    Console.Out.WriteLine("Request:");
                    Console.Out.WriteLine(odee.Request.Content);
                    Console.Out.WriteLine("Response:");
                    Console.Out.WriteLine(odee.Response.Content);
                }
            }

            // remove all lgin
            var lgins = _dynamicsClient.Localgovindigenousnations.Get().Value;

            foreach (var lgin in lgins)
            {
                try
                {
                    _dynamicsClient.Localgovindigenousnations.Delete(lgin.AdoxioLocalgovindigenousnationid);
                    Console.Out.WriteLine("Deleted LGIN " + lgin.AdoxioLocalgovindigenousnationid);
                }
                catch (OdataerrorException odee)
                {
                    Console.Out.WriteLine("Error deleting LGIN");
                    Console.Out.WriteLine("Request:");
                    Console.Out.WriteLine(odee.Request.Content);
                    Console.Out.WriteLine("Response:");
                    Console.Out.WriteLine(odee.Response.Content);
                }
            }
        }
示例#5
0
        public async Task <ActionResult> Test()
        {
            _logger.LogError("Testing Dynamics");

            var client = DynamicsClient.GenerateClient(Configuration);

            string url = "https://devorg.dev.jag.gov.bc.ca/api/data/v9.0/WhoAmI";

            HttpRequestMessage _httpRequest = new HttpRequestMessage(HttpMethod.Get, url);

            var _httpResponse2 = await client.SendAsync(_httpRequest);

            HttpStatusCode _statusCode = _httpResponse2.StatusCode;

            var _responseString = _httpResponse2.ToString();

            var _responseContent2 = await _httpResponse2.Content.ReadAsStringAsync();



            return(Content(_responseContent2));
        }
        public void Move(DynamicsClient _dynamicsClient)
        {
            // first find Cantest1
            string filter = "name eq 'XYZ Cannabis Sales Test'";

            try
            {
                var cantest1 = _dynamicsClient.Accounts.Get(filter: filter).Value.FirstOrDefault();

                if (cantest1 != null)
                {
                    var applications = _dynamicsClient.Applications.Get().Value;

                    foreach (var application in applications)
                    {
                        try
                        {
                            MicrosoftDynamicsCRMadoxioApplication newItem = new MicrosoftDynamicsCRMadoxioApplication()
                            {
                                AdoxioApplicantODataBind = _dynamicsClient.GetEntityURI("accounts", cantest1.Accountid)
                            };
                            _dynamicsClient.Applications.Update(application.AdoxioApplicationid, newItem);
                        }
                        catch (OdataerrorException odee)
                        {
                            Console.Out.WriteLine("Error updating application");
                            Console.Out.WriteLine("Request:");
                            Console.Out.WriteLine(odee.Request.Content);
                            Console.Out.WriteLine("Response:");
                            Console.Out.WriteLine(odee.Response.Content);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.Out.WriteLine("Unable to find Cantest1.");
            }
        }
示例#7
0
        private void SetupDynamics(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.AddTransient(new Func <IServiceProvider, IDynamicsClient>((serviceProvider) =>
            {
                ServiceClientCredentials serviceClientCredentials = null;

                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;
                    string token             = authenticationResult.CreateAuthorizationHeader().Substring("Bearer ".Length);
                    serviceClientCredentials = new TokenCredentials(token);
                }
                else
                {
                    serviceClientCredentials = new BasicAuthenticationCredentials()
                    {
                        UserName = ssgUsername,
                        Password = ssgPassword
                    };
                }

                IDynamicsClient client = new DynamicsClient(new Uri(Configuration["DYNAMICS_ODATA_URI"]), serviceClientCredentials);


                // set the native client URI
                if (string.IsNullOrEmpty(Configuration["DYNAMICS_NATIVE_ODATA_URI"]))
                {
                    client.NativeBaseUri = new Uri(Configuration["DYNAMICS_ODATA_URI"]);
                }
                else
                {
                    client.NativeBaseUri = new Uri(Configuration["DYNAMICS_NATIVE_ODATA_URI"]);
                }

                return(client);
            }));

            // add SharePoint.

            string sharePointServerAppIdUri = Configuration["SHAREPOINT_SERVER_APPID_URI"];
            string sharePointOdataUri       = Configuration["SHAREPOINT_ODATA_URI"];
            string sharePointWebname        = Configuration["SHAREPOINT_WEBNAME"];
            string sharePointAadTenantId    = Configuration["SHAREPOINT_AAD_TENANTID"];
            string sharePointClientId       = Configuration["SHAREPOINT_CLIENT_ID"];
            string sharePointCertFileName   = Configuration["SHAREPOINT_CERTIFICATE_FILENAME"];
            string sharePointCertPassword   = Configuration["SHAREPOINT_CERTIFICATE_PASSWORD"];
            string sharePointNativeBaseURI  = Configuration["SHAREPOINT_NATIVE_BASE_URI"];

            // SharePoint could be using a different username / password.

            string sharePointSsgUsername = ssgUsername;
            string sharePointSsgPassword = ssgPassword;

            if (!string.IsNullOrEmpty(Configuration["SHAREPOINT_SSG_USERNAME"]))
            {
                sharePointSsgUsername = Configuration["SHAREPOINT_SSG_USERNAME"];
            }

            if (!string.IsNullOrEmpty(Configuration["SHAREPOINT_SSG_PASSWORD"]))
            {
                sharePointSsgPassword = Configuration["SHAREPOINT_SSG_PASSWORD"];
            }

            services.AddTransient <SharePointFileManager>(_ => new SharePointFileManager(sharePointServerAppIdUri, sharePointOdataUri, sharePointWebname, sharePointAadTenantId, sharePointClientId, sharePointCertFileName, sharePointCertPassword, sharePointSsgUsername, sharePointSsgPassword, sharePointNativeBaseURI));

            // 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));
        }
示例#8
0
        // the one parameter is the BCeID guid for an individual.
        static void Main(string[] args)
        {
            bool   isBackfill    = false;
            bool   isSingleQuery = false;
            string singleQuery   = null;


            if (args.Length > 0)
            {
                string arg = args[0];
                if (!string.IsNullOrEmpty(arg))
                {
                    if (arg.ToLower().Equals("backfill"))
                    {
                        isBackfill = true;
                        Console.Out.WriteLine("Backfill enabled.");
                    }
                    else
                    {
                        isSingleQuery = true;
                        singleQuery   = arg;
                        Console.Out.WriteLine("Single query enabled.");
                    }
                }
            }

            // get the environment settings.
            string bceidServiceSvcid  = Environment.GetEnvironmentVariable("BCEID_SERVICE_SVCID");
            string bceidServiceUser   = Environment.GetEnvironmentVariable("BCEID_SERVICE_USER");
            string bceidServicePasswd = Environment.GetEnvironmentVariable("BCEID_SERVICE_PASSWD");
            string bceidServiceUrl    = Environment.GetEnvironmentVariable("BCEID_SERVICE_URL");

            string dynamicsOdataUri       = Environment.GetEnvironmentVariable("DYNAMICS_ODATA_URI");
            string ssgUsername            = Environment.GetEnvironmentVariable("SSG_USERNAME");
            string ssgPassword            = Environment.GetEnvironmentVariable("SSG_PASSWORD");
            string dynamicsNativeOdataUri = Environment.GetEnvironmentVariable("DYNAMICS_NATIVE_ODATA_URI");

            BCeIDBusinessQuery bCeIDBusinessQuery = new BCeIDBusinessQuery(bceidServiceSvcid, bceidServiceUser, bceidServicePasswd, bceidServiceUrl);

            var serviceClientCredentials = new BasicAuthenticationCredentials()
            {
                UserName = ssgUsername,
                Password = ssgPassword
            };

            var _dynamicsClient = new DynamicsClient(new Uri(dynamicsOdataUri), serviceClientCredentials);

            if (isBackfill)
            {
                var contacts = _dynamicsClient.Contacts.Get().Value;

                foreach (MicrosoftDynamicsCRMcontact contact in contacts)
                {
                    if (string.IsNullOrEmpty(contact.Emailaddress1))
                    {
                        string externalId = contact.AdoxioExternalid;
                        if (!string.IsNullOrEmpty(externalId))
                        {
                            var caller = bCeIDBusinessQuery.ProcessBusinessQuery(externalId);
                            caller.Wait();
                            Gov.Lclb.Cllb.Interfaces.BCeIDBusiness bceidBusiness = caller.Result;

                            if (bceidBusiness != null)
                            {
                                MicrosoftDynamicsCRMcontact patchRecord = new MicrosoftDynamicsCRMcontact();
                                if (string.IsNullOrEmpty(contact.Firstname))
                                {
                                    patchRecord.Firstname = bceidBusiness.individualFirstname;
                                }
                                if (string.IsNullOrEmpty(contact.Lastname))
                                {
                                    patchRecord.Lastname = bceidBusiness.individualSurname;
                                }
                                if (string.IsNullOrEmpty(contact.Middlename))
                                {
                                    patchRecord.Middlename = bceidBusiness.individualMiddlename;
                                }
                                if (string.IsNullOrEmpty(contact.Emailaddress1))
                                {
                                    patchRecord.Emailaddress1 = bceidBusiness.contactEmail;
                                }
                                if (string.IsNullOrEmpty(contact.Telephone1))
                                {
                                    patchRecord.Telephone1 = bceidBusiness.contactPhone;
                                }

                                // update the contact.
                                try
                                {
                                    _dynamicsClient.Contacts.Update(contact.Contactid, patchRecord);
                                    Console.Out.WriteLine("Updated contact " + contact.Firstname + " " + contact.Lastname);
                                }
                                catch (OdataerrorException odee)
                                {
                                    Console.Out.WriteLine("Error patching contact");
                                    Console.Out.WriteLine("Request:");
                                    Console.Out.WriteLine(odee.Request.Content);
                                    Console.Out.WriteLine("Response:");
                                    Console.Out.WriteLine(odee.Response.Content);
                                }
                            }
                        }
                    }
                }

                IList <MicrosoftDynamicsCRMaccount> accounts = null;
                // now get a list of all the related accounts.
                try
                {
                    accounts = _dynamicsClient.Accounts.Get().Value;
                }
                catch (OdataerrorException odee)
                {
                    Console.Out.WriteLine("Error getting accounts");
                    Console.Out.WriteLine("Request:");
                    Console.Out.WriteLine(odee.Request.Content);
                    Console.Out.WriteLine("Response:");
                    Console.Out.WriteLine(odee.Response.Content);
                }

                if (accounts != null)
                {
                    foreach (var account in accounts)
                    {
                        // get the contact.
                        string contactid = account._primarycontactidValue;
                        // only process accounts with missing email address.
                        if (!string.IsNullOrEmpty(contactid) && string.IsNullOrEmpty(account.Emailaddress1))
                        {
                            var    contact = _dynamicsClient.Contacts.GetByKey(contactid);
                            string guid    = contact.AdoxioExternalid;

                            if (!string.IsNullOrEmpty(guid))
                            {
                                var caller = bCeIDBusinessQuery.ProcessBusinessQuery(guid);
                                caller.Wait();
                                Gov.Lclb.Cllb.Interfaces.BCeIDBusiness bceidBusiness = caller.Result;

                                if (bceidBusiness != null)
                                {
                                    MicrosoftDynamicsCRMaccount accountPatchRecord = new MicrosoftDynamicsCRMaccount();
                                    if (string.IsNullOrEmpty(account.Emailaddress1))
                                    {
                                        accountPatchRecord.Emailaddress1 = bceidBusiness.contactEmail;
                                    }
                                    if (string.IsNullOrEmpty(account.Telephone1))
                                    {
                                        accountPatchRecord.Telephone1 = bceidBusiness.contactEmail;
                                    }
                                    if (string.IsNullOrEmpty(account.Address1City))
                                    {
                                        accountPatchRecord.Address1City = bceidBusiness.addressCity;
                                    }
                                    if (string.IsNullOrEmpty(account.Address1Postalcode))
                                    {
                                        accountPatchRecord.Address1Postalcode = bceidBusiness.addressPostal;
                                    }
                                    if (string.IsNullOrEmpty(account.Address1Line1))
                                    {
                                        accountPatchRecord.Address1Line1 = bceidBusiness.addressLine1;
                                    }
                                    if (string.IsNullOrEmpty(account.Address1Line2))
                                    {
                                        accountPatchRecord.Address1Line2 = bceidBusiness.addressLine2;
                                    }
                                    try
                                    {
                                        _dynamicsClient.Accounts.Update(account.Accountid, accountPatchRecord);

                                        Console.Out.WriteLine("Updated account " + account.Name);
                                    }
                                    catch (OdataerrorException odee)
                                    {
                                        Console.Out.WriteLine("Error patching account");
                                        Console.Out.WriteLine("Request:");
                                        Console.Out.WriteLine(odee.Request.Content);
                                        Console.Out.WriteLine("Response:");
                                        Console.Out.WriteLine(odee.Response.Content);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else if (isSingleQuery)
            {
                Console.Out.WriteLine("\"BCEID GUID\",\"Given name\",\"Surname\",\"Email\",\"Phone\",\"Business Number\"");

                // query BCeID
                if (!string.IsNullOrEmpty(singleQuery))
                {
                    var caller = bCeIDBusinessQuery.ProcessBusinessQuery(singleQuery);
                    caller.Wait();
                    var result = caller.Result;
                    if (result != null)
                    {
                        Console.Out.WriteLine("\"" + singleQuery + "\",\"" + result.individualFirstname + "\",\"" + result.individualSurname + "\",\"" + result.contactEmail + "\",\"" + result.contactPhone + "\",\"" + result.businessNumber + "\"");
                    }
                }
            }

            else     // get all contacts.
            {
                // first parse the contacts file.
                List <string> stringList = new List <string>();

                // read from file.

                /*
                 * string jsonString = File.ReadAllText("filename");
                 *
                 *  var jsonData = JsonConvert.DeserializeObject<GetOKResponseModelModelModelModelModelModelModelModel>(jsonString);
                 *  var contacts = jsonData.Value;
                 */

                // Get contacts from dynamics.

                var contacts = _dynamicsClient.Contacts.Get().Value;

                foreach (var contact in contacts)
                {
                    stringList.Add(contact.AdoxioExternalid);
                }

                Console.Out.WriteLine("\"BCEID GUID\",\"Given name\",\"Surname\",\"Email\",\"Phone\",\"Business Number\"");

                foreach (string guid in stringList)
                {
                    // query BCeID
                    if (!string.IsNullOrEmpty(guid))
                    {
                        var caller = bCeIDBusinessQuery.ProcessBusinessQuery(guid);
                        caller.Wait();
                        var result = caller.Result;
                        if (result != null)
                        {
                            Console.Out.WriteLine("\"" + guid + "\",\"" + result.individualFirstname + "\",\"" + result.individualSurname + "\",\"" + result.contactEmail + "\",\"" + result.contactPhone + "\",\"" + result.businessNumber + "\"");
                        }
                    }
                }
            }
        }
示例#9
0
        public static T GetEntityAttribute <T>(this DynamicsClient client, string cast, string entityName, string attributeName, CancellationToken cancellationToken = default(CancellationToken))
        {
            var _baseUrl = client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "EntityDefinitions").ToString();

            _url += $"(LogicalName='{entityName}')/Attributes(LogicalName='{attributeName}')/{cast}?";

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

            _httpRequest.Method     = new HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);

            // Set Credentials
            if (client.Credentials != null)
            {
                client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            _httpResponse = client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult();
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            string _requestContent  = null;

            if ((int)_statusCode != 200)
            {
                var ex = new OdataerrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false).GetAwaiter().GetResult();
                    Odataerror _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Odataerror>(_responseContent, client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <T>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false).GetAwaiter().GetResult();
                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <T>(_responseContent, client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            return(_result.Body);
        }
示例#10
0
        // the one parameter is the BCeID guid for an individual.
        static void Main(string[] args)
        {
            bool isClean = false;


            if (args.Length > 0)
            {
                string arg = args[0];
                if (!string.IsNullOrEmpty(arg))
                {
                    if (arg.ToLower().Equals("clean"))
                    {
                        isClean = true;
                        Console.Out.WriteLine("Clean users enabled");
                    }
                    else
                    {
                        Console.Out.WriteLine("USAGE - enter the clean parameter to clean users for the given environment.");
                    }
                }
            }

            string dynamicsOdataUri       = Environment.GetEnvironmentVariable("DYNAMICS_ODATA_URI");
            string ssgUsername            = Environment.GetEnvironmentVariable("SSG_USERNAME");
            string ssgPassword            = Environment.GetEnvironmentVariable("SSG_PASSWORD");
            string dynamicsNativeOdataUri = Environment.GetEnvironmentVariable("DYNAMICS_NATIVE_ODATA_URI");


            string aadTenantId    = Environment.GetEnvironmentVariable("DYNAMICS_AAD_TENANT_ID");
            string serverAppIdUri = Environment.GetEnvironmentVariable("DYNAMICS_SERVER_APP_ID_URI");
            string clientKey      = Environment.GetEnvironmentVariable("DYNAMICS_CLIENT_KEY");
            string clientId       = Environment.GetEnvironmentVariable("DYNAMICS_CLIENT_ID");

            ServiceClientCredentials serviceClientCredentials = null;

            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();
                var    authenticationResult = task.Result;
                string token = authenticationResult.CreateAuthorizationHeader().Substring("Bearer ".Length);
                serviceClientCredentials = new TokenCredentials(token);
            }
            else
            {
                serviceClientCredentials = new BasicAuthenticationCredentials()
                {
                    UserName = ssgUsername,
                    Password = ssgPassword
                };
            }


            var _dynamicsClient = new DynamicsClient(new Uri(dynamicsOdataUri), serviceClientCredentials);

            if (isClean)
            {
                // remove all BusinessContacts.
                var businessContacts = _dynamicsClient.Businesscontacts.Get().Value;

                foreach (var businessContact in businessContacts)
                {
                    try
                    {
                        _dynamicsClient.Businesscontacts.Delete(businessContact.BcgovBusinesscontactid);
                        Console.Out.WriteLine("Deleted BusinessContact " + businessContact.BcgovBusinesscontactid);
                    }
                    catch (OdataerrorException odee)
                    {
                        Console.Out.WriteLine("Error deleting business contact");
                        Console.Out.WriteLine("Request:");
                        Console.Out.WriteLine(odee.Request.Content);
                        Console.Out.WriteLine("Response:");
                        Console.Out.WriteLine(odee.Response.Content);
                    }
                }

                // remove all incidents (waiver applications etc)
                var incidents = _dynamicsClient.Incidents.Get().Value;

                foreach (var incident in incidents)
                {
                    try
                    {
                        _dynamicsClient.Incidents.Delete(incident.Incidentid);
                        Console.Out.WriteLine("Deleted Incident " + incident.Incidentid);
                    }
                    catch (OdataerrorException odee)
                    {
                        Console.Out.WriteLine("Error deleting incident");
                        Console.Out.WriteLine("Request:");
                        Console.Out.WriteLine(odee.Request.Content);
                        Console.Out.WriteLine("Response:");
                        Console.Out.WriteLine(odee.Response.Content);
                    }
                }


                // remove all business profiles.
                var businessProfiles = _dynamicsClient.Accounts.Get().Value;

                foreach (var businessProfile in businessProfiles)
                {
                    try
                    {
                        _dynamicsClient.Accounts.Delete(businessProfile.Accountid);
                        Console.Out.WriteLine("Deleted BusinessProfile " + businessProfile.Accountid);
                    }
                    catch (OdataerrorException odee)
                    {
                        Console.Out.WriteLine("Error deleting business profile");
                        Console.Out.WriteLine("Request:");
                        Console.Out.WriteLine(odee.Request.Content);
                        Console.Out.WriteLine("Response:");
                        Console.Out.WriteLine(odee.Response.Content);
                    }
                }

                // remove contacts

                var contacts = _dynamicsClient.Contacts.Get().Value;

                foreach (var contact in contacts)
                {
                    try
                    {
                        _dynamicsClient.Contacts.Delete(contact.Contactid);
                        Console.Out.WriteLine("Deleted Contact " + contact.Contactid);
                    }
                    catch (OdataerrorException odee)
                    {
                        Console.Out.WriteLine("Error deleting contact");
                        Console.Out.WriteLine("Request:");
                        Console.Out.WriteLine(odee.Request.Content);
                        Console.Out.WriteLine("Response:");
                        Console.Out.WriteLine(odee.Response.Content);
                    }
                }

                // remove customAddresses

                var customAddresses = _dynamicsClient.Customaddresses.Get().Value;

                foreach (var item in customAddresses)
                {
                    try
                    {
                        _dynamicsClient.Customaddresses.Delete(item.BcgovCustomaddressid);
                        Console.Out.WriteLine("Deleted CustomAddress " + item.BcgovCustomaddressid);
                    }
                    catch (OdataerrorException odee)
                    {
                        Console.Out.WriteLine("Error deleting CustomAddress");
                        Console.Out.WriteLine("Request:");
                        Console.Out.WriteLine(odee.Request.Content);
                        Console.Out.WriteLine("Response:");
                        Console.Out.WriteLine(odee.Response.Content);
                    }
                }

                // remove customProducts

                var customProducts = _dynamicsClient.Customproducts.Get().Value;

                foreach (var item in customProducts)
                {
                    try
                    {
                        _dynamicsClient.Customproducts.Delete(item.BcgovCustomproductid);
                        Console.Out.WriteLine("Deleted customProducts " + item.BcgovCustomproductid);
                    }
                    catch (OdataerrorException odee)
                    {
                        Console.Out.WriteLine("Error deleting customProduct");
                        Console.Out.WriteLine("Request:");
                        Console.Out.WriteLine(odee.Request.Content);
                        Console.Out.WriteLine("Response:");
                        Console.Out.WriteLine(odee.Response.Content);
                    }
                }

                var certificates = _dynamicsClient.Certificates.Get().Value;

                foreach (var item in certificates)
                {
                    try
                    {
                        _dynamicsClient.Certificates.Delete(item.BcgovCertificateid);
                        Console.Out.WriteLine("Deleted certificate " + item.BcgovCertificateid);
                    }
                    catch (OdataerrorException odee)
                    {
                        Console.Out.WriteLine("Error deleting certificate");
                        Console.Out.WriteLine("Request:");
                        Console.Out.WriteLine(odee.Request.Content);
                        Console.Out.WriteLine("Response:");
                        Console.Out.WriteLine(odee.Response.Content);
                    }
                }

                var riskAssessments = _dynamicsClient.Riskassessments.Get().Value;

                foreach (var item in riskAssessments)
                {
                    try
                    {
                        _dynamicsClient.Riskassessments.Delete(item.BcgovRiskassessmentid);
                        Console.Out.WriteLine("Deleted Riskassessment " + item.BcgovRiskassessmentid);
                    }
                    catch (OdataerrorException odee)
                    {
                        Console.Out.WriteLine("Error deleting Riskassessment");
                        Console.Out.WriteLine("Request:");
                        Console.Out.WriteLine(odee.Request.Content);
                        Console.Out.WriteLine("Response:");
                        Console.Out.WriteLine(odee.Response.Content);
                    }
                }

                var equipmentLocations = _dynamicsClient.Equipmentlocations.Get().Value;

                foreach (var item in equipmentLocations)
                {
                    try
                    {
                        _dynamicsClient.Equipmentlocations.Delete(item.BcgovEquipmentlocationid);
                        Console.Out.WriteLine("Deleted Equipmentlocation " + item.BcgovEquipmentlocationid);
                    }
                    catch (OdataerrorException odee)
                    {
                        Console.Out.WriteLine("Error deleting Equipmentlocation");
                        Console.Out.WriteLine("Request:");
                        Console.Out.WriteLine(odee.Request.Content);
                        Console.Out.WriteLine("Response:");
                        Console.Out.WriteLine(odee.Response.Content);
                    }
                }

                var locations = _dynamicsClient.Locations.Get().Value;

                foreach (var item in locations)
                {
                    try
                    {
                        _dynamicsClient.Locations.Delete(item.BcgovLocationid);
                        Console.Out.WriteLine("Deleted location " + item.BcgovLocationid);
                    }
                    catch (OdataerrorException odee)
                    {
                        Console.Out.WriteLine("Error deleting location");
                        Console.Out.WriteLine("Request:");
                        Console.Out.WriteLine(odee.Request.Content);
                        Console.Out.WriteLine("Response:");
                        Console.Out.WriteLine(odee.Response.Content);
                    }
                }

                var equipment = _dynamicsClient.Equipments.Get().Value;

                foreach (var item in equipment)
                {
                    try
                    {
                        _dynamicsClient.Equipments.Delete(item.BcgovEquipmentid);
                        Console.Out.WriteLine("Deleted equipment " + item.BcgovEquipmentid);
                    }
                    catch (OdataerrorException odee)
                    {
                        Console.Out.WriteLine("Error deleting equipment");
                        Console.Out.WriteLine("Request:");
                        Console.Out.WriteLine(odee.Request.Content);
                        Console.Out.WriteLine("Response:");
                        Console.Out.WriteLine(odee.Response.Content);
                    }
                }
            }
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {
            var log = loggerFactory.CreateLogger("Startup");

            string connectionString = "unknown.";

#if (USE_MSSQL)
            if (!string.IsNullOrEmpty(Configuration["DB_PASSWORD"]))
            {
                try
                {
                    using (IServiceScope serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
                    {
                        log.LogDebug("Fetching the application's database context ...");
                        AppDbContext    context        = serviceScope.ServiceProvider.GetService <AppDbContext>();
                        IDynamicsClient dynamicsClient = serviceScope.ServiceProvider.GetService <IDynamicsClient>();

                        connectionString = context.Database.GetDbConnection().ConnectionString;

                        log.LogDebug("Migrating the database ...");
                        context.Database.Migrate();
                        log.LogDebug("The database migration complete.");

                        // run the database seeders
                        log.LogDebug("Adding/Updating seed data ...");

                        Seeders.SeedFactory <AppDbContext> seederFactory = new Seeders.SeedFactory <AppDbContext>(Configuration, env, loggerFactory, dynamicsClient);
                        seederFactory.Seed((AppDbContext)context);
                        log.LogDebug("Seeding operations are complete.");
                    }
                }
                catch (Exception e)
                {
                    StringBuilder msg = new StringBuilder();
                    msg.AppendLine("The database migration failed!");
                    msg.AppendLine("The database may not be available and the application will not function as expected.");
                    msg.AppendLine("Please ensure a database is available and the connection string is correct.");
                    msg.AppendLine("If you are running in a development environment, ensure your test database and server configuration match the project's default connection string.");
                    msg.AppendLine("Which is: " + connectionString);
                    log.LogCritical(new EventId(-1, "Database Migration Failed"), e, msg.ToString());
                }
            }
#else
            // seed for newsletter.

            using (IServiceScope serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                log.LogDebug("Fetching the application's MS Dynamics interface ...");
                var httpClientFactory = serviceScope.ServiceProvider.GetService <System.Net.Http.IHttpClientFactory>();


                var httpClient = httpClientFactory.CreateClient("Dynamics");

                IDynamicsClient dynamicsClient = new DynamicsClient(httpClient, _configuration);


                // run the database seeders
                log.LogDebug("Adding/Updating seed data ...");
                Seeders.SeedFactory <AppDbContext> seederFactory = new Seeders.SeedFactory <AppDbContext>(_configuration, env, loggerFactory, dynamicsClient);
                seederFactory.Seed(null);
                log.LogDebug("Seeding operations are complete.");
            }
#endif


            string pathBase = _configuration["BASE_PATH"];

            if (!string.IsNullOrEmpty(pathBase))
            {
                app.UsePathBase(pathBase);
            }
            if (!env.IsProduction())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(errorApp =>
                {
                    errorApp.Run(async context =>
                    {
                        context.Response.StatusCode  = 500;
                        context.Response.ContentType = "text/html";

                        await context.Response.WriteAsync("An unexpected server error occurred.\r\n");

                        var exceptionHandlerPathFeature =
                            context.Features.Get <IExceptionHandlerPathFeature>();

                        if (exceptionHandlerPathFeature?.Error != null)
                        {
                            Log.Logger.Error(exceptionHandlerPathFeature?.Error, "Unexpected Error");
                        }
                    });
                });
                app.UseHsts(); // Strict-Transport-Security
                app.UseCors(MyAllowSpecificOrigins);
            }

            var healthCheckOptions = new HealthCheckOptions
            {
                ResponseWriter = async(c, r) =>
                {
                    c.Response.ContentType = MediaTypeNames.Application.Json;
                    var result = JsonConvert.SerializeObject(
                        new
                    {
                        checks = r.Entries.Select(e =>
                                                  new
                        {
                            description  = e.Key,
                            status       = e.Value.Status.ToString(),
                            responseTime = e.Value.Duration.TotalMilliseconds
                        }),
                        totalResponseTime = r.TotalDuration.TotalMilliseconds
                    });
                    await c.Response.WriteAsync(result);
                }
            };
            app.UseHealthChecks("/hc/ready", new HealthCheckOptions
            {
                Predicate      = _ => true,
                ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
            });

            app.UseHealthChecks("/hc/live", new HealthCheckOptions
            {
                // Exclude all checks and return a 200-Ok.
                Predicate = (_) => false
            });

            app.UseXContentTypeOptions();
            app.UseXfo(xfo => xfo.Deny());

            StaticFileOptions staticFileOptions = new StaticFileOptions();

            staticFileOptions.OnPrepareResponse = ctx =>
            {
                ctx.Context.Response.Headers[HeaderNames.CacheControl] = "no-cache, no-store, must-revalidate, private";
                ctx.Context.Response.Headers[HeaderNames.Pragma]       = "no-cache";
                ctx.Context.Response.Headers["X-Frame-Options"]        = "SAMEORIGIN";
                ctx.Context.Response.Headers["X-XSS-Protection"]       = "1; mode=block";
                ctx.Context.Response.Headers["X-Content-Type-Options"] = "nosniff";
            };

            app.UseStaticFiles(staticFileOptions);

            app.UseSpaStaticFiles(staticFileOptions);
            app.UseXXssProtection(options => options.EnabledWithBlockMode());
            app.UseNoCacheHttpHeaders();
            // IMPORTANT: This session call MUST go before UseMvc()
            app.UseSession();
            app.UseAuthentication();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });



            // enable Splunk logger using Serilog
            if (!string.IsNullOrEmpty(_configuration["SPLUNK_COLLECTOR_URL"]) &&
                !string.IsNullOrEmpty(_configuration["SPLUNK_TOKEN"])
                )
            {
                Serilog.Sinks.Splunk.CustomFields fields = new Serilog.Sinks.Splunk.CustomFields();
                if (!string.IsNullOrEmpty(_configuration["SPLUNK_CHANNEL"]))
                {
                    fields.CustomFieldList.Add(new Serilog.Sinks.Splunk.CustomField("channel", _configuration["SPLUNK_CHANNEL"]));
                }
                var splunkUri       = new Uri(_configuration["SPLUNK_COLLECTOR_URL"]);
                var upperSplunkHost = splunkUri.Host?.ToUpperInvariant() ?? string.Empty;

                // Fix for bad SSL issues


                Log.Logger = new LoggerConfiguration()
                             .Enrich.FromLogContext()
                             .Enrich.WithExceptionDetails()
                             .WriteTo.Console()
                             .WriteTo.EventCollector(splunkHost: _configuration["SPLUNK_COLLECTOR_URL"],
                                                     sourceType: "portal", eventCollectorToken: _configuration["SPLUNK_TOKEN"],
                                                     restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information,
#pragma warning disable CA2000 // Dispose objects before losing scope
                                                     messageHandler: new HttpClientHandler()
                {
                    ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return(true); }
                }
#pragma warning restore CA2000 // Dispose objects before losing scope
                                                     )
                             .CreateLogger();

                Serilog.Debugging.SelfLog.Enable(Console.Error);

                Log.Logger.Information("CARLA Portal Container Started");
            }
            else
            {
                Log.Logger = new LoggerConfiguration()
                             .Enrich.FromLogContext()
                             .Enrich.WithExceptionDetails()
                             .WriteTo.Console()
                             .CreateLogger();
            }

            if (env.IsDevelopment())
            {
                app.UseSpa(spa =>
                {
                    // To learn more about options for serving an Angular SPA from ASP.NET Core,
                    // see https://go.microsoft.com/fwlink/?linkid=864501

                    spa.Options.SourcePath = "ClientApp";

                    // Only run the angular CLI Server in Development mode (not staging or test.)
                    if (env.IsDevelopment())
                    {
                        spa.UseAngularCliServer(npmScript: "start");
                    }
                });
            }
            else
            {
                Log.Logger.Information("Not enabling single page application hosting from Dotnet - using externally hosted static content.");
            }
        }
示例#12
0
        private void SetupDynamics(IServiceCollection services)
        {
            string redisServer = Configuration["REDIS_SERVER"];

            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"];

            if (string.IsNullOrEmpty(redisServer))
            {
                services.AddDistributedRedisCache(options =>
                {
                    options.Configuration = redisServer;
                });
            }
            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.AddTransient(new Func <IServiceProvider, IDynamicsClient>((serviceProvider) =>
            {
                ServiceClientCredentials serviceClientCredentials = null;

                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;
                    string token             = authenticationResult.CreateAuthorizationHeader().Substring("Bearer ".Length);
                    serviceClientCredentials = new TokenCredentials(token);
                }
                else
                {
                    serviceClientCredentials = new BasicAuthenticationCredentials()
                    {
                        UserName = ssgUsername,
                        Password = ssgPassword
                    };
                }

                IDynamicsClient client = new DynamicsClient(new Uri(Configuration["DYNAMICS_ODATA_URI"]), serviceClientCredentials);

                // set the native client URI
                if (string.IsNullOrEmpty(Configuration["DYNAMICS_NATIVE_ODATA_URI"]))
                {
                    client.NativeBaseUri = new Uri(Configuration["DYNAMICS_ODATA_URI"]);
                }
                else
                {
                    client.NativeBaseUri = new Uri(Configuration["DYNAMICS_NATIVE_ODATA_URI"]);
                }

                return(client);
            }));


            Interfaces.Microsoft.Dynamics.CRM.System context = new Interfaces.Microsoft.Dynamics.CRM.System(new Uri(Configuration["DYNAMICS_ODATA_URI"]));

            // determine if we have a SSG connection.

            if (string.IsNullOrEmpty(ssgUsername) || string.IsNullOrEmpty(ssgPassword))
            {
                context.BuildingRequest += (sender, eventArgs) => eventArgs.Headers.Add(
                    "Authorization", authenticationResult.CreateAuthorizationHeader());
            }
            else
            {
                // authenticate using the SSG.
                string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(ssgUsername + ":" + ssgPassword));

                context.BuildingRequest += (sender, eventArgs) => eventArgs.Headers.Add(
                    "Authorization", "Basic " + credentials);
            }



            services.AddSingleton <Interfaces.Microsoft.Dynamics.CRM.System>(context);

            // add SharePoint.

            string sharePointServerAppIdUri = Configuration["SHAREPOINT_SERVER_APPID_URI"];
            string sharePointOdataUri       = Configuration["SHAREPOINT_ODATA_URI"];
            string sharePointWebname        = Configuration["SHAREPOINT_WEBNAME"];
            string sharePointAadTenantId    = Configuration["SHAREPOINT_AAD_TENANTID"];
            string sharePointClientId       = Configuration["SHAREPOINT_CLIENT_ID"];
            string sharePointCertFileName   = Configuration["SHAREPOINT_CERTIFICATE_FILENAME"];
            string sharePointCertPassword   = Configuration["SHAREPOINT_CERTIFICATE_PASSWORD"];

            services.AddTransient <SharePointFileManager>(_ => new SharePointFileManager(sharePointServerAppIdUri, sharePointOdataUri, sharePointWebname, sharePointAadTenantId, sharePointClientId, sharePointCertFileName, sharePointCertPassword, ssgUsername, ssgPassword));

            // 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    = Environment.GetEnvironmentVariable("BCEP_SERVICE_URL");
            var bcep_svc_svcid  = Environment.GetEnvironmentVariable("BCEP_MERCHANT_ID");
            var bcep_svc_hashid = Environment.GetEnvironmentVariable("BCEP_HASH_KEY");
            var bcep_base_uri   = Environment.GetEnvironmentVariable("BASE_URI");
            var bcep_base_path  = Environment.GetEnvironmentVariable("BASE_PATH");
            var bcep_conf_path  = Environment.GetEnvironmentVariable("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));
        }
        public void Clean(DynamicsClient _dynamicsClient)
        {
            // remove all incidents (waiver applications etc)
            var licences = _dynamicsClient.Licenceses.Get().Value;

            foreach (var licence in licences)
            {
                try
                {
                    _dynamicsClient.Licenceses.Delete(licence.AdoxioLicencesid);
                    Console.Out.WriteLine("Deleted Licence " + licence.AdoxioLicencesid);
                }
                catch (OdataerrorException odee)
                {
                    Console.Out.WriteLine("Error deleting licence");
                    Console.Out.WriteLine("Request:");
                    Console.Out.WriteLine(odee.Request.Content);
                    Console.Out.WriteLine("Response:");
                    Console.Out.WriteLine(odee.Response.Content);
                }
            }

            // remove all BusinessContacts.
            var applications = _dynamicsClient.Applications.Get().Value;

            foreach (var application in applications)
            {
                try
                {
                    _dynamicsClient.Applications.Delete(application.AdoxioApplicationid);
                    Console.Out.WriteLine("Deleted Application " + application.AdoxioApplicationid);
                }
                catch (OdataerrorException odee)
                {
                    Console.Out.WriteLine("Error deleting application");
                    Console.Out.WriteLine("Request:");
                    Console.Out.WriteLine(odee.Request.Content);
                    Console.Out.WriteLine("Response:");
                    Console.Out.WriteLine(odee.Response.Content);
                }
            }

            // remove all BusinessContacts.
            var legalEntities = _dynamicsClient.Legalentities.Get().Value;

            foreach (var legalEntity in legalEntities)
            {
                try
                {
                    _dynamicsClient.Legalentities.Delete(legalEntity.AdoxioLegalentityid);
                    Console.Out.WriteLine("Deleted LegalEntity " + legalEntity.AdoxioLegalentityid);
                }
                catch (OdataerrorException odee)
                {
                    Console.Out.WriteLine("Error deleting application");
                    Console.Out.WriteLine("Request:");
                    Console.Out.WriteLine(odee.Request.Content);
                    Console.Out.WriteLine("Response:");
                    Console.Out.WriteLine(odee.Response.Content);
                }
            }

            var establishments = _dynamicsClient.Establishments.Get().Value;

            foreach (var item in establishments)
            {
                try
                {
                    _dynamicsClient.Establishments.Delete(item.AdoxioEstablishmentid);
                    Console.Out.WriteLine("Deleted Establishment " + item.AdoxioEstablishmentid);
                }
                catch (OdataerrorException odee)
                {
                    Console.Out.WriteLine("Error deleting Establishment");
                    Console.Out.WriteLine("Request:");
                    Console.Out.WriteLine(odee.Request.Content);
                    Console.Out.WriteLine("Response:");
                    Console.Out.WriteLine(odee.Response.Content);
                }
            }

            // remove all business profiles.
            var accounts = _dynamicsClient.Accounts.Get().Value;

            foreach (var account in accounts)
            {
                try
                {
                    _dynamicsClient.Accounts.Delete(account.Accountid);
                    Console.Out.WriteLine("Deleted BusinessProfile " + account.Accountid);
                }
                catch (OdataerrorException odee)
                {
                    Console.Out.WriteLine("Error deleting business profile");
                    Console.Out.WriteLine("Request:");
                    Console.Out.WriteLine(odee.Request.Content);
                    Console.Out.WriteLine("Response:");
                    Console.Out.WriteLine(odee.Response.Content);
                }
            }


            // remove workers

            var workers = _dynamicsClient.Workers.Get().Value;

            foreach (var item in workers)
            {
                try
                {
                    _dynamicsClient.Workers.Delete(item.AdoxioWorkerid);
                    Console.Out.WriteLine("Deleted worker " + item.AdoxioWorkerid);
                }
                catch (OdataerrorException odee)
                {
                    Console.Out.WriteLine("Error deleting worker");
                    Console.Out.WriteLine("Request:");
                    Console.Out.WriteLine(odee.Request.Content);
                    Console.Out.WriteLine("Response:");
                    Console.Out.WriteLine(odee.Response.Content);
                }
            }

            var aliases = _dynamicsClient.Aliases.Get().Value;

            foreach (var item in aliases)
            {
                try
                {
                    _dynamicsClient.Aliases.Delete(item.AdoxioAliasid);
                    Console.Out.WriteLine("Deleted alias " + item.AdoxioAliasid);
                }
                catch (OdataerrorException odee)
                {
                    Console.Out.WriteLine("Error deleting alias");
                    Console.Out.WriteLine("Request:");
                    Console.Out.WriteLine(odee.Request.Content);
                    Console.Out.WriteLine("Response:");
                    Console.Out.WriteLine(odee.Response.Content);
                }
            }


            // remove contacts
            var contacts = _dynamicsClient.Contacts.Get().Value;

            foreach (var contact in contacts)
            {
                try
                {
                    _dynamicsClient.Contacts.Delete(contact.Contactid);
                    Console.Out.WriteLine("Deleted Contact " + contact.Contactid);
                }
                catch (OdataerrorException odee)
                {
                    Console.Out.WriteLine("Error deleting contact");
                    Console.Out.WriteLine("Request:");
                    Console.Out.WriteLine(odee.Request.Content);
                    Console.Out.WriteLine("Response:");
                    Console.Out.WriteLine(odee.Response.Content);
                }
            }

            // remove invoices
            var invoices = _dynamicsClient.Invoices.Get().Value;

            foreach (var invoice in invoices)
            {
                try
                {
                    _dynamicsClient.Invoices.Delete(invoice.Invoiceid);
                    Console.Out.WriteLine("Deleted Invoice " + invoice.Invoiceid);
                }
                catch (OdataerrorException odee)
                {
                    Console.Out.WriteLine("Error deleting invoice");
                    Console.Out.WriteLine("Request:");
                    Console.Out.WriteLine(odee.Request.Content);
                    Console.Out.WriteLine("Response:");
                    Console.Out.WriteLine(odee.Response.Content);
                }
            }
        }