public ContactController(Interfaces.Microsoft.Dynamics.CRM.System context, IConfiguration configuration, IDistributedCache distributedCache, IHttpContextAccessor httpContextAccessor) { Configuration = configuration; this._system = context; this._httpContextAccessor = httpContextAccessor; this._distributedCache = null; // distributedCache; }
public AccountController(Interfaces.Microsoft.Dynamics.CRM.System context, IConfiguration configuration, IDistributedCache distributedCache, IHttpContextAccessor httpContextAccessor, BCeIDBusinessQuery bceid, ILoggerFactory loggerFactory, IDynamicsClient dynamicsClient) { Configuration = configuration; this._system = context; this._distributedCache = null; //distributedCache; this._httpContextAccessor = httpContextAccessor; this._bceid = bceid; this._dynamicsClient = dynamicsClient; _logger = loggerFactory.CreateLogger(typeof(AccountController)); }
public AdoxioApplicationController(Interfaces.Microsoft.Dynamics.CRM.System context, SharePointFileManager sharePointFileManager, IConfiguration configuration, IDistributedCache distributedCache, IHttpContextAccessor httpContextAccessor, ILoggerFactory loggerFactory, IDynamicsClient dynamicsClient) { Configuration = configuration; this._system = context; this._httpContextAccessor = httpContextAccessor; this._sharePointFileManager = sharePointFileManager; //this._distributedCache = null; this._dynamicsClient = dynamicsClient; _logger = loggerFactory.CreateLogger(typeof(AdoxioLegalEntityController)); }
public PaymentController(Interfaces.Microsoft.Dynamics.CRM.System context, IConfiguration configuration, IHttpContextAccessor httpContextAccessor, ILoggerFactory loggerFactory, IDynamicsClient dynamicsClient, BCEPWrapper bcep) { Configuration = configuration; this._system = context; this._httpContextAccessor = httpContextAccessor; this._dynamicsClient = dynamicsClient; this._bcep = bcep; _logger = loggerFactory.CreateLogger(typeof(PaymentController)); }
public SystemFormController(Interfaces.Microsoft.Dynamics.CRM.System context, IConfiguration configuration, IDistributedCache distributedCache) { Configuration = configuration; this._system = context; this._distributedCache = null; // distributedCache; }
/// <summary> /// Process Authentication Request /// </summary> /// <returns></returns> protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { // get siteminder headers _logger.LogDebug("Parsing the HTTP headers for SiteMinder authentication credential"); SiteMinderAuthOptions options = new SiteMinderAuthOptions(); bool isDeveloperLogin = false; bool isBCSCDeveloperLogin = false; try { ClaimsPrincipal principal; HttpContext context = Request.HttpContext; Interfaces.Microsoft.Dynamics.CRM.System _system = (Interfaces.Microsoft.Dynamics.CRM.System)context.RequestServices.GetService(typeof(Interfaces.Microsoft.Dynamics.CRM.System)); IDistributedCache _distributedCache = null; // (IDistributedCache) context.RequestServices.GetService(typeof(IDistributedCache)); IHostingEnvironment hostingEnv = (IHostingEnvironment)context.RequestServices.GetService(typeof(IHostingEnvironment)); UserSettings userSettings = new UserSettings(); string userId = null; string devCompanyId = null; string siteMinderGuid = ""; string siteMinderBusinessGuid = ""; string siteMinderUserType = ""; // ************************************************** // If this is an Error or Authentiation API - Ignore // ************************************************** string url = context.Request.GetDisplayUrl().ToLower(); if (url.Contains(".js")) { return(AuthenticateResult.NoResult()); } // ************************************************** // Check if we have a Dev Environment Cookie // ************************************************** if (!hostingEnv.IsProduction()) { // check for a fake BCeID login in dev mode string temp = context.Request.Cookies[options.DevAuthenticationTokenKey]; if (string.IsNullOrEmpty(temp)) // could be an automated test user. { temp = context.Request.Headers["DEV-USER"]; } if (!string.IsNullOrEmpty(temp)) { if (temp.Contains("::")) { var temp2 = temp.Split("::"); userId = temp2[0]; if (temp2.Length >= 2) { devCompanyId = temp2[1]; } else { devCompanyId = temp2[0]; } } else { userId = temp; devCompanyId = temp; } isDeveloperLogin = true; _logger.LogDebug("Got user from dev cookie = " + userId + ", company = " + devCompanyId); } else { // same set of tests for a BC Services Card dev login temp = context.Request.Cookies[options.DevBCSCAuthenticationTokenKey]; if (string.IsNullOrEmpty(temp)) // could be an automated test user. { temp = context.Request.Headers["DEV-BCSC-USER"]; } if (!string.IsNullOrEmpty(temp)) { userId = temp; isBCSCDeveloperLogin = true; _logger.LogDebug("Got user from dev cookie = " + userId); } } } // ************************************************** // Check if the user session is already created // ************************************************** try { _logger.LogInformation("Checking user session"); userSettings = UserSettings.ReadUserSettings(context); _logger.LogDebug("UserSettings found: " + userSettings.GetJson()); } catch { //do nothing _logger.LogDebug("No UserSettings found"); } // is user authenticated - if so we're done if ((userSettings.UserAuthenticated && string.IsNullOrEmpty(userId)) || (userSettings.UserAuthenticated && !string.IsNullOrEmpty(userId) && !string.IsNullOrEmpty(userSettings.UserId) && userSettings.UserId == userId)) { _logger.LogDebug("User already authenticated with active session: " + userSettings.UserId); principal = userSettings.AuthenticatedUser.ToClaimsPrincipal(options.Scheme); return(AuthenticateResult.Success(new AuthenticationTicket(principal, null, Options.Scheme))); } string smgov_userdisplayname = context.Request.Headers["smgov_userdisplayname"]; if (!string.IsNullOrEmpty(smgov_userdisplayname)) { userSettings.UserDisplayName = smgov_userdisplayname; } string smgov_businesslegalname = context.Request.Headers["smgov_businesslegalname"]; if (!string.IsNullOrEmpty(smgov_businesslegalname)) { userSettings.BusinessLegalName = smgov_businesslegalname; } // ************************************************** // Authenticate based on SiteMinder Headers // ************************************************** _logger.LogDebug("Parsing the HTTP headers for SiteMinder authentication credential"); // At this point userID would only be set if we are logging in through as a DEV user if (string.IsNullOrEmpty(userId)) { _logger.LogDebug("Getting user data from headers"); userId = context.Request.Headers[options.SiteMinderUserNameKey]; if (string.IsNullOrEmpty(userId)) { userId = context.Request.Headers[options.SiteMinderUniversalIdKey]; } siteMinderGuid = context.Request.Headers[options.SiteMinderUserGuidKey]; siteMinderBusinessGuid = context.Request.Headers[options.SiteMinderBusinessGuidKey]; siteMinderUserType = context.Request.Headers[options.SiteMinderUserTypeKey]; // ************************************************** // Validate credentials // ************************************************** if (string.IsNullOrEmpty(userId)) { _logger.LogError(options.MissingSiteMinderUserIdError); return(AuthenticateResult.Fail(options.MissingSiteMinderGuidError)); } if (string.IsNullOrEmpty(siteMinderGuid)) { _logger.LogError(options.MissingSiteMinderGuidError); return(AuthenticateResult.Fail(options.MissingSiteMinderGuidError)); } if (string.IsNullOrEmpty(siteMinderUserType)) { _logger.LogError(options.MissingSiteMinderUserTypeError); return(AuthenticateResult.Fail(options.MissingSiteMinderUserTypeError)); } } else // DEV user, setup a fake session and SiteMinder headers. { if (isDeveloperLogin) { _logger.LogError("Generating a Development user"); userSettings.BusinessLegalName = devCompanyId + " TestBusiness"; userSettings.UserDisplayName = userId + " TestUser"; siteMinderGuid = GuidUtility.CreateIdForDynamics("contact", userSettings.UserDisplayName).ToString(); siteMinderBusinessGuid = GuidUtility.CreateIdForDynamics("account", userSettings.BusinessLegalName).ToString(); siteMinderUserType = "Business"; } else if (isBCSCDeveloperLogin) { _logger.LogError("Generating a Development BC Services user"); userSettings.BusinessLegalName = null; userSettings.UserDisplayName = userId + " Associate"; siteMinderGuid = GuidUtility.CreateIdForDynamics("bcsc", userSettings.UserDisplayName).ToString(); siteMinderBusinessGuid = null; siteMinderUserType = "BC Services Card"; } } // Previously the code would do a database lookup here. However there is no backing database for the users table now, // so we just do a Dynamics lookup on the siteMinderGuid. _logger.LogDebug("Loading user external id = " + siteMinderGuid); userSettings.AuthenticatedUser = await _system.LoadUser(_distributedCache, siteMinderGuid); _logger.LogDebug("After getting authenticated user = "******" (" + userId + ")"); return(AuthenticateResult.Fail(options.InactivegDbUserIdError)); } if (userSettings.AuthenticatedUser != null && !String.IsNullOrEmpty(siteMinderUserType)) { userSettings.AuthenticatedUser.UserType = siteMinderUserType; } // This line gets the various claims for the current user. ClaimsPrincipal userPrincipal = userSettings.AuthenticatedUser.ToClaimsPrincipal(options.Scheme); // ************************************************** // Create authenticated user // ************************************************** _logger.LogDebug("Authentication successful: " + userId); _logger.LogDebug("Setting identity and creating session for: " + userId); // create session info for the current user userSettings.UserId = userId; userSettings.UserAuthenticated = true; userSettings.IsNewUserRegistration = (userSettings.AuthenticatedUser == null); // set other session info userSettings.SiteMinderGuid = siteMinderGuid; userSettings.SiteMinderBusinessGuid = siteMinderBusinessGuid; _logger.LogDebug("Before getting contact and account ids = " + userSettings.GetJson()); if (userSettings.AuthenticatedUser != null && siteMinderBusinessGuid != null) { userSettings.ContactId = userSettings.AuthenticatedUser.ContactId.ToString(); var account = await _system. GetAccountBySiteminderBusinessGuid(_distributedCache, siteMinderBusinessGuid); if (account != null) { userSettings.AccountId = account.Accountid.ToString(); userSettings.AuthenticatedUser.AccountId = (Guid)account.Accountid; } } if (!hostingEnv.IsProduction() && (isDeveloperLogin || isBCSCDeveloperLogin)) { _logger.LogError("DEV MODE Setting identity and creating session for: " + userId); if (isDeveloperLogin) { userSettings.BusinessLegalName = devCompanyId + " TestBusiness"; userSettings.UserDisplayName = userId + " TestUser"; // add generated guids userSettings.SiteMinderBusinessGuid = GuidUtility.CreateIdForDynamics("account", userSettings.BusinessLegalName).ToString(); userSettings.SiteMinderGuid = GuidUtility.CreateIdForDynamics("contact", userSettings.UserDisplayName).ToString(); } else if (isBCSCDeveloperLogin) { userSettings.BusinessLegalName = null; userSettings.UserDisplayName = userId + " Associate"; // add generated guids userSettings.SiteMinderBusinessGuid = null; userSettings.SiteMinderGuid = GuidUtility.CreateIdForDynamics("bcsc", userSettings.UserDisplayName).ToString(); } if (userSettings.IsNewUserRegistration) { if (isDeveloperLogin) { // add generated guids userSettings.AccountId = userSettings.SiteMinderBusinessGuid; userSettings.ContactId = userSettings.SiteMinderGuid; } else if (isBCSCDeveloperLogin) { // set to null for now userSettings.AccountId = null; userSettings.ContactId = null; } _logger.LogError("New user registration:" + userSettings.UserDisplayName); _logger.LogError("userSettings.SiteMinderBusinessGuid:" + userSettings.SiteMinderBusinessGuid); _logger.LogError("userSettings.SiteMinderGuid:" + userSettings.SiteMinderGuid); _logger.LogError("userSettings.AccountId:" + userSettings.AccountId); _logger.LogError("userSettings.ContactId:" + userSettings.ContactId); } // Set account ID from authenticated user else if (userSettings.AuthenticatedUser != null) { // populate the business GUID. if (string.IsNullOrEmpty(userSettings.AccountId)) { userSettings.AccountId = userSettings.AuthenticatedUser.AccountId.ToString(); } if (string.IsNullOrEmpty(userSettings.ContactId)) { userSettings.ContactId = userSettings.AuthenticatedUser.ContactId.ToString(); } _logger.LogError("Returning user:"******"userSettings.AccountId:" + userSettings.AccountId); _logger.LogError("userSettings.ContactId:" + userSettings.ContactId); } } else if (!hostingEnv.IsProduction() && isBCSCDeveloperLogin) { } // ************************************************** // Update user settings // ************************************************** UserSettings.SaveUserSettings(userSettings, context); // done! principal = userPrincipal; return(AuthenticateResult.Success(new AuthenticationTicket(principal, null, Options.Scheme))); } catch (Exception exception) { _logger.LogError(exception.Message); Console.WriteLine(exception); throw; } }
public async static Task <AdoxioLicense> ToViewModel(this Adoxio_licences dynamicsLicense, Interfaces.Microsoft.Dynamics.CRM.System _system) { AdoxioLicense adoxioLicenseVM = new AdoxioLicense(); // fetch the establishment and get name and address Guid?adoxioEstablishmentId = dynamicsLicense._adoxio_establishment_value; if (adoxioEstablishmentId != null) { Interfaces.Microsoft.Dynamics.CRM.Adoxio_establishment establishment = await _system.Adoxio_establishments.ByKey(adoxio_establishmentid : adoxioEstablishmentId).GetValueAsync(); adoxioLicenseVM.establishmentName = establishment.Adoxio_name; adoxioLicenseVM.establishmentAddress = establishment.Adoxio_addressstreet + ", " + establishment.Adoxio_addresscity + " " + establishment.Adoxio_addresspostalcode; } // fetch the licence status int?adoxio_licenceStatusId = dynamicsLicense.Statuscode; if (adoxio_licenceStatusId != null) { adoxioLicenseVM.licenseStatus = dynamicsLicense.Statuscode.ToString(); } // fetch the licence type Guid?adoxio_licencetypeId = dynamicsLicense._adoxio_licencetype_value; if (adoxio_licencetypeId != null) { Adoxio_licencetype adoxio_licencetype = await _system.Adoxio_licencetypes.ByKey(adoxio_licencetypeid : adoxio_licencetypeId).GetValueAsync(); adoxioLicenseVM.licenseType = adoxio_licencetype.Adoxio_name; } // fetch license number adoxioLicenseVM.licenseNumber = dynamicsLicense.Adoxio_licencenumber; return(adoxioLicenseVM); }
/// <summary> /// Copy values from View Model to Dynamics legal entity /// </summary> /// <param name="to"></param> /// <param name="from"></param> public static void CopyValues(this Adoxio_legalentity to, ViewModels.AdoxioLegalEntity from, Interfaces.Microsoft.Dynamics.CRM.System _system) { to.Adoxio_commonnonvotingshares = from.commonnonvotingshares; to.Adoxio_commonvotingshares = from.commonvotingshares; to.Adoxio_dateofbirth = from.dateofbirth; to.Adoxio_firstname = from.firstname; to.Adoxio_interestpercentage = from.interestpercentage; to.Adoxio_isindividual = (from.isindividual != null && (bool)from.isindividual) ? 1 : 0; to.Adoxio_lastname = from.lastname; to.Adoxio_legalentitytype = (int?)from.legalentitytype; to.Adoxio_middlename = from.middlename; to.Adoxio_name = from.name; to.Adoxio_ispartner = (from.isPartner == true); to.Adoxio_isshareholder = from.isShareholder; to.Adoxio_istrustee = false; to.Adoxio_isdirector = from.isDirector; to.Adoxio_isofficer = from.isOfficer; to.Adoxio_isowner = false; to.Adoxio_preferrednonvotingshares = from.preferrednonvotingshares; to.Adoxio_preferredvotingshares = from.preferredvotingshares; to.Adoxio_sameasapplyingperson = (from.sameasapplyingperson != null && (bool)from.sameasapplyingperson) ? 1 : 0; to.Adoxio_email = from.email; to.Adoxio_dateofappointment = from.dateofappointment; // Assigning the account this way throws exception: // System.InvalidOperationException: Collection was modified; enumeration operation may not execute. //if (from.account.id != null) //{ // // fetch the account from Dynamics. // var getAccountTask = _system.GetAccountById(null, Guid.Parse(from.account.id)); // getAccountTask.Wait(); // to.Adoxio_Account= getAccountTask.Result; //} // adoxio_dateemailsent }
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)); }