private IModelBinder GetModelBinderForSection(Section section, INConfigSettings settings) { var binder = new ConfigurationHelper() .GetConfigurationProperty<Section, IModelBinder>(section, x => x.ModelBinder, settings.ModelBinder, x => settings.ModelBinder); return binder; }
public void Given_ValidTimedServiceConfigurationXml_Then_ConfigurationXmlDeserialisedToObjects() { // Arrange IConfigurationHelper configHelper = new ConfigurationHelper(); // Action var result = configHelper.GetSection<TimedServicesConfig>("TimedServices"); // Assert Assert.True(result.TimedServiceCommandConfigs.Count() > 0); }
public void Given_RunAtTimeFormatHHMMSS_With_NoDateDefined_Then_TodaysDateWillBeUsedAsDefault() { // Arrange IConfigurationHelper configHelper = new ConfigurationHelper(); var expectedResult = DateTime.Today.Date; // Action var section = configHelper.GetSection<TimedServicesConfig>("TimedServices"); var actualResult = section.TimedServiceCommandConfigs.Where(c => c.Name == "TestTimedService").FirstOrDefault().RunAt.Value.Date; // Assert Assert.Equal<DateTime>(expectedResult, actualResult); }
public async Task SendMailAsync(string subject, string body) { var config = new ConfigurationHelper(); var smtpClient = new SmtpClient(config.MailHost, config.MailPort); smtpClient.Credentials = new NetworkCredential(config.MailUserName, config.MailPassword); smtpClient.EnableSsl = true; MailMessage mail = new MailMessage(config.MailFrom, config.MailTo); mail.Subject = subject; mail.Body = body; await smtpClient.SendMailAsync(mail); }
public Task <T> GetDataFromTableStorageAsync() { return(ConfigurationHelper.GetConfigurationAsync <T>(ConfigurationName)); }
public ActionResult AddToCart(CartModel model) { if (ModelState.IsValid) { //string customerId = User.Identity.Name; string customerId = "221ea0b2-6a56-450d-bcb7-7fa110ea0da1"; model.CustomerId = customerId; int programId = Convert.ToInt32(ConfigurationHelper.Get("NetCommerce.Program")); Response <CatalogFilterListResponse> response = ApiService .Post <CatalogFilterListResponse>(ConfigurationHelper.Get("Proxy.Base"), string.Format( ConfigurationHelper.Get("Proxy.ShowCartV2"), programId, model.ProductGuid, customerId, model.ProductReference, model.Quantity, model.SelectedPaymentRule), null, null); TempData["StartUpScript"] = string.Format("jQuery(showMask('Error','Prueba'))"); return(PartialView(response.ObjectResponse)); } //string customerId = User.Identity.Name; TempData["StartUpScript"] = string.Format("jQuery(showMask('Error','Prueba'))"); return(RedirectToAction("ProductDetails", "Catalog", new { id = model.ProductGuid })); }
public static string ConnectionString() { var _config = ConfigurationHelper.GetConfiguration(Environment.CurrentDirectory); return(_config.GetConnectionString("DefaultConnection")); }
public JsonResult _SavePartyLicenceID(string scaleId, string licenseImageRefId) { try { bool result = false; if (!string.IsNullOrEmpty(licenseImageRefId)) { ScaleAttachmentsLibrary scaleAttOps = new ScaleAttachmentsLibrary(ConfigurationHelper.GetsmARTDBContextConnectionString()); ScaleAttachments scaleAttachment = scaleAttOps.GetScaleAttachmentByRefId(new Guid(licenseImageRefId)); if (scaleAttachment != null) { FilelHelper fileHelper = new FilelHelper(); string imagePath = fileHelper.GetFilePathByFileRefId(licenseImageRefId); byte[] imageBytes = fileHelper.GetBytesFromFile(imagePath); SaveScaleIDCardAttachment(Convert.ToInt32(scaleId), imageBytes); result = true; } } var data = new { Success = result }; return(Json(data, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { string message = ex.Message; Common.MessageLogger.Instance.LogMessage(ex, ex.Message, Common.Priority.High, 0, System.Diagnostics.TraceEventType.Critical, "Scanner Error", "Scanner"); throw ex; } }
public static GuildHouseConfiguration LoadFromConfigFile() { return(ConfigurationHelper.Load <GuildHouseConfiguration>(ConfigFile)); }
public static WebSiteManagementClient CreateWebSiteManagementClient(this CloudClients clients) { return(ConfigurationHelper.CreateFromSettings <WebSiteManagementClient>(WebSiteManagementClient.Create)); }
public static string ParseExpression(string expression, Collection <DataTable> dataTableCollection, Assembly assembly) { if (string.IsNullOrWhiteSpace(expression)) { return(string.Empty); } string logo = ConfigurationHelper.GetReportParameter("LogoPath"); expression = expression.Replace("{LogoPath}", PageUtility.GetCurrentDomainName() + PageUtility.ResolveUrl(logo)); //Or else logo will not be exported into excel. expression = expression.Replace("{PrintDate}", DateTime.Now.ToString(LocalizationHelper.GetCurrentCulture())); foreach (var match in Regex.Matches(expression, "{.*?}")) { string word = match.ToString(); if (word.StartsWith("{Session.", StringComparison.OrdinalIgnoreCase)) { string sessionKey = RemoveBraces(word); sessionKey = sessionKey.Replace("Session.", ""); sessionKey = sessionKey.Trim(); string value = Conversion.TryCastString(SessionHelper.GetSessionKey(sessionKey)); expression = expression.Replace(word, value); } else if (word.StartsWith("{Resources.", StringComparison.OrdinalIgnoreCase)) { string res = RemoveBraces(word); string[] resource = res.Split('.'); string key = resource[2]; string fullyQualifiedResourceClassName = assembly.GetName().Name + "." + resource[0] + "." + resource[1]; expression = expression.Replace(word, LocalizationHelper.GetResourceString(assembly, fullyQualifiedResourceClassName, key)); } else if (word.StartsWith("{DataSource", StringComparison.OrdinalIgnoreCase) && word.ToLower(CultureInfo.InvariantCulture).Contains("runningtotalfieldvalue")) { string res = RemoveBraces(word); string[] resource = res.Split('.'); int dataSourceIndex = Conversion.TryCastInteger(resource[0].ToLower(CultureInfo.InvariantCulture).Replace("datasource", "").Replace("[", "").Replace("]", "")); int index = Conversion.TryCastInteger(resource[1].ToLower(CultureInfo.InvariantCulture).Replace("runningtotalfieldvalue", "").Replace("[", "").Replace("]", "")); if (dataSourceIndex >= 0 && index >= 0) { if (dataTableCollection != null && dataTableCollection[dataSourceIndex] != null) { expression = expression.Replace(word, GetSum(dataTableCollection[dataSourceIndex], index).ToString(CultureInfo.InvariantCulture)); } } } else if (word.StartsWith("{Barcode", StringComparison.OrdinalIgnoreCase)) { string res = RemoveBraces(word).Replace("Barcode(", "").Replace(")", ""); string barCodeValue = res; if (res.StartsWith("DataSource")) { barCodeValue = ParseDataSource("{" + res + "}", dataTableCollection); } string barCodeFormat = ConfigurationHelper.GetReportParameter("BarCodeFormat"); string barCodeDisplayValue = ConfigurationHelper.GetReportParameter("BarCodeDisplayValue"); string barCodeFontSize = ConfigurationHelper.GetReportParameter("BarCodeFontSize"); string barCodeWidth = ConfigurationHelper.GetReportParameter("BarCodeWidth"); string barCodeHeight = ConfigurationHelper.GetReportParameter("BarCodeHeight"); string barCodeQuite = ConfigurationHelper.GetReportParameter("BarCodeQuite"); string barCodeFont = ConfigurationHelper.GetReportParameter("BarCodeFont"); string barCodeTextAlign = ConfigurationHelper.GetReportParameter("BarCodeTextAlign"); string barCodeBackgroundColor = ConfigurationHelper.GetReportParameter("BarCodeBackgroundColor"); string barCodeLineColor = ConfigurationHelper.GetReportParameter("BarCodeLineColor"); string imageSource = "<img class='reportEngineBarCode' data-barcodevalue='{0}' alt='{0}' value='{0}' data-barcodeformat='{1}' data-barcodedisplayvalue='{2}' data-barcodefontsize='{3}' data-barcodewidth='{4}' data-barcodeheight='{5}' data-barcodefont='{6}' data-barcodetextalign='{7}' data-barcodebackgroundcolor='{8}' data-barcodelinecolor='{9}' data-barcodequite={10} />"; imageSource = string.Format(CultureInfo.InvariantCulture, imageSource, barCodeValue, barCodeFormat, barCodeDisplayValue, barCodeFontSize, barCodeWidth, barCodeHeight, barCodeFont, barCodeTextAlign, barCodeBackgroundColor, barCodeLineColor, barCodeQuite); expression = expression.Replace(word, imageSource).ToString(CultureInfo.InvariantCulture); } else if (word.StartsWith("{QRCode", StringComparison.OrdinalIgnoreCase)) { string res = RemoveBraces(word).Replace("QRCode(", "").Replace(")", ""); string qrCodeValue = res; if (res.StartsWith("DataSource")) { qrCodeValue = ParseDataSource("{" + res + "}", dataTableCollection); } string qrCodeRender = ConfigurationHelper.GetReportParameter("QRCodeRender"); string qrCodeBackgroundColor = ConfigurationHelper.GetReportParameter("QRCodeBackgroundColor"); string qrCodeForegroundColor = ConfigurationHelper.GetReportParameter("QRCodeForegroundColor"); string qrCodeWidth = ConfigurationHelper.GetReportParameter("QRCodeWidth"); string qrCodeHeight = ConfigurationHelper.GetReportParameter("QRCodeHeight"); string qrCodeTypeNumber = ConfigurationHelper.GetReportParameter("QRCodeTypeNumber"); string qrCodeDiv = "<div class='reportEngineQRCode' data-qrcodevalue={0} data-qrcoderender='{1}' data-qrcodebackgroundcolor='{2}' data-qrcodeforegroundcolor='{3}' data-qrcodewidth='{4}' data-qrcodeheight='{5}' data-qrcodetypenumber='{6}'></div>"; qrCodeDiv = string.Format(CultureInfo.InvariantCulture, qrCodeDiv, qrCodeValue, qrCodeRender, qrCodeBackgroundColor, qrCodeForegroundColor, qrCodeWidth, qrCodeHeight, qrCodeTypeNumber); expression = expression.Replace(word, qrCodeDiv).ToString(CultureInfo.InvariantCulture); } } return(expression); }
public RouteProviderTests() { _routeProvider = new DefaultRouteProvider(new DefaultConfigurationManager(ConfigurationHelper.GetConfiguration())); }
protected override ActionResult Display(GridCommand command, string id, bool isNew) { int totalRows = 0; IEnumerable <PaymentReceiptDetails> resultList; PaymentReceiptDetailsLibrary lib = new PaymentReceiptDetailsLibrary(ConfigurationHelper.GetsmARTDBContextConnectionString()); ScaleLibrary libScale = new ScaleLibrary(ConfigurationHelper.GetsmARTDBContextConnectionString()); if (isNew || id == "0") { resultList = lib.GetAllByPaging(TempEntityList, out totalRows, command.Page, command.PageSize, command.SortDescriptors.Count == 0 ? "" : command.SortDescriptors[0].Member, command.SortDescriptors.Count == 0 ? "" : command.SortDescriptors[0].SortDirection == System.ComponentModel.ListSortDirection.Descending ? "Desc" : "Asc", IncludePredicates, (command.FilterDescriptors.Count == 0 ? null : command.FilterDescriptors) ); } else { resultList = new PaymentReceiptDetailsLibrary(ConfigurationHelper.GetsmARTDBContextConnectionString()) .GetAllByPagingByParentID(out totalRows, int.Parse(id.ToString()), command.Page, command.PageSize == 0 ? 20 : command.PageSize, command.SortDescriptors.Count == 0 ? "" : command.SortDescriptors[0].Member, command.SortDescriptors.Count == 0 ? "" : command.SortDescriptors[0].SortDirection == System.ComponentModel.ListSortDirection.Descending ? "Desc" : "Asc", new string[] { "PaymentReceipt", "Settlement.Scale.Party_ID", "Settlement.Scale.Purchase_Order", "ExpenseRequest.Paid_Party_To", "ExpenseRequest.Scale_Ref", "ExpenseRequest.Dispatcher_Request_Ref.Booking_Ref_No", "ExpenseRequest.Dispatcher_Request_Ref.Container" }, (command.FilterDescriptors.Count == 0 ? null : command.FilterDescriptors) ); foreach (var item in resultList) { if (item.ExpenseRequest != null && item.ExpenseRequest.Dispatcher_Request_Ref != null && item.ExpenseRequest.Dispatcher_Request_Ref.Container != null) { item.ExpenseRequest.Scale_Ref = libScale.GetScalesByContainerId(item.ExpenseRequest.Dispatcher_Request_Ref.Container.ID); } } } return(View(new GridModel { Data = resultList, Total = totalRows })); }
private void GetConfiguration() { _configurationHelper = new ConfigurationHelper(); }
private IModelBinder GetModelBinderForSection(Type sectionType, Section section, IByContextSettings settings) { var factory = new ConfigurationHelper() .GetConfigurationProperty<Section, IModelBinderFactory>(section, x => x.ModelBinderFactory, settings.ModelBinderFactory, x => settings.ModelBinderFactory); return factory.Create(sectionType); }
private static string GetDisplayFields() { List <string> displayFields = new List <string>(); ScrudHelper.AddDisplayField(displayFields, "core.counties.county_id", ConfigurationHelper.GetDbParameter("CountyDisplayField")); ScrudHelper.AddDisplayField(displayFields, "core.entities.entity_id", ConfigurationHelper.GetDbParameter("EntityDisplayField")); ScrudHelper.AddDisplayField(displayFields, "core.industries.industry_id", ConfigurationHelper.GetDbParameter("IndustryDisplayField")); ScrudHelper.AddDisplayField(displayFields, "core.item_groups.item_group_id", ConfigurationHelper.GetDbParameter("ItemGroupDisplayField")); return(string.Join(",", displayFields)); }
public static Settings ApplicationSettings() => ConfigurationHelper.ApplicationSettings();
public FileHandlingService(ConfigurationHelper configurationHelper) { _configurationHelper = configurationHelper; }
public static string GetParameter(string key) { return(ConfigurationHelper.GetParameter(key)); }
public IHttpActionResult TryToAutoInstallModules() { var notification = new webModel.ModuleAutoInstallPushNotification(User.Identity.Name) { Title = "Modules installation", //set completed by default Finished = DateTime.UtcNow }; if (!_settingsManager.GetValue("VirtoCommerce.ModulesAutoInstalled", false)) { lock (_lockObject) { if (!_settingsManager.GetValue("VirtoCommerce.ModulesAutoInstalled", false)) { var moduleBundles = ConfigurationHelper.SplitAppSettingsStringValue("VirtoCommerce:AutoInstallModuleBundles"); if (!moduleBundles.IsNullOrEmpty()) { _settingsManager.SetValue("VirtoCommerce.ModulesAutoInstalled", true); _settingsManager.SetValue(_autoInstallStateSetting, webModel.AutoInstallState.Processing); EnsureModulesCatalogInitialized(); var modules = new List <ManifestModuleInfo>(); var moduleVersionGroups = _moduleCatalog.Modules .OfType <ManifestModuleInfo>() .Where(x => x.Groups.Intersect(moduleBundles, StringComparer.OrdinalIgnoreCase).Any()) .GroupBy(x => x.Id); //Need install only latest versions foreach (var moduleVersionGroup in moduleVersionGroups) { var alreadyInstalledModule = _moduleCatalog.Modules.OfType <ManifestModuleInfo>().FirstOrDefault(x => x.IsInstalled && x.Id.EqualsInvariant(moduleVersionGroup.Key)); //skip already installed modules if (alreadyInstalledModule == null) { var latestVersion = moduleVersionGroup.OrderBy(x => x.Version).LastOrDefault(); if (latestVersion != null) { modules.Add(latestVersion); } } } var modulesWithDependencies = _moduleCatalog.CompleteListWithDependencies(modules) .OfType <ManifestModuleInfo>() .Where(x => !x.IsInstalled) .Select(x => x.ToWebModel()) .ToArray(); if (modulesWithDependencies.Any()) { var options = new webModel.ModuleBackgroundJobOptions { Action = webModel.ModuleAction.Install, Modules = modulesWithDependencies }; //reset finished date notification.Finished = null; BackgroundJob.Enqueue(() => ModuleBackgroundJob(options, notification)); } } } } } return(Ok(notification)); }
/// <summary> /// 初始化 /// </summary> public ParallelPoster() { logger = DependencyHelper.LoggerFactory.CreateLogger <ParallelPoster>(); ConfigurationHelper.RegistOnChange("MessageMVC:ParallelService", ReloadOption, true); }
public async Task FixtureSetup() { TestConfiguration config = ConfigurationHelper.GetTestConfiguration(); await Task.WhenAll(StartMySqlContainer(config.MySqlPort), StartSqlServerContainer(config.MsSqlPassword, config.MsSqlPort)); }
public static void MainTest() { using (var conn = new SqlConnection(ConfigurationHelper.ConnectionString("TestDb"))) { Init(conn); var aaaa = conn.Fetch <TestEntity>("SELECT * FROM [dbo].[TestTable111]"); for (int i = 0; i < 3; i++) { conn.Execute(@"INSERT INTO [dbo].[TestTable111] ( [Token], [CreatedTime] ) VALUES (@Token, --Token - nvarchar(200) @CreatedTime-- CreatedTime - datetime )", new TestEntity { Token = Guid.NewGuid().ToString("N") + "_Execute_Model", CreatedTime = DateTime.Now }); } var tokens = conn.QueryColumn <string>("SELECT Token FROM [dbo].[TestTable111]").ToArray(); Console.WriteLine("tokens:{0}", string.Join(",", tokens)); Console.WriteLine("Current data count:{0}", conn.ExecuteScalarTo <int>("SELECT COUNT(1) FROM [dbo].[TestTable111]")); for (int i = 0; i < 3; i++) { conn.Execute(@"INSERT INTO [dbo].[TestTable111] ( [Token], [CreatedTime] ) VALUES (@Token, --Token - nvarchar(200) GETDATE()-- CreatedTime - datetime )", new TestEntity { Token = Guid.NewGuid().ToString("N") + "_Execute_Model_1" }, new SqlParameter("@Token", Guid.NewGuid().ToString("N"))); } Console.WriteLine("Current data count:{0}", conn.ExecuteScalarTo <int>("SELECT COUNT(1) FROM [dbo].[TestTable111]")); for (int i = 0; i < 3; i++) { conn.Execute(@"INSERT INTO [dbo].[TestTable111] ( [Token], [CreatedTime] ) VALUES (@Token, --Token - nvarchar(200) GETDATE()-- CreatedTime - datetime )", new { Token = Guid.NewGuid().ToString("N") + "_Execute_Anonymous_Model" }); } conn.Execute(@"INSERT INTO [dbo].[TestTable111] ( [Token], [CreatedTime] ) VALUES (@Token, --Token - nvarchar(200) GETDATE()-- CreatedTime - datetime )", new Dictionary <string, object> { { "@Token", Guid.NewGuid().ToString("N") + " executed-dictionary" } }); Console.WriteLine("Current data count:{0}", conn.ExecuteScalarTo <int>("SELECT COUNT(1) FROM [dbo].[TestTable111]")); conn.Execute("Delete from TestTable111 where PKID > @pkid", new { pkid = 888 }); Console.WriteLine("Current data count:{0}", conn.ExecuteScalarTo <int>("SELECT COUNT(1) FROM [dbo].[TestTable111]")); Clean(conn); } }
/// <summary> /// This is the entry point of the service host process. /// </summary> private static void Main() { try { // The ServiceManifest.XML file defines one or more service type names. // Registering a service maps a service type name to a .NET type. // When Service Fabric creates an instance of this service type, // an instance of the class is created in this host process. using (var diagnosticsPipeline = ServiceFabricDiagnosticPipelineFactory.CreatePipeline("DCT.ILR.ValidationServiceStateless-pipeline")) { // Start with the trusty old container builder. var builder = new ContainerBuilder(); // Register any regular dependencies. builder.RegisterModule <BusinessLogicAutofacModule>(); builder.RegisterModule <ValidationServiceServiceModuleSF>(); var config = new ESFA.DC.Logging.ApplicationLoggerSettings(); config.LoggerOutput = ESFA.DC.Logging.Enums.LogOutputDestination.SqlServer; builder.RegisterType <ESFA.DC.Logging.SeriLogging.SeriLogger>().As <ESFA.DC.Logging.ILogger>() .WithParameter(new TypedParameter(typeof(ESFA.DC.Logging.ApplicationLoggerSettings), config)) .InstancePerLifetimeScope(); var applicationInsightsKey = FabricRuntime.GetActivationContext() .GetConfigurationPackageObject("Config") .Settings .Sections["ConfigurationSection"] .Parameters["ApplicationInsightsKey"] .Value; var configurationOptions = ConfigurationHelper.GetSectionValues <ConfigurationOptions>("ConfigurationSection"); var seviceBusOptions = ConfigurationHelper.GetSectionValues <ServiceBusOptions>("ServiceBusSettings"); builder.RegisterInstance(configurationOptions).As <ConfigurationOptions>().SingleInstance(); builder.RegisterInstance(seviceBusOptions).As <ServiceBusOptions>().SingleInstance(); //var loggerFactory = new LoggerFactoryBuilder().CreateLoggerFactory(applicationInsightsKey); //logger = loggerFactory.CreateLogger<MyStateless>(); builder.RegisterType <TopicHelper>().As <ITopicHelper>().InstancePerDependency(); builder.RegisterType <RuleManager>().As <IRuleManager>(); //builder.Register(c => // new RuleManagerValidationService(c.Resolve<IRuleManager>(), c.Resolve<IFileData>())) // .As<IValidationService>().InstancePerLifetimeScope(); builder.RegisterType <RuleManagerValidationService>().As <IValidationService>().InstancePerLifetimeScope(); builder.RegisterInstance(new ActorsHelper()).As <IActorsHelper>(); // Register the Autofac magic for Service Fabric support. builder.RegisterServiceFabricSupport(); // Register the stateless service. builder.RegisterStatelessService <ValidationServiceStateless>("DCT.ILR.ValidationServiceStatelessType"); //ServiceRuntime.RegisterServiceAsync("DCT.ILR.VadationServiceStatefulType", // context => new VadationServiceStateful(context)).GetAwaiter().GetResult(); //ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(VadationServiceStateful).Name); using (var container = builder.Build()) { using (var newScope = container.BeginLifetimeScope()) { var val = newScope.Resolve <IValidationService>(); } ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(ValidationServiceStateless).Name); // Prevents this host process from terminating so services keep running. Thread.Sleep(Timeout.Infinite); } } } catch (Exception e) { ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString()); throw; } }
private static string GetDisplayFields() { List <string> displayFields = new List <string>(); ScrudHelper.AddDisplayField(displayFields, "core.accounts.account_id", ConfigurationHelper.GetDbParameter("AccountDisplayField")); return(string.Join(",", displayFields)); }
private void OnConnectHost(AccountVM acct) { ChangeStatus("连接中...", true); SynchronizationContext uiContext = SynchronizationContext.Current; HostPort = ConfigurationHelper.GetAppSettingValue("tradeHostPort", 16181);; EventLogger.Write(string.Format("正在为{0}建立交易终端...", acct.InvestorId)); Func <int, bool, bool> funcLaunch = new Func <int, bool, bool>(_host.Startup); funcLaunch.BeginInvoke(HostPort, true, delegate(IAsyncResult arLaunch) { bool succ = funcLaunch.EndInvoke(arLaunch); if (!succ) { LogManager.Logger.Warn("Launch trade station failed"); return; } LogManager.Logger.InfoFormat("TradeStaion started up."); Action <int> actionLoopConnect = null; _connectTimes = 1; Action <bool, string, bool> actionClntConnectDone = null; actionClntConnectDone = (b, t, attach) => { string txt = string.Format("连接交易终端(第{0}次)", _connectTimes); if (b) { txt += "成功"; } else { txt += "失败 (" + t + ")"; } EventLogger.Write(txt); if (b) { if (attach) { uiContext.Send(o => ChangeStatus("已连接", false), null); EventLogger.Write("恢复连接到交易终端"); } else { Func <AccountVM, bool> actionReady = new Func <AccountVM, bool>(HaveTradeStationReady); actionReady.BeginInvoke( acct, new AsyncCallback( delegate(IAsyncResult ar) { try { bool ok = actionReady.EndInvoke(ar); if (ok) { uiContext.Send(o => ChangeStatus("已连接", false), null); EventLogger.Write(string.Format("{0}准备就绪", acct.InvestorId)); SyncToHost(); } else { uiContext.Send(o => ChangeStatus("连接失败", false), null); EventLogger.Write(string.Format("{0}发生错误", acct.InvestorId)); _client.Disconnect(); _host.Exit(); } } catch (System.Exception ex) { EventLogger.Write("初始化交易终端发生错误"); LogManager.Logger.Error(ex.Message); _host.Exit(); } }), null); LogManager.Logger.Info(txt); } } else { LogManager.Logger.Warn(txt); if ("交易终端拒绝连接" != t && _connectTimes < MaxRetryConnectTimes && actionLoopConnect != null) { actionLoopConnect.Invoke(++_connectTimes); } else { uiContext.Send(o => ChangeStatus("连接失败", false), null); EventLogger.Write(string.Format("为{0}尝试{1}次连接均发生错误" , acct.InvestorId, _connectTimes)); _client.Disconnect(); } } }; actionLoopConnect = new Action <int>(delegate(int times) { if (times > 1) { Thread.Sleep(1000); } string effectiveTradeStation = AddressRepo.EffectiveTradeStation.Address; EventLogger.Write("Connect to {0}", effectiveTradeStation); LogManager.Logger.InfoFormat("Connect to {0}", effectiveTradeStation); _client.AuthClientId = this.Id; try { _client.ConnectAsync(effectiveTradeStation, actionClntConnectDone); } catch (System.Exception ex) { LogManager.Logger.ErrorFormat("Error connecting host due to : {0}", ex.Message); if (actionClntConnectDone != null) { actionClntConnectDone(false, "交易终端拒绝连接", false); } } }); actionLoopConnect.Invoke(_connectTimes); }, null); //_host.Startup(HostPort); }
public PartialViewResult GetCart() { //string customerId = User.Identity.Name; string customerId = "221ea0b2-6a56-450d-bcb7-7fa110ea0da1"; int programId = Convert.ToInt32(ConfigurationHelper.Get("NetCommerce.Program")); Response <CatalogFilterListResponse> response = ApiService .Post <CatalogFilterListResponse>(ConfigurationHelper.Get("Proxy.Base"), string.Format( ConfigurationHelper.Get("Proxy.ShowCartV2"), programId, customerId), null, null); return(PartialView(response.ObjectResponse)); }
protected void Page_Load(object sender, EventArgs e) { if (!QueryHelper.ValidateHash("hash") || Parameters == null) { StopProcessing = true; return; } PageTitle.TitleText = GetString("om.contactrole.select"); Page.Title = PageTitle.TitleText; // Check if the dialog was opened from mass actions isMassAction = Parameters.ContainsKey("ismassaction"); if (isMassAction) { siteId = ValidationHelper.GetInteger(Parameters["siteid"], 0); } else { int accountContactId = ValidationHelper.GetInteger(Parameters["accountcontactid"], 0); aci = AccountContactInfoProvider.GetAccountContactInfo(accountContactId); if (aci != null) { AccountInfo ai = AccountInfoProvider.GetAccountInfo(aci.AccountID); if (ai != null) { siteId = ai.AccountSiteID; } } } // Show all global configuration to authorized users .. bool allowGlobal = ConfigurationHelper.AuthorizedReadConfiguration(UniSelector.US_GLOBAL_RECORD, false); // .. but just in SiteManager - fake it in CMSDesk so that even Global Admin sees user configuration // as Site Admins (depending on settings). bool isSiteManager = ValidationHelper.GetBoolean(Parameters["issitemanager"], false); allowGlobal &= (isSiteManager || SettingsKeyInfoProvider.GetBoolValue(SiteInfoProvider.GetSiteName(siteId) + ".cmscmglobalconfiguration")); bool allowSite; if (siteId > 0) { allowSite = ConfigurationHelper.AuthorizedReadConfiguration(siteId, false); } else { allowSite = ConfigurationHelper.AuthorizedReadConfiguration(SiteContext.CurrentSiteID, false); } // Check read permission if ((siteId > 0) && !allowSite && !allowGlobal) { RedirectToAccessDenied("cms.contactmanagement", "ReadConfiguration"); return; } else if ((siteId == 0) && !allowGlobal) { RedirectToAccessDenied("cms.contactmanagement", "ReadGlobalConfiguration"); return; } if (siteId > 0) { if (allowSite) { gridElem.WhereCondition = "ContactRoleSiteID = " + siteId; } // Check if global config is allowed for the site if (allowGlobal) { // Add contact roles from global configuration gridElem.WhereCondition = SqlHelper.AddWhereCondition(gridElem.WhereCondition, "ContactRoleSiteID IS NULL", "OR"); } } else if ((siteId == 0) && allowGlobal) { gridElem.WhereCondition = "ContactRoleSiteID IS NULL"; } gridElem.OnExternalDataBound += gridElem_OnExternalDataBound; gridElem.Pager.DefaultPageSize = 10; // Display 'Reset' button when 'none' role is allowed if (ValidationHelper.GetBoolean(Parameters["allownone"], false)) { btnReset.Visible = true; btnReset.Click += btn_Click; btnReset.CommandArgument = "0"; } }
public virtual T GetDataFromTableStorage() { return(ConfigurationHelper.GetConfiguration <T>(ConfigurationName)); }
void IProvider.Initialize(Dictionary <string, string> parameters) { ConfigurationHelper.TryGetAndRemove(parameters, "hashName", out this.hashName, false); }
private static string GetDisplayFields() { List <string> displayFields = new List <string>(); ScrudHelper.AddDisplayField(displayFields, "core.cash_flow_headings.cash_flow_heading_id", ConfigurationHelper.GetDbParameter("CashFlowHeadingDisplayField")); ScrudHelper.AddDisplayField(displayFields, "core.account_masters.account_master_id", ConfigurationHelper.GetDbParameter("AccountMasterDisplayField")); return(string.Join(",", displayFields)); }
public IEnumerable <QBLog> GetAll() { QuickBookLibrary lib = new QuickBookLibrary(ConfigurationHelper.GetsmARTDBContextConnectionString()); return(lib.GetUnPostedParentQBLogs()); }
public static string ConnectionString() => ConfigurationHelper.ConnectionString();
public QBLog Get(int?id) { QuickBookLibrary lib = new QuickBookLibrary(ConfigurationHelper.GetsmARTDBContextConnectionString()); return(lib.GetByID(id.Value.ToString())); }
public static BatchManagementClient CreateBatchManagementClient(this CloudClients clients) { return(ConfigurationHelper.CreateFromSettings <BatchManagementClient>(BatchManagementClient.Create)); }
protected void Page_Load(object sender, EventArgs e) { if (!QueryHelper.ValidateHash("hash") || Parameters == null) { StopProcessing = true; return; } CurrentMaster.Title.TitleText = GetString("om.accountstatus.select"); CurrentMaster.Title.TitleImage = GetImageUrl("Objects/OM_AccountStatus/object.png"); Page.Title = CurrentMaster.Title.TitleText; siteId = ValidationHelper.GetInteger(Parameters["siteid"], 0); bool allowSite = ConfigurationHelper.AuthorizedReadConfiguration(CMSContext.CurrentSiteID, false); // Show all global configuration to authorized users .. bool allowGlobal = ConfigurationHelper.AuthorizedReadConfiguration(UniSelector.US_GLOBAL_RECORD, false); // .. but just in SiteManager - fake it in CMSDesk so that even Global Admin sees user configuration // as Site Admins (depending on settings). bool isSiteManager = ValidationHelper.GetBoolean(Parameters["issitemanager"], false); allowGlobal &= (isSiteManager || SettingsKeyProvider.GetBoolValue(SiteInfoProvider.GetSiteName(siteId) + ".cmscmglobalconfiguration")); // Check read permission if ((siteId > 0) && !allowSite && !allowGlobal) { RedirectToAccessDenied("cms.contactmanagement", "ReadConfiguration"); return; } else if ((siteId == 0) && !allowGlobal) { RedirectToAccessDenied("cms.contactmanagement", "ReadGlobalConfiguration"); return; } if (siteId > 0) { if (allowSite) { gridElem.WhereCondition = "AccountStatusSiteID = " + siteId; } // Check if global config is allowed for the site if (allowGlobal) { // Add account statuses from global configuration gridElem.WhereCondition = SqlHelperClass.AddWhereCondition(gridElem.WhereCondition, "AccountStatusSiteID IS NULL", "OR"); } } else if ((siteId == 0) && allowGlobal) { gridElem.WhereCondition = "AccountStatusSiteID IS NULL"; } gridElem.OnExternalDataBound += gridElem_OnExternalDataBound; gridElem.Pager.DefaultPageSize = 10; // Display 'Reset' button when 'none' status is allowed if (ValidationHelper.GetBoolean(Parameters["allownone"], false)) { btnReset.Visible = true; btnReset.Click += btn_Click; btnReset.CommandArgument = "0"; } }