public DbDataTests() { ConfigurationManagerHelper.AddDbProvider(); ConfigurationManagerHelper.ToggleConnectionStringsWrite(); _settings = new ConnectionStringSettings( ConnectionName, ConnectionString, ProviderName ); ConfigurationManager.ConnectionStrings.Add(_settings); _connection = new Mock <IDbConnection>(); _command = new Mock <IDbCommand>(); _data = new DbData(ConnectionName); _data.Connection = _connection.Object; _data.Command = _command.Object; }
public static string CreateTempDir(string id, string path) { var tempDir = ConfigurationManagerHelper.GetValueOnKey("stardust.StoreLocation") + "\\bck_temp\\"; if (Directory.Exists(tempDir)) { Directory.Delete(tempDir, true); } Directory.CreateDirectory(tempDir); //foreach (var enumerateFile in Directory.EnumerateFiles(path)) //{ // var finfo = new FileInfo(enumerateFile); // finfo.CopyTo(tempDir + "\\" + finfo.Name, true); //} return(tempDir); }
private static string GetMetadataFromFederationServer(string issuerAddress, WebClient client, string metadataLocation) { var data = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"; try { data += client.DownloadString(metadataLocation); } catch (Exception ex) { if (ConfigurationManagerHelper.GetValueOnKey("stardust.Debug") == "true") { Logging.Exception(ex, string.Format("Unable to download federation metadata for {0}", issuerAddress)); } } return(data); }
public ActionResult Index(HttpPostedFileBase file) { try { var fileName = string.Format("{0}\\{1}.bbs", ConfigurationManagerHelper.GetValueOnKey("stardust.StoreLocation"), DateTime.Now.Ticks); file.SaveAs(fileName); RepositoryFactory.Restore(fileName); } catch (Exception ex) { ex.Log(); } Thread.Sleep(100); var stores = Directory.EnumerateDirectories(ConfigurationManagerHelper.GetValueOnKey("stardust.StoreLocation")).Select(Path.GetDirectoryName); return(RedirectToAction("Index")); }
public ActionResult Backup(string id) { try { var path = Path.Combine(ConfigurationManagerHelper.GetValueOnKey("stardust.StoreLocation"), id); var tempDir = RepositoryFactory.CreateTempDir(id, path); var file = string.Format("{0}\\{1}.zip", ConfigurationManagerHelper.GetValueOnKey("stardust.StoreLocation"), id); var finfo = RepositoryFactory.Backup(file, tempDir); return(File(finfo.FullName, "application/zip, application/octet-stream", string.Format("{0}.zip", id))); } catch (Exception ex) { ex.Log(); var currentStore = RepositoryFactory.GetConnectionString().Split(';').Last().Split('=').Last(); var lastFile = Directory.GetFiles(ConfigurationManagerHelper.GetValueOnKey("stardust.StoreLocation")).Where(f => f.Contains(currentStore) && !f.Contains(currentStore + ".zip")).OrderBy(s => s).SingleOrDefault(); return(File(lastFile, "application/zip, application/octet-stream", string.Format("{0}.zip", id))); } }
/// <summary> /// Creat model. /// </summary> /// <param name="modelBuilder">model builder</param> protected override void OnModelCreating(DbModelBuilder modelBuilder) { try { base.OnModelCreating(modelBuilder); OnUserModelCreating(modelBuilder); OnAcvtivityModelCreating(modelBuilder); OnNewsModelCreating(modelBuilder); OnOccurrenceModelCreating(modelBuilder); OnRessourceModelCreating(modelBuilder); OnCountryModelCreating(modelBuilder); OnSectionModelCreating(modelBuilder); OnNewsletterModelCreating(modelBuilder); OnAboutModelCreating(modelBuilder); OnStepModelCreating(modelBuilder); modelBuilder.HasDefaultSchema(ConfigurationManagerHelper.GetAppSettingsToString(Constant.OmsDefaultSchema, string.Empty)); modelBuilder.Properties().Where(p => p.PropertyType == typeof(string) && p.GetCustomAttributes(typeof(MaxLengthAttribute), false).Length == 0).Configure(p => p.HasMaxLength(int.MaxValue)); var entityMethod = typeof(DbModelBuilder).GetMethod("Entity"); var activeServices = ServiceActivation.GetAllActivatedServices().ToList(); foreach (var service in activeServices) { var entityAssembly = ServiceSettings.GetEntityAssembly(service); var dependencies = ServiceSettings.GetAllServiceDependencies(service).ToSystemTypeList(entityAssembly); foreach (var type in dependencies) { if (entityMethod != null) { entityMethod.MakeGenericMethod(type).Invoke(modelBuilder, new object[] { }); } } var configs = ServiceSettings.GetAllServiceConfigurationDependencies(service).ToSystemTypeList(entityAssembly); foreach (var type in configs) { dynamic configurationInstance = Activator.CreateInstance(type); modelBuilder.Configurations.Add(configurationInstance); } } } catch (Exception ex) { throw new ArgumentNullException(ex.Message); } }
public void Configuration(IAppBuilder app) { if (ConfigurationManagerHelper.GetValueOnKey("stardust.UseAzureAd") == "true") { ConfigureAuth(app); } if (ConfigurationManagerHelper.GetValueOnKey("stardust.UseRealtimeUpdate") == "true") { app.MapSignalR("/signalr", new HubConfiguration { EnableJSONP = true, EnableDetailedErrors = true, EnableJavaScriptProxies = true }); hub = GlobalHost.ConnectionManager.GetHubContext <ConfigSetHub>(); Resolver.Activate <ICacheManagementService>().RegisterRealtimeNotificationService( (id, environment) => { try { Logging.DebugMessage("Sending update message {0}-{1}", id, environment); hub.Clients.All.changed(id, environment); } catch (Exception ex) { ex.Log(); } }); if (!Utilities.IsDevelopementEnv()) { return; } hubConnection = new HubConnection("https://localhost:44305/"); hubClient = hubConnection.CreateHubProxy("configSetHub"); hubClient.On( "changed", (string id, string environment) => { Logging.DebugMessage("UpdateMessage: {0}-{1}", id, environment); }); hubConnection.Start(); } }
private static FaultException <ErrorMessage> ConstructErrorMessage(Exception exception, ITracer data, IServiceBase service) { if (ConfigurationManagerHelper.GetValueOnKey("stardust.useWcfWebFault", false)) { return(new WebFaultException <ErrorMessage>(new ErrorMessage { Message = exception.Message, FaultLocation = data.GetCallstack().ErrorPath, TicketNumber = service.Runtime.InstanceId, Detail = ErrorDetail.GetDetails(exception) }, HttpStatusCode.InternalServerError)); } var error = new FaultException <ErrorMessage>(new ErrorMessage { Message = exception.Message, FaultLocation = data.GetCallstack().ErrorPath, TicketNumber = service.Runtime.InstanceId, Detail = ErrorDetail.GetDetails(exception) }, exception.Message); return(error); }
public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary <string, object> values, HttpRouteDirection routeDirection) { if (routeDirection != HttpRouteDirection.UriResolution) { return(false); } IConfigurationManagerHelper configurationManagerHelper = request.GetDependencyScope().GetService(typeof(IConfigurationManagerHelper)) as IConfigurationManagerHelper; if (configurationManagerHelper == null) { configurationManagerHelper = new ConfigurationManagerHelper(); } var version = GetVersionHeader(request, configurationManagerHelper) ?? configurationManagerHelper.GetSettingOrDefaultValue(VersionConstants.ConfVersionDefault, VersionConstants.VersionDefault); return(version == allowedVersion); }
public void ConfigureAuth(IAppBuilder app) { if (ConfigurationManagerHelper.GetValueOnKey <bool>("stardust.useAzureAd")) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = ConfigurationManagerHelper.GetValueOnKey("stardust.fererationClientId"), Authority = ConfigurationManagerHelper.GetValueOnKey("stardust.fererationAuthority"), Notifications = new OpenIdConnectAuthenticationNotifications { AuthenticationFailed = context => { context.HandleResponse(); context.Response.Redirect("/Error?message=" + context.Exception.Message); return(Task.FromResult(0)); } } }); app.UseWindowsAzureActiveDirectoryBearerAuthentication( new WindowsAzureActiveDirectoryBearerAuthenticationOptions { Tenant = ConfigurationManagerHelper.GetValueOnKey("stardust.fererationTenant"), TokenValidationParameters = new TokenValidationParameters { ValidAudience = ConfigurationManagerHelper.GetValueOnKey("stardust.fererationAudience"), ValidAudiences = new List <string> { ConfigurationManagerHelper.GetValueOnKey("stardust.fererationAudience"), ConfigurationManagerHelper.GetValueOnKey("stardust.fererationAudience") + "/" }, } }); } }
public void Bind(IConfigurator configuration) { var azureServiceTokenProvider = new AzureServiceTokenProvider(); var keyVaultClient = new KeyVaultClient(async(authority, resource, scope) => await azureServiceTokenProvider.GetAccessTokenAsync(resource)); var cosmosDbAccount = keyVaultClient.GetSecretAsync("https://stardust-test-vault.vault.azure.net/", "cosmosAccountName").Result; var cosmosDbKey = keyVaultClient .GetSecretAsync("https://stardust-test-vault.vault.azure.net/", "cosmosAccountKey").Result; configuration.AddEntityBinding((type, type1) => { configuration.Bind(type).To(type1).SetTransientScope(); }) .Bind <IGremlinLanguageConnector>() .ToConstructor(s => new GremlinNetLanguageConnector($"{cosmosDbAccount.Value}.gremlin.cosmosdb.azure.com", "graphTest", "services", cosmosDbKey.Value)); GremlinFactory.SetActivatorFactory(() => new GremlinNetLanguageConnector($"{cosmosDbAccount.Value}.gremlin.cosmosdb.azure.com", "graphTest", "services", cosmosDbKey.Value)); ConfigurationManagerHelper.SetValueOnKey("cosmosDbAccount", cosmosDbAccount.Value); ConfigurationManagerHelper.SetValueOnKey("cosmosDbKey", cosmosDbKey.Value); }
public void Error(Exception exception, string additionalDebugInformation) { if (!ConfigurationManagerHelper.GetValueOnKey("stardust.logToKeen", false)) { return; } try { keenClient.AddEventAsync(string.Format("{0}.Error.Details", "Config"), new { exception.Message, exception.StackTrace, DebugMessage = additionalDebugInformation, TimeStamp = DateTime.UtcNow, }); } catch (Exception ex) { } }
public void Debug(string message, EventLogEntryType entryType, string additionalDebugInformation) { if (!ConfigurationManagerHelper.GetValueOnKey("stardust.logToKeen", false)) { return; } try { keenClient.AddEventAsync(string.Format("{0}.Debug.Details", "Config"), new { Message = message, DebugMessage = additionalDebugInformation, entryType, TimeStamp = DateTime.UtcNow, }); } catch (Exception ex) { // ex.Log(); } }
private static async Task ValidatePolicies(AuthorizationCodeReceivedNotification notification) { _debugLogger?.Invoke($"Validating policies with api: {VeracityApiUrl}"); var validator = ServiceProviderFactory?.Invoke()?.GetService(typeof(IPolicyValidation)) as IPolicyValidation; if (validator != null) { var policy = ConfigurationManagerHelper.GetValueOnKey("serviceId").ContainsCharacters() ? await validator.ValidatePolicyWithServiceSpesificTerms(ConfigurationManagerHelper.GetValueOnKey("serviceId"), notification.RedirectUri) : await validator.ValidatePolicy(notification.RedirectUri ?? _redirectUrl); if (!policy.AllPoliciesValid) { _debugLogger?.Invoke($"policies validated, redirecting to {policy.RedirectUrl} for approval"); notification.Response.Redirect(policy.RedirectUrl); notification.HandleResponse(); return; } } _debugLogger?.Invoke($"policies validated"); }
public Binding Create(Endpoint serviceInterface) { var binding = new WebHttpBinding(WebHttpSecurityMode.Transport) { AllowCookies = false, HostNameComparisonMode = serviceInterface.HostNameComparisonMode.ParseAsEnum(HostNameComparisonMode.WeakWildcard), MaxBufferPoolSize = serviceInterface.MaxBufferPoolSize, MaxReceivedMessageSize = serviceInterface.MaxReceivedSize, ReaderQuotas = XmlDictionaryReaderQuotas.Max, BypassProxyOnLocal = true, UseDefaultWebProxy = false, MaxBufferSize = serviceInterface.MaxBufferSize, }; if (ConfigurationManagerHelper.GetValueOnKey("stardust.UseDefaultProxy") == "true") { binding.BypassProxyOnLocal = false; binding.UseDefaultWebProxy = true; } return(binding); }
protected DocumentRow ParseRow(string row, Document document) { var documentRow = new DocumentRow(document); string[] rowContent; if (ConfigurationManagerHelper.GetValueOnKey("stardust.useRegexParsing") == "true") { var regex = @",(?=(?:[^\""]*\""[^\""]*\"")*(?![^\""]*\""))"; var myRegex = new Regex(regex, RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace); rowContent = myRegex.Split(row); } else { rowContent = row.Replace("\r", "").Split(Delimiter.ToCharArray()); } foreach (var collumn in GetCells(rowContent)) { AddColumn(documentRow, collumn); } return(documentRow); }
private static void RegisterUpdateHandler() { //ContainerFactory.Current.InvalidateBinding(typeof(IConfigurationReader), Scope.Singleton); //Resolver.GetConfigurator().UnBind<IConfigurationReader>().AllAndBind().To<StarterkitConfigurationReaderEx>().SetSingletonScope(); hubConnection = new HubConnection(Utilities.GetConfigLocation()) { //GroupsToken = string.Format("{0}-{1}", GetConfigSetName(), GetEnvironmentName()) }; hub = hubConnection.CreateHubProxy("notificationHub"); hub.On("notify", (string id, string env) => { if (id != GetConfigSetName() || env != GetEnvironmentName()) { Logging.DebugMessage("NotMe, exiting"); return; } Logging.DebugMessage("update config"); MemoryCache.Default.Remove(string.Format("{0}{1}", GetConfigSetName(), GetEnvironmentName())); var reader = Resolver.Activate <IConfigurationReader>(); var set = reader.GetConfiguration(id, env); StarterkitConfigurationReaderEx.Notify(set); }); hub.On("joinConfirmation", s => { Logging.DebugMessage("Join successfull: {0}", s); }); var key = ConfigurationManagerHelper.GetValueOnKey("stardust.accessTokenKey"); hubConnection.Headers.Add("set", GetConfigSetName()); hubConnection.Headers.Add("env", GetEnvironmentName()); var keyName = key.ContainsCharacters() ? key : string.Format("{0}-{1}", GetConfigSetName(), GetEnvironmentName()).ToLower(); hubConnection.Headers.Add("key", keyName); hubConnection.Headers.Add("Token", GetAccessToken()); hubConnection.CookieContainer = new CookieContainer(); hubConnection.EnsureReconnecting(); Logging.DebugMessage("{0} cookies", hubConnection.CookieContainer.Count); Task.Run(async() => { await StartNotificationHandler(key, keyName); }); }
private void CreateClient(EndpointAddress endpointAdress) { var rest = ClientFactory.Endpoint.Behaviors.Find <RestTokenHandler>(); if (rest != null) { var tokenManager = FindTokenManager(); RuntimeFactory.Current.GetStateStorageContainer().TryAddStorageItem(tokenManager); Client = ClientFactory.CreateChannel(endpointAdress); } else { if (ConfigurationManagerHelper.GetValueOnKey("stardust.RelayToken") == "true") { if (BootstrapContext != null) { Client = ClientFactory.CreateChannelWithIssuedToken(BootstrapContext.SecurityToken); return; } } if (!(ClientFactory.Endpoint.Binding is WS2007FederationHttpBinding)) { Client = ClientFactory.CreateChannel(endpointAdress); return; } if (BootstrapContext.IsInstance()) { Client = ClientFactory.CreateChannelWithIssuedToken(GetTokenOnBehalfOf(), endpointAdress); } else if (UseSecureChannel) { Client = ClientFactory.CreateChannelWithIssuedToken(GetToken(), endpointAdress); } else { Client = ClientFactory.CreateChannel(endpointAdress); } } }
public void PrepWebServer(HttpApplication host) { if (ConfigurationManagerHelper.GetValueOnKey("stardust.IsBackendServer") == "false") { DynamicModuleUtility.RegisterModule(typeof(SessionAuthenticationModule)); DynamicModuleUtility.RegisterModule(typeof(WSFederationAuthenticationModule)); IsConfiguredAsWebFront = true; } if (ConfigurationManagerHelper.GetValueOnKey("stardust.SecureWcfRest") == "true") { DynamicModuleUtility.RegisterModule(typeof(WcfRestClaimsModule)); } var modules = ConfigurationManagerHelper.GetValueOnKey("stardust.registerModules"); if (modules.ContainsCharacters()) { foreach (var moduleTypeName in modules.Split('|')) { DynamicModuleUtility.RegisterModule(Type.GetType(moduleTypeName)); } } }
private void context_EndRequest(object sender, EventArgs e) { HttpApplication context = sender as HttpApplication; if (!IsService(sender, context)) { return; } //if (!context.Request.Url.ToString().EndsWith("/securerest") && !HttpContext.Current.Request.Url.ToString().Contains("/securerest/")) return; context.Response.AppendHeader("X-Handler", "Stardust 2.1.1"); if (ConfigurationManagerHelper.GetValueOnKey("statdust.forceJsonOnWfc", true)) { if (context.Request.ContentType.Contains("xml")) { context.Response.ContentType = context.Response.ContentType.Replace("xml", "json"); } } if (context.Response.StatusCode != (int)HttpStatusCode.Forbidden) { return; } }
static void Main(string[] args) { if (!SetConsoleCtrlHandler(ConsoleCtrlHandler, true)) { Console.WriteLine("无法注册系统事件!\n"); } ServiceHost host = new ServiceHost(typeof(UserService).Assembly); var listeningOn = ConfigurationManagerHelper.GetValue("EIM_Service_Url"); host.Init().Start(listeningOn); host.Load(); Console.WriteLine("服务已启动。"); HostCommandHandler commandHandler = new HostCommandHandler(host); while (true) { string cmd = Console.ReadLine(); if (string.IsNullOrEmpty(cmd)) { continue; } if (cmd == "exit") { break; } try { commandHandler.Process(cmd); } catch (Exception ex) { Console.WriteLine(ex.Message); EIMLog.Logger.Error(ex.Message, ex); } } }
private static X509Certificate2 GetThumbprintFromMetadata(string issuerAddress) { if (thumbprintExtractionFailed) { return(null); } var issuerAdr = new Uri(issuerAddress); var metadataLocation = String.Format("{0}://{1}/federationmetadata/2007-06/federationmetadata.xml", issuerAdr.Scheme, issuerAdr.Host); using (var client = new WebClient()) { var data = GetMetadataFromFederationServer(issuerAddress, client, metadataLocation); if (data.IsNullOrWhiteSpace()) { thumbprintExtractionFailed = true; return(null); } try { var metadata = GetMetadatFromString(data); return(GetAndAddThumbprint(metadata, issuerAddress)); } catch (Exception ex) { thumbprintExtractionFailed = true; if (ConfigurationManagerHelper.GetValueOnKey("stardust.Debug") != "true") { return(null); } Logging.DebugMessage("------------------------------------------------------------------------"); Logging.DebugMessage(data); Logging.DebugMessage("------------------------------------------------------------------------"); Logging.Exception(ex, "Uable to extract thumbprint from metadata"); return(null); } } }
/// <summary> /// retreives the users companies using a basic http client /// </summary> /// <returns></returns> public async Task <ActionResult> About() { ViewBag.Message = "Getting your companies with HttpClient"; if (Request.IsAuthenticated) { ViewBag.Email = (User.Identity as ClaimsIdentity)?.Claims .FirstOrDefault(c => c.Type == ClaimTypes.Upn)?.Value; var client = new HttpClient { BaseAddress = new Uri(ConfigurationManager.AppSettings["myApiV3Url"]), DefaultRequestHeaders = { Authorization = AuthenticationHeaderValue.Parse(await _tokenProvider.GetBearerTokenAsync(new TokenProviderConfiguration().Scope)), } }; client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", ConfigurationManagerHelper.GetValueOnKey("subscriptionKey")); var companies = await client.GetAsync("my/companies"); ViewBag.CompaniesRawData = await companies.Content.ReadAsStringAsync(); } return(View()); }
public static void SetCredentials(HubConnection req) { if (ConfigurationManagerHelper.GetValueOnKey("stardust.useAzureAd") != "true") { req.Credentials = new NetworkCredential( ConfigurationManagerHelper.GetValueOnKey("stardust.configUser"), ConfigurationManagerHelper.GetValueOnKey("stardust.configPassword"), ConfigurationManagerHelper.GetValueOnKey("stardust.configDomain")); } else { var bearerToken = GetBearerToken(); try { req.Headers.Remove("Authorization"); } catch (Exception ex) { ex.Log(); } req.Headers.Add("Authorization", bearerToken); } }
public static string GetConnectionString() { string connectionString; var postfix = "Store"; if (ConfigurationManagerHelper.GetValueOnKey("configStoreMigrationFile").ContainsCharacters()) { if (File.Exists(ConfigurationManagerHelper.GetValueOnKey("configStoreMigrationFile"))) { postfix = ""; } else { } } connectionString = ConfigurationManagerHelper.GetValueOnKey("configStore"); if (connectionString.IsNullOrWhiteSpace()) { connectionString = "Type=embedded;endpoint=http://localhost:8090/brightstar;StoresDirectory=C:\\Stardust\\Stores;StoreName=configWeb"; } connectionString = connectionString + postfix; return(connectionString); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddVeracity(Configuration) .AddSingleton(ConstructDataProtector) .AddSingleton(ConstructDistributedCache) .AddVeracityServices(ConfigurationManagerHelper.GetValueOnKey("myApiV3Url")) .AddAuthentication(sharedOptions => { sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddVeracityAuthentication(Configuration) .AddCookie(options => { options.Cookie.HttpOnly = true; options.Cookie.SameSite = SameSiteMode.Lax; options.Cookie.SecurePolicy = CookieSecurePolicy.Always; options.Cookie.IsEssential = true; }); services.AddMvc() .AddVeracityApiProxies(ConfigurationManagerHelper.GetValueOnKey("myApiV3Url"), CookieAuthenticationDefaults.AuthenticationScheme); }
static void Main(string[] args) { try { ConfigurationManagerHelper.SetManager(new DummyManager()); B2CGlobalConfiguration.AadPolicy = "B2C_1A_SignInWithADFSIdp"; B2CGlobalConfiguration.AadTenant = "dnvglb2ctest.onmicrosoft.com"; B2CGlobalConfiguration.Audience = "aa307cec-db8a-4224-8d5f-e864f16b1ad0"; IdentityModelEventSource.ShowPII = true; //B2CGlobalConfiguration.AudienceV1 = "https://dnvglb2ctest.onmicrosoft.com/af7f55bc-5f35-44a7-a18a-c62ef80bdd5d"; B2CGlobalConfiguration.AudienceV1 = "https://dnvglb2ctest.onmicrosoft.com/efb3e529-2f80-458b-aedf-7f4c8c794b45"; B2CGlobalConfiguration.ValidIssuer = "https://login.microsoftonline.com/ed815121-cdfa-4097-b524-e2b23cd36eb6/v2.0"; B2CGlobalConfiguration.ValidIssuerV1 = "https://sts.windows.net/ed815121-cdfa-4097-b524-e2b23cd36eb6/"; Console.WriteLine("Validating bearer token"); TokenValidator.SetLogger(new ConsoleLogger()); TokenValidator.Validate(string.Join("", args)); } catch (Exception ex) { Console.WriteLine("Failed"); } Console.ReadKey(); }
public int GetCalculatedPrice(int basePrice, int price, int Type) { if (Type == (int)PriceType.Decreased) { var PriceDecreasedByPercentage = ConfigurationManagerHelper.PriceDecreaseBy(); var PriceRangeMinPercentage = ConfigurationManagerHelper.PriceMinimum(); var MinimumPrice = basePrice * PriceRangeMinPercentage / 100; var PriceDecreasedValue = price - (price * PriceDecreasedByPercentage / 100); if (PriceDecreasedValue < MinimumPrice) { //Set Minimum value-- Should not fall below 75% of base price return(basePrice); } return(PriceDecreasedValue); } else { var PriceIncreasedByPercentage = ConfigurationManagerHelper.PriceIncreaseBy(); var PriceRangeMaxPercentage = ConfigurationManagerHelper.PriceMaximum(); var MaximumPrice = basePrice * PriceRangeMaxPercentage / 100; var PriceIncreasedValue = price + (price * PriceIncreasedByPercentage / 100); if (PriceIncreasedValue > MaximumPrice) { //Set Maximum value-- Should not rise above 125% of base price return(basePrice); } return(PriceIncreasedValue); } }
private static void RefreshThumbprintsTokens(object state) { if (PassiveIdentityConfiguration.IsInstance()) { try { var issuer = FederatedAuthentication.FederationConfiguration.WsFederationConfiguration.Issuer; var thumbprint = GetThumbprintFromMetadata(issuer); if (!thumbprint.IsInstance()) { UpdateWebIdentity(issuer, thumbprint.Thumbprint); CacheIssuerThumbprint(thumbprint, issuer); } } catch (Exception ex) { if (ConfigurationManagerHelper.GetValueOnKey("stardust.Debug") == "true") { Logging.Exception(ex, "Unable to update passive federation settings"); } } } foreach (var serviceHostBase in CachedIssuers) { try { UpdateServiceHost(serviceHostBase); } catch (Exception ex) { if (ConfigurationManagerHelper.GetValueOnKey("stardust.Debug") == "true") { Logging.Exception(ex, "Unable to update service host"); } } } }
// Initializes the cache against a local file. // If the file is already present, it loads its content in the ADAL cache public NativeTokenCache(string filePath = @"\TokenCache.dat") { var pathBase = ConfigurationManagerHelper.GetValueOnKey("stardust.nativeTokenCachePath"); if (pathBase.ContainsCharacters()) { CacheFilePath = pathBase + filePath; } else { CacheFilePath = AppDomain.CurrentDomain.BaseDirectory + "App_Data" + filePath; } this.AfterAccess = AfterAccessNotification; this.BeforeAccess = BeforeAccessNotification; lock (FileLock) { try { this.Deserialize(File.Exists(CacheFilePath) ? MachineKey.Unprotect(File.ReadAllBytes(CacheFilePath)) : null); } catch (CryptographicException ex) { ex.Log(); if (!File.Exists(CacheFilePath)) { throw; } File.Delete(CacheFilePath); this.Deserialize(File.Exists(CacheFilePath) ? MachineKey.Unprotect(File.ReadAllBytes(CacheFilePath)) : null); } } }