/// <summary> /// Loads the module into the kernel. /// </summary> /// <param name="container">The container.</param> public void register_components(Container container) { Log.InitializeWith<Log4NetLog>(); IConfigurationSettings configuration = new ConfigurationSettings(); Config.initialize_with(configuration); container.Register(() => configuration, Lifestyle.Singleton); container.Register<IEventAggregator, EventAggregator>(Lifestyle.Singleton); container.Register<IMessageSubscriptionManagerService, MessageSubscriptionManagerService>(Lifestyle.Singleton); EventManager.initialize_with(container.GetInstance<IMessageSubscriptionManagerService>); container.Register<INotificationSendService, SmtpMarkdownNotificationSendService>(Lifestyle.Singleton); container.Register<IMessageService, MessageService>(Lifestyle.Singleton); container.Register<IEmailDistributionService, EmailDistributionService>(Lifestyle.Singleton); container.Register<IDateTimeService, SystemDateTimeUtcService>(Lifestyle.Singleton); container.Register<ICommandExecutor, CommandExecutor>(Lifestyle.Singleton); container.Register<IFileSystemService, FileSystemService>(Lifestyle.Singleton); container.Register<IFileSystem, DotNetFileSystem>(Lifestyle.Singleton); container.Register<IRegularExpressionService, RegularExpressionService>(Lifestyle.Singleton); container.Register<INuGetService, NuGetService>(Lifestyle.Singleton); container.Register<IPackageValidationService, PackageValidationService>(Lifestyle.Singleton); container.Register<ITypeLocator, TypeLocator>(Lifestyle.Singleton); RegisterOverrideableComponents(container, configuration); }
private void UpdateConfigSettings(ConfigurationSettings settings) { KeyedCollection<string, ConfigurationProperty> parameters = settings.Sections["RecaptchaSettings"].Parameters; this.key = parameters["Key"].DecryptValue(); this.verifyUrl = new Uri(parameters["VerifyUrl"].Value); }
/// <summary> /// Assigns the gangway setting rule. /// </summary> /// <param name="configurationSetting">The configuration setting.</param> public static void AssignGangwaySettingRule(ConfigurationSettings configurationSetting) { if (configurationSetting.Validate == null) { configurationSetting.Validate = () => ApplyGangwaySettingRule(configurationSetting); } }
private void CreateButton_Click(object sender, EventArgs e) { if (!this.ValidateChildren()) { return; } DisableControls(); try { ConfigurationSettings configurationSettings = new ConfigurationSettings(); configurationSettings.OutputFileName = _outputFileNameTextBox.Text.Trim(); configurationSettings.OutputFolder = GetAppSetting("outputPath", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)); configurationSettings.SourceFolder = _sourceFolderTextBox.Text.Trim(); configurationSettings.TempFolder = Path.Combine(Path.GetTempPath(), "epubcreator"); configurationSettings.Creator = _creatorTextBox.Text.Trim(); configurationSettings.Language = _languageTextBox.Text.Trim(); configurationSettings.Rights = _rightsTextBox.Text.Trim(); configurationSettings.Title = _titleTextBox.Text.Trim(); configurationSettings.TitlePage = GetAppSetting("defaultTitlePage", String.Empty); EpubCreator epubCreator = new EpubCreator(configurationSettings); epubCreator.Create(); if (!GetAppSetting("preserveTempFiles", "false").Equals("true", StringComparison.OrdinalIgnoreCase)) { Directory.Delete(configurationSettings.TempFolder); } } finally { EnableControls(); } }
public ProxyHandler(ConfigurationSettings configSettings) { KeyedCollection<string, ConfigurationProperty> parameters = configSettings.Sections["WebServiceConfig"].Parameters; if (parameters.Contains("SecureClusterCertThumbprint")) { this.secureClusterCertThumbprint = parameters["SecureClusterCertThumbprint"].Value; } }
/// <summary> /// Loads the module into the kernel. /// </summary> public override void Load() { Log.InitializeWith<Log4NetLog>(); IConfigurationSettings configuration = new ConfigurationSettings(); Config.InitializeWith(configuration); Bind<IConfigurationSettings>().ToMethod(context => configuration); Bind<IDataContext>().To<DatabaseContext>().InRequestScope(); Bind<IRepository>().To<EntityFrameworkRepository>().InRequestScope(); }
/// <summary> /// <para> /// Evaluates the given XML section and returns a <see cref="ConfigurationSettings"/> instance that contains the results of the evaluation. /// </para> /// </summary> /// <param name="parent"> /// <para>The configuration settings in a corresponding parent configuration section. </para> /// </param> /// <param name="configContext"> /// <para>An HttpConfigurationContext when <see cref="Create"/> is called from the ASP.NET configuration system. Otherwise, this parameter is reserved and is a null reference (Nothing in Visual Basic). </para> /// </param> /// <param name="section"> /// <para>The <see cref="XmlNode"/> that contains the configuration information to be handled. Provides direct access to the XML contents of the configuration section. </para> /// </param> /// <returns> /// <para> /// A <see cref="ConfigurationSettings"/> instance that contains the section's configuration settings. /// </para> /// </returns> public object Create(object parent, object configContext, XmlNode section) { ConfigurationSettings configurationSettings = new ConfigurationSettings(); if (section == null) { return configurationSettings; } XmlSerializer xmlSerializer = new XmlSerializer(typeof(ConfigurationSettings)); configurationSettings = (ConfigurationSettings)xmlSerializer.Deserialize(new XmlTextReader(new StringReader(section.OuterXml))); return configurationSettings; }
public ActionResult Index() { ConfigurationSettings settings; if (RoleEnvironment.IsAvailable) { settings = new ConfigurationSettings(new ServiceConfigurationProvider()); } else { settings = new ConfigurationSettings(new WebConfigProvider()); } return View(settings); }
public CodeInspectSetting() { InitializeComponent(); configurationSettings = new ConfigurationSettings(); configurationSettings = configurationSettings.Load(); if (configurationSettings == null || (configurationSettings != null && configurationSettings.CodingRules.Count == 0)) { Rules = new ObservableCollection<CodingRule>(); Rules.Add(new CodingRule() { RuleName = "Class Property Name", Type=CodingRulesTypeEnum.ClassPropertyName, RuleCase = CodingRuleCaseEnum.Normal, RuleFirstLetter = "" }); Rules.Add(new CodingRule() { RuleName = "Class Variable Name", Type = CodingRulesTypeEnum.ClassVariableName, RuleCase = CodingRuleCaseEnum.UpperCamelCase, RuleFirstLetter = "_" }); } else { Rules = configurationSettings.CodingRules; } //listOfRules.ItemsSource = rules; }
/// <summary> /// Check for class property matching rules /// </summary> /// <param name="neosSdiMef"></param> public static void ParseProperty(this NeosSdiMef neosSdiMef) { ConfigurationSettings configurationSettings = new ConfigurationSettings(); configurationSettings = configurationSettings.Load(); CodingRule rule = configurationSettings.CodingRules.Where(p => p.Type == NeosSdiConfiguration.Controls.Helpers.CodingRulesTypeEnum.ClassPropertyName).SingleOrDefault(); var root = (CompilationUnitSyntax)neosSdiMef.tree.Root; var _properties = root.DescendentNodes() .OfType<Roslyn.Compilers.CSharp.PropertyDeclarationSyntax>() .ToList(); foreach (var _property in _properties) { string text = _property.Identifier.ValueText; string textFull = _property.ToString().Replace(System.Environment.NewLine, ""); CheckFormat.CheckForFormat(neosSdiMef, rule, _property, text, textFull, _property.Identifier.Span.Start, _property.Identifier.Span.End); } }
static void Main(string[] args) { //read the customer order StreamReader sr = null; string content = null; try { sr = new StreamReader("..\\..\\OrderSample.xml"); content = sr.ReadToEnd(); } finally { sr.Close(); } GenericIdentity gi = new GenericIdentity("CustomerA"); GenericPrincipal gp = new GenericPrincipal(gi, null); //create the document object IDocument doc = new Document(gp, content, null); //load the configuration obect for the workflow SAF.Application.Configuration.ConfigurationManager cm = null; cm = (ConfigurationManager)ConfigurationSettings.GetConfig("MyApplication"); //get the inital documet layer IDocumentLayer layer = (IDocumentLayer)cm.DocumentLayerConfig.GetDocumentLayerByName("PurchaseOrderWorkFlow"); //start process the document by calling the ProcessDocument on the inital layer. //For this perticular example, the last document layer is DocumentWorkFlowLayer object //which will trigger the work flow defined in the GenericPurchaseOrderVisitor class IDocument response = layer.ProcessDocument(doc); //display potential response document if (response != null) { Console.WriteLine(">>>>>>>>>>>>>Repsonse document from " + response.Sender.Identity.Name + " has arrived <<<<<<<<<<<<"); Console.WriteLine("Response Document is: \n " + response.Content + "\n"); } //change the cost of some product to greater than $100 and run this demo again //to see how the workflow is changed. }
/// <summary> /// 取得配置文件中的字符串KEY /// </summary> /// <param name="SectionName">节点名称</param> /// <param name="key">KEY名</param> /// <returns>返回KEY值</returns> public static string GetConfigString(string SectionName, string key) { string returnVal = ""; if (SectionName != "") { try { var cfgName = (NameValueCollection)ConfigurationSettings.GetConfig(SectionName); //NameValueCollection cfgName = (NameValueCollection)ConfigurationManager.GetSection(SectionName); if (cfgName[key] != null) { returnVal = cfgName[key]; } cfgName = null; }catch {} } return(returnVal); }
public void SaveDevice_TestMethod() { IDeviceConfiguration configuration = new ConfigurationSettings(); var webCam = new HWDeviceDesciption() { Device = DeviceType.WebCam, DeviceId = "camera id custom", Name = "camera name custom" }; configuration.SaveDevice(webCam); var savedWebCam = configuration.GetDevice(DeviceType.WebCam); Assert.AreEqual(savedWebCam.Device, webCam.Device); Assert.AreEqual(savedWebCam.DeviceId, webCam.DeviceId); Assert.AreEqual(savedWebCam.Name, webCam.Name); Assert.AreEqual(savedWebCam.IsSet, webCam.IsSet); }
protected virtual IDictionary GetFeatures() { IDictionary config = (IDictionary)ConfigurationSettings.GetConfig("jayrock/jsonrpc/features"); if (config == null) { // // Check an alternate path for backward compatibility. // config = (IDictionary)ConfigurationSettings.GetConfig("jayrock/json.rpc/features"); } if (config == null) { config = DefaultFeatures; } return(config); }
public void InitConfig() { try { NameValueCollection nc = (NameValueCollection)ConfigurationSettings.GetConfig(_ConfigName); int.TryParse(nc.Get(_DbType), out _db_type); _connectString = nc.Get(_ConnectString); /* * nc = (NameValueCollection)ConfigurationSettings.GetConfig(_ConfigName); * int i = 0; * i++; * */ } catch (Exception e) { Log.WriteLog(e.Message); Log.WriteLog(e.StackTrace); } }
public void EmployeeGetAlltest() { using (var connection = new SqlConnection(ConfigurationSettings.GetConnectionString())) { //var result = connection.GetList<Employee>(); //var enumerable = result as IList<Employee> ?? result.ToList(); //foreach (var model in enumerable) //{ // Console.WriteLine("EmployeeId: {0}", model.EmployeeId); // Console.WriteLine("FullName: {0} {1} {2}", model.FirstName, model.MiddleName, model.LastName); // Console.WriteLine("Employee Number: {0}", model.EmployeeNumber); // Console.WriteLine("ImageEmployee {0}", model.ImageEmployee); // Console.WriteLine("==================================="); //} //Assert.AreEqual(1002,enumerable.Count()); } }
internal static unsafe ConfigurationPackage CreateFromNative(NativeRuntime.IFabricConfigurationPackage nativePackage) { ReleaseAssert.AssertIfNull(nativePackage, "nativePackage"); string path = NativeTypes.FromNativeString(nativePackage.get_Path()); var settings = ConfigurationSettings.CreateFromNative(nativePackage.get_Settings()); var nativeDescription = *((NativeTypes.FABRIC_CONFIGURATION_PACKAGE_DESCRIPTION *)nativePackage.get_Description()); var description = ConfigurationPackageDescription.CreateFromNative(nativeDescription, path, settings); var returnValue = new ConfigurationPackage() { Description = description, Path = path, Settings = settings }; GC.KeepAlive(nativePackage); return(returnValue); }
public void TestWriteNullEvent() { var entityModelSettings = ConfigurationSettings.GetAuditLogConfigurationSection().EntityModelSettings; bool isEnabled = entityModelSettings.IsEnabled; try { var mockDeleter = new Mock <IAuditLogDeleter>(MockBehavior.Loose); // Ensure event log is enabled entityModelSettings.IsEnabled = true; var entityModelWriter = new AuditLogEntityModelWriter(mockDeleter.Object); Assert.Throws <ArgumentNullException>(() => entityModelWriter.Write(null)); } finally { entityModelSettings.IsEnabled = isEnabled; } }
/// <summary> /// <para>Saves the configuration settings created for the application.</para> /// </summary> /// <param name="serviceProvider"> /// <para>The a mechanism for retrieving a service object; that is, an object that provides custom support to other objects.</para> /// </param> public void Save(IServiceProvider serviceProvider) { ConfigurationContext configurationContext = ServiceHelper.GetCurrentConfigurationContext(serviceProvider); ConfigurationNode node = ServiceHelper.GetCurrentRootNode(serviceProvider); try { ConfigurationSettings configurationSettings = GetConfigurationSettings(serviceProvider); configurationSettings.ApplicationName = node.Name; configurationContext.WriteMetaConfiguration(configurationSettings); } catch (ConfigurationException e) { ServiceHelper.LogError(serviceProvider, node, e); } catch (InvalidOperationException e) { ServiceHelper.LogError(serviceProvider, node, e); } }
/// <summary> /// Get an instance of the test configuration settings. First attemp to /// load the settings from the configuration file, if that fails then /// set to default values. /// </summary> /// <returns>An instance of the test configuration settings.</returns> public static SharpCvsLibTestsConfig GetInstance() { SharpCvsLibTestsConfig config; try { config = (SharpCvsLibTestsConfig)ConfigurationSettings.GetConfig (SharpCvsLibTestsConfigHandler.APP_CONFIG_SECTION); if (null == config) { config = new SharpCvsLibTestsConfig(); } } catch (Exception e) { LOGGER.Error(e); // The default values are initialized in the config file. config = new SharpCvsLibTestsConfig(); } return(config); }
public void TestWriteNullEvent() { var eventLogSettings = ConfigurationSettings.GetAuditLogConfigurationSection().EventLogSettings; bool isEnabled = eventLogSettings.IsEnabled; try { var mockEventLog = new Mock <IEventLog>(MockBehavior.Strict); // Ensure event log is enabled eventLogSettings.IsEnabled = true; var eventLogWriter = new AuditLogEventLogWriter(mockEventLog.Object); Assert.Throws <ArgumentNullException>(() => eventLogWriter.Write(null)); } finally { eventLogSettings.IsEnabled = isEnabled; } }
private async Task <ConfigurationSettings> GetConfigurationSettings(IWebHostEnvironment env, DeployMode deployMode) { var configurationSettings = new ConfigurationSettings(deployMode); //Read from appsettings if exists var section = Configuration.GetSection("ConfigurationSettings"); //Bind pre-defined properties if (section.Exists()) { Configuration.Bind("ConfigurationSettings", configurationSettings); } else { //Read from environment variables configurationSettings.LoadVariables(); } await configurationSettings.SetFilePathsProperties(env); return(configurationSettings); }
public void RemoveServer( ) { var configuration = ConfigurationSettings.GetRedisConfigurationSection( ); Assert.AreEqual(1, configuration.Servers.Count); RedisServer server = configuration.Servers[0]; configuration.Servers.RemoveAt(0); ConfigurationSettings.UpdateRedisConfigurationSection(configuration); Assert.AreEqual(0, configuration.Servers.Count); configuration.Servers.Add(server); ConfigurationSettings.UpdateRedisConfigurationSection(configuration); Assert.AreEqual(1, configuration.Servers.Count); }
/// <summary> /// Load a configuration from local file. /// </summary> /// <param name="configName">Configuration name</param> /// <param name="configFile">Configuration File Path</param> /// <param name="version">Configuration Version (expected)</param> /// <param name="settings">Configuration Settings</param> /// <param name="password">Password (if required)</param> /// <returns>Loaded Configruation</returns> public Configuration Load(string configName, string configFile, Version version, ConfigurationSettings settings, string password = null) { Preconditions.CheckArgument(configName); Preconditions.CheckArgument(configFile); Preconditions.CheckArgument(version); LogUtils.Info(String.Format("Loading Configuration. [name={0}][version={1}][file={2}]", configName, version.ToString(), configFile)); using (FileReader reader = new FileReader(configFile)) { AbstractConfigParser parser = ConfigProviderFactory.GetParser(configFile); Postconditions.CheckCondition(parser); parser.Parse(configName, reader, version, settings, password); return(parser.GetConfiguration()); } }
public Task <string> GetGreetingAsync() { if (string.IsNullOrEmpty(this.State.Greeting)) { ConfigurationSettings configSettings = this.ActorService.ServiceInitializationParameters.CodePackageActivationContext.GetConfigurationPackageObject("Config").Settings; ConfigurationSection configSection = configSettings.Sections.FirstOrDefault(s => (s.Name == "GreetingConfig")); if (configSection != null) { ConfigurationProperty defaultGreeting = configSection.Parameters.FirstOrDefault(p => (p.Name == "DefaultGreeting")); if (defaultGreeting != null) { return(Task.FromResult(defaultGreeting.Value)); } } return(Task.FromResult("No one is available, please leave a message after the beep.")); } return(Task.FromResult(this.State.Greeting)); }
public void CanAccessOtherValuesInExpression() { // Given IConfiguration configuration = GetConfiguration(@" { ""foo"": ""=> $\""ABC {bar} XYZ\"""", ""bar"": 3 }"); TestExecutionContext context = new TestExecutionContext(); context.ScriptHelper = new ScriptHelper(context); ConfigurationSettings settings = new ConfigurationSettings(context, configuration, null); // When bool result = settings.TryGetValue("foo", out object value); // Then result.ShouldBeTrue(); value.ShouldBe("ABC 3 XYZ"); }
void ReadConfigFile() { // Application configuration settings try { string szipport = System.Configuration.ConfigurationManager.AppSettings["ipport"]; string milliseconds = System.Configuration.ConfigurationManager.AppSettings["cycletime"]; string ReadTimeout = System.Configuration.ConfigurationManager.AppSettings["ReadTimeout"]; string szDebug = System.Configuration.ConfigurationManager.AppSettings["debug"]; SimulatedDevice.dTimeDivisor = Convert.ToDouble(System.Configuration.ConfigurationManager.AppSettings["TimeDivisor"]); SimulatedDevice.nSimCycleTime = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SimCycleTime"]); ipport = (szipport != null) ? Convert.ToInt32(szipport) : 80; _cycletime = (milliseconds != null) ? Convert.ToInt32(milliseconds) : 2000; _debug = (szDebug != null) ? Convert.ToInt32(szDebug) : 0; ////MTConnectAgentSHDR.ShdrObj.ReadTimeout = 600000; ////if (ReadTimeout != null) //// MTConnectAgentSHDR.ShdrObj.ReadTimeout = Convert.ToInt32(ReadTimeout); if (_debug > 99) { System.Diagnostics.Debugger.Break(); } // Get the current configuration file. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) as System.Configuration.Configuration; //ConfigurationSection customSection = config.GetSection("Devices"); //string xml = customSection.SectionInformation.GetRawXml(); devices = (List <SimulatedDevice>)ConfigurationSettings.GetConfig("Devices"); } catch (Exception ex) { string msg = " Error " + ex.Message; Logger.LogMessage(msg, 0); Application.Exit(); return; } }
/// <summary> /// To the set the value of the property of the control /// </summary> /// <param name="theControl">Control for which property value need to be set</param> /// <param name="Root">xml containing all the values for the controls</param> /// //private void SetStyleAllControls(Control theControl, XmlElement theRoot) //{ // if (theControl.Controls.Count > 0) // { // foreach (Control ctrl in theControl.Controls) // { // if (ctrl.GetType().Name == "Panel" || ctrl.GetType().Name == "GroupBox" || ctrl.GetType().Name == "TabControl" || ctrl.GetType().Name == "Splitter" || ctrl.GetType().Name == "TabPage" || // ctrl.GetType().Name == "TableLayoutPanel" || ctrl.GetType().Name == "FlowLayoutPanel" || ctrl.GetType().Name == "SplitterPanel" || ctrl.GetType().Name == "SplitContainer") //pannel or groupbox // { // SetStyleAllControls(ctrl, theRoot); // } // else // { // setValue(ctrl, theRoot); // } // } // } // else // { // setValue(theControl, theRoot); // } //} public void setValue(Control theControl, XmlElement Root) { XmlNode Node; string theImgPath = ((NameValueCollection)ConfigurationSettings.GetConfig("appSettings"))["ImagePath"]; foreach (Control ctrl in theControl.Controls) { Node = null; if (ctrl.Tag != null) { Node = Root.SelectSingleNode("Style[@Id = '" + ctrl.Tag.ToString().Trim() + "']"); if (Node != null) { ctrl.ForeColor = System.Drawing.Color.FromName(Node.Attributes["ForeColor"].Value); int theFontSize = Convert.ToInt32(Node.Attributes["FontSize"].Value); if (Node.Attributes["FontStyle"].Value == "1") { ctrl.Font = new System.Drawing.Font((Node.Attributes["Font"].Value.ToString()), ((float)(theFontSize)), System.Drawing.FontStyle.Bold); } else { ctrl.Font = new System.Drawing.Font((Node.Attributes["Font"].Value.ToString()), ((float)(theFontSize))); } if (Node.Attributes["Width"].Value != "" && Node.Attributes["Height"].Value != "") { ctrl.Size = new System.Drawing.Size(Convert.ToInt32(Node.Attributes["Width"].Value), Convert.ToInt32(Node.Attributes["Height"].Value)); } else if (Node.Attributes["Height"].Value != "") { ctrl.Height = Convert.ToInt32(Node.Attributes["Height"].Value); } } } if (ctrl.GetType().Name == "Panel" || ctrl.GetType().Name == "GroupBox" || ctrl.GetType().Name == "TabControl" || ctrl.GetType().Name == "Splitter" || ctrl.GetType().Name == "TabPage" || ctrl.GetType().Name == "TableLayoutPanel" || ctrl.GetType().Name == "FlowLayoutPanel" || ctrl.GetType().Name == "SplitterPanel" || ctrl.GetType().Name == "SplitContainer" || ctrl.GetType().Name == "UserControl") //pannel or groupbox { setValue(ctrl, Root); } }//end of function }
private bool SaveKeyAlgorithmPairWithNewDapiSettings(DpapiSettings newDpapiSettings, DpapiSettings originalDpapiSettings) { ConfigurationContext context = GetContext(); ConfigurationSettings settings = context.GetMetaConfiguration(); FileKeyAlgorithmPairStorageProvider loadProvider = new FileKeyAlgorithmPairStorageProvider(); FileKeyAlgorithmPairStorageProviderData loadData = new FileKeyAlgorithmPairStorageProviderData( SR.DefaultFileKeyAlgorithmStorageProviderNodeName, currentNode.File, GetDpapiSettingsData(originalDpapiSettings)); settings.KeyAlgorithmPairStorageProviderData = loadData; loadProvider.ConfigurationName = loadData.Name; loadProvider.Initialize(new RuntimeConfigurationView(context)); FileKeyAlgorithmPairStorageProvider saveProvider = new FileKeyAlgorithmPairStorageProvider(); FileKeyAlgorithmPairStorageProviderData saveData = new FileKeyAlgorithmPairStorageProviderData( SR.DefaultFileKeyAlgorithmStorageProviderNodeName, currentNode.File, GetDpapiSettingsData(newDpapiSettings)); settings.KeyAlgorithmPairStorageProviderData = saveData; saveProvider.ConfigurationName = saveData.Name; saveProvider.Initialize(new RuntimeConfigurationView(context)); try { KeyAlgorithmPair key = loadProvider.Load(); saveProvider.Save(key); } catch (Exception ex) { MessageBox.Show( SR.FileKeyAlgorithmDpapiSettingsEditorUnableToSaveNewDpapiSettingsErrorMessage(ex.Message), SR.FileKeyAlgorithmDpapiSettingsEditorUnableToSaveNewDpapiSettingsCaption, MessageBoxButtons.OK, MessageBoxIcon.Error ); return(false); } return(true); }
public ActionResult SendSMS(ConfigurationSettings sm) { string API_KEY = sm.API_KEY; string API_SECRET = sm.API_SECRET; double TO = Convert.ToDouble(sm.To_Number); string Message = sm.TextMessage; string sURL; sURL = "https://www.thetexting.com/rest/sms/json/message/send?api_key=" + API_KEY + "&api_secret=" + API_SECRET + "&from=test" + "&to=" + TO + "&text=" + Message + "&type=text"; if (ModelState.IsValid) { try { using (WebClient client = new WebClient()) { string s = client.DownloadString(sURL); var responseObject = Newtonsoft.Json.JsonConvert.DeserializeObject <RootObject>(s); int n = responseObject.Status; if (n == 3) { return(Content("<script>alert('Message does not Send Successfully due to invalid credentials !');location.href='/';</script>")); } else { return(Content("<script>alert('Message Send Successfully !');location.href='/';</script>")); } } } catch (Exception ex) { ModelState.AddModelError("", "Error in sending Message"); ex.ToString(); } return(View("Index")); } else { ModelState.AddModelError("", "Error in sending Message"); return(View("Index")); } }
// Constructors static WebRequest() { if (Platform.IsMacOS) { #if MONOTOUCH Type type = Type.GetType("MonoTouch.CoreFoundation.CFNetwork, monotouch"); #else Type type = Type.GetType("MonoMac.CoreFoundation.CFNetwork, monomac"); #endif if (type != null) { cfGetDefaultProxy = type.GetMethod("GetDefaultProxy"); } } #if NET_2_1 IWebRequestCreate http = new HttpRequestCreator(); RegisterPrefix("http", http); RegisterPrefix("https", http); #if MOBILE RegisterPrefix("file", new FileWebRequestCreator()); RegisterPrefix("ftp", new FtpRequestCreator()); #endif #else defaultCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore); #if CONFIGURATION_DEP object cfg = ConfigurationManager.GetSection("system.net/webRequestModules"); WebRequestModulesSection s = cfg as WebRequestModulesSection; if (s != null) { foreach (WebRequestModuleElement el in s.WebRequestModules) { AddPrefix(el.Prefix, el.Type); } return; } #endif ConfigurationSettings.GetConfig("system.net/webRequestModules"); #endif }
public void Test_GetTraceCacheInvalidationSetting() { bool oldSetting; bool newSetting; CacheInvalidator <int, int> cacheInvalidator; oldSetting = ConfigurationSettings.GetServerConfigurationSection().Security.CacheTracing; try { newSetting = !oldSetting; ConfigurationSettings.GetServerConfigurationSection().Security.CacheTracing = newSetting; cacheInvalidator = new CacheInvalidator <int, int>(new DictionaryCache <int, int>(), "Test"); Assert.That(cacheInvalidator.TraceCacheInvalidations, Is.EqualTo(newSetting)); } finally { ConfigurationSettings.GetServerConfigurationSection().Security.CacheTracing = oldSetting; } }
public BaseDALC() { // retrieve the key value pairs from the appParams section of the configuration file NameValueCollection values = (NameValueCollection)ConfigurationSettings.GetConfig("appParams"); if (values == null) { throw new ConfigurationException(ResourceManager.GetString("RES_ExceptionStoreConfigNotFound")); } // read the database connection string from the configuration information and store it in the connection // string property string connectionString = values[CONFIG_CONNECTION_STRING]; if (connectionString == null) { throw new ConfigurationException(ResourceManager.GetString("RES_ExceptionStoreConfigConnection")); } this.connectionString = connectionString; }
/// <summary> /// Called when a configuration package is modified. /// </summary> private void CodePackageActivationContext_ConfigurationPackageModifiedEvent(object sender, PackageModifiedEventArgs <ConfigurationPackage> e) { if ("Config" == e.NewPackage.Description.Name) { lock (thisLock) { this._settings = e.NewPackage.Settings; this._logger.Dispose(); this._logger = InitializeLogger(this._settings); if (this._perfCounters != null) { foreach (var counter in this._perfCounters) { counter.Dispose(); } } this._perfCounters = InitializePerformanceCounters(this._settings); } } }
public static string GetMessage(string name) { if (m_msgs == null) { m_msgs = new Hashtable(); NameValueCollection msgs = (NameValueCollection) ConfigurationSettings.GetConfig("Messages"); foreach (string msgkey in msgs) { string msg = msgs[msgkey]; m_msgs.Add(msgkey, msg); } } string val = (string)m_msgs[name]; val = val.Replace(@"\n", "\n"); return(val); }
/// <summary> /// 获得主页主推产品 /// </summary> /// <param name="Top"></param> /// <returns></returns> public async Task <IEnumerable <ProductInfo> > GetRecommendProduct(int Top) { StringBuilder strSql = new StringBuilder(); strSql.Append("select "); if (Top > 0) { strSql.Append(" top " + Top); } strSql.Append(" ProductCode,ProductName,ProductFeature,MinPrice,ImgUrlList,ImgUrlApp,ProductDesc "); strSql.Append(" FROM ProductInfo "); strSql.Append(" where IsValid=1 and IsRecommend=1 "); strSql.Append(" order by OrderNum "); using (IDbConnection conn = new SqlConnection(ConfigurationSettings.GetConnectionString())) { var list = await conn.QueryAsync <ProductInfo>(strSql.ToString()); return(list); } }
public void PopulateTest() { object o = ConfigurationSettings.GetConfig(configSection); DataSet ds = o as DataSet; DataTable dt = ds.Tables [0]; Assert.AreEqual(2, dt.Rows.Count, "#A1"); DataRow r = dt.Rows.Find("ProviderTest.InvariantName"); Assert.AreEqual("ProviderTest.Name", r ["Name"].ToString(), "#B2"); Assert.AreEqual("ProviderTest.Description", r ["Description"].ToString(), "#B3"); Assert.AreEqual("ProviderTest.InvariantName", r ["InvariantName"].ToString(), "#B4"); Assert.AreEqual("ProviderTest.AssemblyQualifiedName", r ["AssemblyQualifiedName"].ToString(), "#B5"); r = dt.Rows.Find("ProviderTest4.InvariantName"); Assert.AreEqual("ProviderTest4.Name", r ["Name"].ToString(), "#A2"); Assert.AreEqual("ProviderTest4.Description", r ["Description"].ToString(), "#A3"); Assert.AreEqual("ProviderTest4.InvariantName", r ["InvariantName"].ToString(), "#A4"); Assert.AreEqual("ProviderTest4.AssemblyQualifiedName", r ["AssemblyQualifiedName"].ToString(), "#A5"); }
/// <summary> /// Initializes a new instance of the <see cref="WelcomeTeamMembersService"/> class. /// </summary> /// <param name="configurationSettings">the configuration settings object.</param> /// <param name="eventRepository">The event repository.</param> /// <param name="botConnectorClientFactory">The bot connector client factory service.</param> /// <param name="sendToConversationQueue">The Azure service bus queue which triggers the send bot messages Azure function.</param> /// <param name="userRepository">The user repository.</param> /// <param name="userTeamMembershipRepository">The user membership repository.</param> /// <param name="welcomeTeamMembersCardRenderer">The welcome team members card renderer.</param> /// <param name="shareEventCardRenderer">The share event card renderer.</param> /// <param name="botActivityBuilder">The bot activity builder.</param> public WelcomeTeamMembersService( ConfigurationSettings configurationSettings, EventRepository eventRepository, BotConnectorClientFactory botConnectorClientFactory, SendToConversationQueue sendToConversationQueue, UserRepository userRepository, UserTeamMembershipRepository userTeamMembershipRepository, WelcomeTeamMembersCardRenderer welcomeTeamMembersCardRenderer, ShareEventCardRenderer shareEventCardRenderer, BotActivityBuilder botActivityBuilder) { this.configurationSettings = configurationSettings; this.eventRepository = eventRepository; this.botConnectorClientFactory = botConnectorClientFactory; this.sendToConversationQueue = sendToConversationQueue; this.userRepository = userRepository; this.userTeamMembershipRepository = userTeamMembershipRepository; this.welcomeTeamMembersCardRenderer = welcomeTeamMembersCardRenderer; this.shareEventCardRenderer = shareEventCardRenderer; this.botActivityBuilder = botActivityBuilder; }
static int Main(string[] args) { if (args.Length == 0 || args.Length > 1 || String.IsNullOrWhiteSpace(args[0])) { Console.WriteLine("Usage: RoadStatus <roadname> eg RoadStatus A2"); return((int)ResponseEnum.NotFound); } try { var configurationSettings = new ConfigurationSettings(); return(runAsync(args[0], configurationSettings).Result); } catch (Exception exception) { Console.WriteLine("Unexpected exception occured."); Console.WriteLine("Exception detail:"); Console.Write(exception); return((int)ResponseEnum.ExceptionOccured); } }
public static ConfigurationSettings ReadLastSettings() { string json = ""; ConfigurationSettings result = null; if (!File.Exists(configFile)) { return(null); } json = File.ReadAllText(configFile); try { result = JsonSerializer.Deserialize <ConfigurationSettings>(json); } catch { File.Delete(configFile); } return(result); }
internal ConfigurationBuilder(ConfigurationDictionary dictionary) { ArgumentValidation.CheckForNullReference(dictionary, "dictionary"); this.configurationSettings = new ConfigurationSettings(); InitializeBuilderCaches(dictionary); CloneConfigurationSettingsFromContextDictionary(dictionary); AddKeysToConfigurationSettingsSoTheyValidate(dictionary); }
/// <summary> /// <para> /// Write the meta configuration for the configuration manager to the configuration file. /// </para> /// </summary> /// <param name="configurationSettings"> /// The meta configuration to write to configuration. /// </param> /// <exception cref="ConfigurationException"> /// <para>An error occured while reading the configuration to save the data.</para> /// </exception> public void WriteMetaConfiguration(ConfigurationSettings configurationSettings) { disposableWrapper.ConfigurationBuilder.WriteMetaConfiguration(configurationSettings); }
/// <summary> /// Applies the gangway setting rule. /// </summary> /// <param name="configurationSettings">The configuration settings.</param> /// <returns> /// Validation errors /// </returns> private static Dictionary<string, string> ApplyGangwaySettingRule(ConfigurationSettings configurationSettings) { var gangwaySettingRules = new GangwaySettingsRules(configurationSettings); return gangwaySettingRules.Apply(); }
private void SaveMetaConfigurationChanges(ConfigurationSettings configurationSettings) { if (configFile != null) { AddConfigurationToConfigFile(configurationSettings); } OnConfigurationChanged(new ConfigurationChangedEventArgs(this.configFile != null ? this.configFile.FileName : string.Empty, ConfigurationSettings.SectionName)); // reload the data InitializeConfiguration(configurationSettings); }
private void UpdateClusterOperatorSettings(ConfigurationSettings settings) { KeyedCollection<string, ConfigurationProperty> clusterConfigParameters = settings.Sections["AzureSubscriptionSettings"].Parameters; // These settings are encrypted in Settings.xml using the PowerShell command: // Invoke-ServiceFabricEncryptText using a certificate this.settings = new ArmClusterOperatorSettings( clusterConfigParameters["Region"].Value, clusterConfigParameters["ClientID"].DecryptValue(), clusterConfigParameters["ClientSecret"].DecryptValue(), clusterConfigParameters["Authority"].DecryptValue(), clusterConfigParameters["SubscriptionID"].DecryptValue(), clusterConfigParameters["Username"].DecryptValue(), clusterConfigParameters["Password"].DecryptValue()); }
private bool UserAcceptsMetaConfigurationChange(ConfigurationSettings configurationSettings) { ConfigurationChangingEventArgs args = new ConfigurationChangingEventArgs(this.configFile.FileName, ConfigurationSettings.SectionName, this.configurationSettings, configurationSettings); OnConfigurationChanging(args); return args.Cancel == false; }
public Startup(ConfigurationSettings configSettings) { this.configSettings = configSettings; }
/// <summary> /// Updates the application settings with the given ConfigurationSettings object. /// </summary> /// <param name="applicationSettings"></param> private void UpdateApplicationSettings(ConfigurationSettings applicationSettings) { // For demonstration purposes, this configuration is using the built-in Settings.xml configuration option. // We could just as easily put these settings in our custom JSON configuration (RequestSettings.json), or vice-versa. try { KeyedCollection<string, ConfigurationProperty> parameters = applicationSettings.Sections["PingServiceConfiguration"].Parameters; this.frequency = TimeSpan.Parse(parameters["FrequencyTimespan"].Value); } catch (Exception e) { ServiceEventSource.Current.ServiceMessage(this, e.ToString()); } }
/// <summary> /// Applies the application setting rule. /// </summary> /// <param name="configurationSettings">The configuration settings.</param> /// <returns> /// Validation errors /// </returns> private static Dictionary<string, string> ApplyApplicationSettingRule(ConfigurationSettings configurationSettings) { var applicationSettingRules = new ApplicationSettingsRules(configurationSettings); return applicationSettingRules.Apply(); }
static ConfigurationSettings() { _current = new ConfigurationSettings(); }
/// <summary> /// <para>Initialize a new instance of the <see cref="ConfigurationManager"/> class with the preloaded configuration.</para> /// </summary> /// <param name="configurationSettings"> /// <para>The preloaded configuration data to initialize the manager.</para> /// </param> public ConfigurationBuilder(ConfigurationSettings configurationSettings) { ArgumentValidation.CheckForNullReference(configurationSettings, "configurationSettings"); InitializeConfiguration(configurationSettings); }
private void UpdateClusterConfigSettings(ConfigurationSettings settings) { KeyedCollection<string, ConfigurationProperty> clusterConfigParameters = settings.Sections["ClusterConfigSettings"].Parameters; this.config = new ClusterConfig(); this.config.RefreshInterval = TimeSpan.Parse(clusterConfigParameters["RefreshInterval"].Value); this.config.MinimumClusterCount = Int32.Parse(clusterConfigParameters["MinimumClusterCount"].Value); this.config.MaximumClusterCount = Int32.Parse(clusterConfigParameters["MaximumClusterCount"].Value); this.config.MaximumUsersPerCluster = Int32.Parse(clusterConfigParameters["MaximumUsersPerCluster"].Value); this.config.MaximumClusterUptime = TimeSpan.Parse(clusterConfigParameters["MaximumClusterUptime"].Value); this.config.UserCapacityHighPercentThreshold = Double.Parse(clusterConfigParameters["UserCapacityHighPercentThreshold"].Value); this.config.UserCapacityLowPercentThreshold = Double.Parse(clusterConfigParameters["UserCapacityLowPercentThreshold"].Value); }
private void UpdateSettings(ConfigurationSettings settings) { KeyedCollection<string, ConfigurationProperty> parameters = settings.Sections["ApplicationDeploySettings"].Parameters; string tempDirectoryParam = parameters["PackageTempDirectory"]?.Value; this.applicationPackageTempDirectory = new DirectoryInfo( String.IsNullOrEmpty(tempDirectoryParam) ? Path.GetTempPath() : tempDirectoryParam); }
internal void LoadSettings() { string file = System.Windows.Forms.Application.StartupPath + "\\Settings.xml"; ConfigurationSettings settings; if ( File.Exists(file) ) { settings = SerializationUtility.DeserializeXmlObject<ConfigurationSettings>(file); } else { settings = new ConfigurationSettings(); settings.AnimationLength = 0.2f; settings.Groups.Add("Mozilla Firefox/Mozilla Firefox"); settings.Groups.Add("Microsoft Visual/Visual Studio"); settings.Groups.Add("Internet Explorer/Internet Explorer"); settings.Triggers.Add("Key F9"); settings.Triggers.Add("Corner TopLeft"); SerializationUtility.SaveObjectToFile(settings, "Settings.xml"); } this.LoadTriggers(settings.Triggers); this.fForm.SetGroups(settings.Groups); this.fForm.AnimationLength = settings.AnimationLength; this.fForm.BorderWidth = settings.BorderWidth; this.fForm.BorderHeight = settings.BorderHeight; this.fForm.BackgroundOpacity = settings.BackgroundOpacity; this.fForm.ThumbnailOpacity = settings.ThumbnailOpacity; }
/// <summary> /// Initializes a new instance of the <see cref="GangwaySettingsRules"/> class. /// </summary> /// <param name="configurationSettings">The configuration settings.</param> public GangwaySettingsRules(ConfigurationSettings configurationSettings) { this.configurationSettings = configurationSettings; }
/// <summary> /// Validates the user. /// </summary> /// <param name="configurationSetting">The configuration setting.</param> private static void ValidateConfigurationSetting(ConfigurationSettings configurationSetting) { RuleEngine.AssignApplicationSettingRule(configurationSetting); }
/// <devdoc> /// Serialize the block configuration into an XmlNode. /// </devdoc> private XmlNode Serialize(ConfigurationSettings configurationSettings) { XmlSerializer serializer = new XmlSerializer(typeof(ConfigurationSettings), GetXmlIncludeTypes(configurationSettings)); using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture)) { serializer.Serialize(sw, configurationSettings); XmlTextReader reader = new XmlTextReader(new StringReader(sw.ToString())); reader.MoveToContent(); XmlDocument doc = new XmlDocument(); return doc.ReadNode(reader); } }
/// <summary> /// Updates the service's ClusterConfig instance with new settings from the given ConfigurationSettings. /// </summary> /// <param name="settings"> /// The ConfigurationSettings object comes from the Settings.xml file in the service's Config package. /// </param> private void UpdateClusterConfigSettings(ConfigurationSettings settings) { // All of these settings are required. // If anything is missing, fail fast. // If a setting is missing after a service upgrade, allow this to throw so the upgrade will fail and roll back. KeyedCollection<string, ConfigurationProperty> clusterConfigParameters = settings.Sections["ClusterConfigSettings"].Parameters; ClusterConfig newConfig = new ClusterConfig(); newConfig.RefreshInterval = TimeSpan.Parse(clusterConfigParameters["RefreshInterval"].Value); newConfig.MinimumClusterCount = Int32.Parse(clusterConfigParameters["MinimumClusterCount"].Value); newConfig.MaximumClusterCount = Int32.Parse(clusterConfigParameters["MaximumClusterCount"].Value); newConfig.MaximumUsersPerCluster = Int32.Parse(clusterConfigParameters["MaximumUsersPerCluster"].Value); newConfig.MaximumClusterUptime = TimeSpan.Parse(clusterConfigParameters["MaximumClusterUptime"].Value); newConfig.UserCapacityHighPercentThreshold = Double.Parse(clusterConfigParameters["UserCapacityHighPercentThreshold"].Value); newConfig.UserCapacityLowPercentThreshold = Double.Parse(clusterConfigParameters["UserCapacityLowPercentThreshold"].Value); this.config = newConfig; }
private void UpdateSendMailSettings(ConfigurationSettings settings) { KeyedCollection<string, ConfigurationProperty> sendGridParameters = settings.Sections["SendGridSettings"].Parameters; this.credentials = new NetworkCredential( sendGridParameters["Username"].DecryptValue().ToUnsecureString(), sendGridParameters["Password"].DecryptValue()); this.mailAddress = sendGridParameters["MailAddress"].Value; this.mailFrom = sendGridParameters["MailFrom"].Value; this.mailSubject = sendGridParameters["MailSubject"].Value; }
public void SerializeTest() { XmlSerializer xmlSerializer = new XmlSerializer(typeof(ConfigurationSettings), new Type[] {typeof(XmlFileStorageProviderData)}); ConfigurationSettings configurationSettings = new ConfigurationSettings(); configurationSettings.XmlIncludeTypes.Add(new XmlIncludeTypeData("My Custom Storage Provider", "Microsoft.Practices.EnterpriseLibrary.Configuration.MyCustomStorageProvider, Microsoft.Practices.EnterpriseLibrary.Configuration")); configurationSettings.XmlIncludeTypes.Add(new XmlIncludeTypeData("My Custom Transformer", "Microsoft.Practices.EnterpriseLibrary.Configuration.MyCustomTransformer, Microsoft.Practices.EnterpriseLibrary.Configuration")); configurationSettings.XmlIncludeTypes.Add(new XmlIncludeTypeData("My Custom Key Algorithm Pair Storage Provider Data", "Microsoft.Practices.EnterpriseLibrary.Configuration.MyCustomKeyAlgorithmPairStorageProviderData, Microsoft.Practices.EnterpriseLibrary.Configuration")); configurationSettings.ApplicationName = "MyApplication"; ConfigurationSectionData configurationSection = new ConfigurationSectionData("ApplConfig1", false, GetStorageProvider(), GetTransformer()); configurationSettings.ConfigurationSections.Add(configurationSection); configurationSection = new ConfigurationSectionData("ApplConfig2", false, GetStorageProvider(), GetTransformer()); configurationSettings.ConfigurationSections.Add(configurationSection); FileKeyAlgorithmPairStorageProviderData fileKeyAlgorithmPairStorageProviderData = new FileKeyAlgorithmPairStorageProviderData("FileStore", "foo.data"); DpapiSettingsData dpapiData = new DpapiSettingsData(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 5, 6}, DpapiStorageMode.Machine); fileKeyAlgorithmPairStorageProviderData.DpapiSettings = dpapiData; configurationSettings.KeyAlgorithmPairStorageProviderData = fileKeyAlgorithmPairStorageProviderData; StringBuilder configXml = new StringBuilder(); XmlTextWriter writer = new XmlTextWriter(new StringWriter(configXml, CultureInfo.CurrentCulture)); writer.Formatting = Formatting.None; xmlSerializer.Serialize(writer, configurationSettings); writer.Close(); Assert.AreEqual(xmlString, configXml.ToString()); }