Search Results

Search found 37 results on 2 pages for 'configurationsection'.

Page 1/2 | 1 2  | Next Page >

  • Default Accessor Needed: Custom ConfigurationSection

    - by Mark
    I am totally confused by a simple Microsoft error message. When I run XSD.exe against an assembly that contains a custom ConfigurationSection (which in turn utilizes a custom ConfigurationElement and a custom ConfigurationElementCollection, as well as several ConfigurationProperties), I get the following error message: Error: There was an error processing 'Olbert.Entity.Utils.dll'. There was an error reflecting type 'Olbert.Entity.DatabaseConnection'. You must implement a default accessor on System.Configuration.ConfigurationLockCollection because it inherits from ICollection. Yet the class in question has a default accessor: public object this[int idx] { get { return null; } set { } } I realize the above doesn't do anything, but I don't need to access the element's properties by index. I'm just trying to work around the error message. So what's going on?

    Read the article

  • Loading a ConfigurationSection with a required child ConfigurationElement with .Net configuration fr

    - by Vadim Rybak
    I have a console application that is trying to load a CustomConfigurationSection from a web.config file. The custom configuration section has a custom configuration element that is required. This means that when I load the config section, I expect to see an exception if that config element is not present in the config. The problem is that the .NET framework seems to be completely ignoring the isRequired attribute. So when I load the config section, I just creates an instance of the custom configuration element and sets it on the config section. My question is, why is this happening? I want the GetSection() method to fire a ConfigurationErrors exception since a required element is missing from the configuration. Here is how my config section looks. public class MyConfigSection : ConfigurationSection { [ConfigurationProperty("MyConfigElement", IsRequired = true)] public MyConfigElement MyElement { get { return (MyConfigElement) this["MyConfigElement"]; } } } public class MyConfigElement : ConfigurationElement { [ConfigurationProperty("MyAttribute", IsRequired = true)] public string MyAttribute { get { return this["MyAttribute"].ToString(); } } } Here is how I load the config section. class Program { public static Configuration OpenConfigFile(string configPath) { var configFile = new FileInfo(configPath); var vdm = new VirtualDirectoryMapping(configFile.DirectoryName, true, configFile.Name); var wcfm = new WebConfigurationFileMap(); wcfm.VirtualDirectories.Add("/", vdm); return WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/"); } static void Main(string[] args) { try{ string path = @"C:\Users\vrybak\Desktop\Web.config"; var configManager = OpenConfigFile(path); var configSection = configManager.GetSection("MyConfigSection") as MyConfigSection; MyConfigElement elem = configSection.MyElement; } catch (ConfigurationErrorsException ex){ Console.WriteLine(ex.ToString()); } } Here is what my config file looks like. <?xml version="1.0"?> <configuration> <configSections> <section name="MyConfigSection" type="configurationFrameworkTestHarness.MyConfigSection, configurationFrameworkTestHarness" /> </configSections> <MyConfigSection> </MyConfigSection> The wierd part is that if I open the config file and load the section 2 times in a row, I will get the exception that I expect. var configManager = OpenConfigFile(path); var configSection = configManager.GetSection("MyConfigSection") as MyConfigSection; configManager = OpenConfigFile(path); configSection = configManager.GetSection("MyConfigSection") as MyConfigSection; If I use the code above, then the exception will fire and tell me that MyConfigElement is required. The question is Why is it not throwing this exception the first time??

    Read the article

  • How to include simple collections in ConfigurationSection

    - by mikemanne
    Is there a way for me to include a simple array of strings, or List<string> on my custom subclass of ConfigurationSection? (Or an array or generic list of simple data objects, for that matter?) I'm becoming familiar with the new (and VERY verbose) ConfigurationSection, ConfigurationElement, and ConfigurationElementCollection classes, but I'm by no means an expert yet. It seems like ConfigurationSection should handle simple collections/lists on its own, without me having to create a custom ConfigurationElementCollection subclass for each and every one. But I haven't found any reference to this ability online.

    Read the article

  • Access ConfigurationSection from ConfigurationElement

    - by shivesh
    I have a configuration class that maps web.config, something like that: public class SiteConfigurationSection : ConfigurationSection { [ConfigurationProperty("defaultConnectionStringName", DefaultValue = "LocalSqlServer")] public string DefaultConnectionStringName { get { return (string)base["defaultConnectionStringName"]; } set { base["defaultConnectionStringName"] = value; } } [ConfigurationProperty("Module", IsRequired = true)] public ModuleElement Module { get { return (ModuleElement)base["Module"]; } } } public class ModuleElement : ConfigurationElement { [ConfigurationProperty("connectionStringName")] public string ConnectionStringName { get { return (string)base["connectionStringName"]; } set { base["connectionStringName"] = value; } } public string ConnectionString { get { string str; if (string.IsNullOrEmpty(this.ConnectionStringName)) { str =//GET THE DefaultConnectionStringName from SiteConfigurationSection; } else str = this.ConnectionStringName; return WebConfigurationManager.ConnectionStrings[str].ConnectionString; } } } Meaning if connection string name value is missing in Module section in web.config file, the value should be read from configurationsection. How to do that?

    Read the article

  • ConfigurationSection with multiple projects

    - by shivesh
    In my asp.net solution i have a couple of class library-projects that act as modules of the site. In main project I have SiteConfigurationSection class that derives from ConfigurationSection. I want all projects to be able to access and use this SiteConfigurationSection. But class library projects can't access it because they obviously don't have a reference to the website itself. Should create a special library-project for SiteConfigurationSection of maybe it's better to create a mini SiteConfigurationSection class in every project and encapsulate only the needed values?

    Read the article

  • Could not load ConfigurationSection class - type

    - by nCdy
    at web.config <section name="FlowWebDataProviders" type="FlowWebProvidersSection" requirePermission="false"/> <FlowWebDataProviders peopleProviderName="sqlProvider" IzmListProviderName="sqlProvider"> <PeopleProviders> <add name="sqlProvider" type="SqlPeopleProvider" connectionStringName="FlowServerConnectionString"/> <add name="xmlProvider" type="XmlPeopleProvider" schemaFile="People.xsd" dataFile="People.xml"/> </PeopleProviders> <IzmListProviders> <add name="sqlProvider" type="SqlIzmListProvider" connectionStringName="FlowServerConnectionString"/> </IzmListProviders> </FlowWebDataProviders> and public class FlowWebProvidersSection : ConfigurationSection { [ConfigurationProperty("peopleProviderName", IsRequired = true)] public PeopleProviderName : string { get { this["peopleProviderName"] :> string } set { this["peopleProviderName"] = value; } } [ConfigurationProperty("IzmListProviderName", IsRequired = true)] public IzmListProviderName : string { get { (this["IzmListProviderName"] :> string) } set { this["IzmListProviderName"] = value; } } [ConfigurationProperty("PeopleProviders")] [ConfigurationValidatorAttribute(typeof(ProviderSettingsValidation))] public PeopleProviders : ProviderSettingsCollection { get { this["PeopleProviders"] :> ProviderSettingsCollection } } [ConfigurationProperty("IzmListProviders")] [ConfigurationValidatorAttribute(typeof(ProviderSettingsValidation))] public IzmListProviders : ProviderSettingsCollection { get { this["IzmListProviders"] :> ProviderSettingsCollection } } } and public class ProviderSettingsValidation : ConfigurationValidatorBase { public override CanValidate(typex : Type) : bool { if(typex : object == typeof(ProviderSettingsCollection)) true else false } /// <summary> // validate the provider section /// </summary> public override Validate(value : object) : void { mutable providerCollection : ProviderSettingsCollection = match(value) { | x is ProviderSettingsCollection => x | _ => null } unless (providerCollection == null) { foreach (_provider is ProviderSettings in providerCollection) { when (String.IsNullOrEmpty(_provider.Type)) { throw ConfigurationErrorsException("Type was not defined in the provider"); } mutable dataAccessType : Type = Type.GetType(_provider.Type); when (dataAccessType == null) { throw (InvalidOperationException("Provider's Type could not be found")); } } } } } project : Web Application ... I need to find error first . . . why : Error message parser: Error creating configuration section handler for FlowWebDataProviders: Could not load type 'FlowWebProvidersSection'. ? by the way : syntax of nemerle (current language) is very similar C#, don't afraid to read the code... thank you

    Read the article

  • Custom ConfigurationSection: CallbackValidator called with empty string

    - by Paolo Tedesco
    I am writing a custom configuration section, and I would like to validate a configuration property with a callback, like in this example: using System; using System.Configuration; class CustomSection : ConfigurationSection { [ConfigurationProperty("stringValue", IsRequired = false)] [CallbackValidator(Type = typeof(CustomSection), CallbackMethodName = "ValidateString")] public string StringValue { get { return (string)this["stringValue"]; } set { this["stringValue"] = value; } } public static void ValidateString(object value) { if (string.IsNullOrEmpty((string)value)) { throw new ArgumentException("string must not be empty."); } } } class Program { static void Main(string[] args) { CustomSection cfg = (CustomSection)ConfigurationManager.GetSection("customSection"); Console.WriteLine(cfg.StringValue); } } And my App.config file looks like this: <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="customSection" type="CustomSection, config-section"/> </configSections> <customSection stringValue="lorem ipsum"/> </configuration> My problem is that when the ValidateString function is called, the value parameter is always an empty string, and therefore the validation fails. If i just remove the validator, the string value is correctly initialized to the value in the configuration file. What am I missing? EDIT I discovered that actually the validation function is being called twice: the first time with the default value of the property, which is an empty string if nothing is specified, the second time with the real value read from the configuration file. Is there a way to modify this behavior?

    Read the article

  • Create Virtual Directory and Set Permissions IIS7 - Cannot read configuration file due to insufficie

    - by Nick
    I am trying to create a virtual directory and set it's permissions using IIS7 and C#. Here is a sample of my code: using (ServerManager serverManager = new ServerManager(webSite)) { ConfigurationSection anonymousAuthenticationSection = config.GetSection( @"system.webServer/security/authentication/anonymousAuthentication", webSite); anonymousAuthenticationSection["enabled"] = true; serverManager.CommitChanges(); return "true"; } This throws an exception and the message is: Cannot read configuration file due to insufficient permissions. Can someone help?

    Read the article

  • Calling Save on a Configuration obj with a custom sectiongroup of type NameValueSectionHandler

    - by Allen
    I've got aConfiguration object that I can easily read and write settings from and call Save(ConfigurationSaveMode.Minimal, true) on and that typically works just fine. However, I now have a config file that has a custom sectionGroup defined of type System.Configuration.NameValueSectionHandler (I didn't write that part and I can't change it). Now when I call the Save method, it throws a TypeLoadException Message: Type System.Configuration.NameValueSectionHandler does not inherit from System.Configuration.ConfigurationSectionGroup. Callstack: at System.Configuration.TypeUtil.VerifyAssignableType (Type baseType, Type type, Boolean throwOnError) at System.Configuration.TypeUtil.GetConstructorWithReflectionPermission (Type type, Type baseType, Boolean throwOnError) at System.Configuration.MgmtConfigurationRecord.CreateSectionGroupFactory (FactoryRecord factoryRecord) at System.Configuration.MgmtConfigurationRecord.EnsureSectionGroupFactory (FactoryRecord factoryRecord) at System.Configuration.MgmtConfigurationRecord.GetSectionGroup (String configKey) at System.Configuration.ConfigurationSectionGroupCollection.Get (String name) at System.Configuration.ConfigurationSectionGroupCollection. <GetEnumerator>d__0.MoveNext() at System.Configuration.Configuration.ForceGroupsRecursive (ConfigurationSectionGroup group) at System.Configuration.Configuration.SaveAsImpl (String filename, ConfigurationSaveMode saveMode, Boolean forceSaveAll) at System.Configuration.Configuration.Save (ConfigurationSaveMode saveMode, Boolean forceSaveAll) at MyCompany.MyProduct.blah.blah.Save () in C:\\projects\\blah\\blah\\blah.cs:line blah For reference, the configuration goes like so <configuration> <configSections> ... normal sections here that work just fine, followed by ... <sectionGroup name="threadSettings" type="System.Configuration.NameValueSectionHandler"> <section name="T1" type="System.Configuration.DictionarySectionHandler"/> <section name="T2" type="System.Configuration.DictionarySectionHandler"/> <section name="T3" type="System.Configuration.DictionarySectionHandler"/> </sectionGroup> </configSections> <applicationSettings /> <threadSettings> <T1> <add key="key-here" value="value-here"/> </T1> ... T2 and T3 here as well, thats not interesting ... </threadSettings> </configuration> If I remove the actual sections and the definition for the custom section groups, I am able to read / write settings just fine and even call Save just fine. Obviously the custom section groups could be setup a little nicer but I can't fix that so I'm wondering: Is it possible to get the Configuration object to save if it has custom sectionGroups of the NameValueSectionHandler type

    Read the article

  • Intellisense for custom config section problem with namespaces

    - by Quick Joe Smith
    I have just rolled a custom configuration section, created an accompanying schema document for Intellisense and added it to the Web.config's Schemas property as per Michael Stum's answer to another similar question. Unfortunately, and possibly due to me creating the XSD by hand with limited knowledge, the Intellisense relies on an xmlns attribute pointing to my XSD file's namespace being present in the custom config element. However, when running the project I get an Unrecognized attribute 'xmlns'. Note that attribute names are case-sensitive error. I could probably just modify my XSD file to define the xmlns attribute for that element, however I am wondering if this is just a bandaid fix to a larger problem. I must confess I don't have a very good understanding of XML namespaces so this might be an oppportunity to set me straight on a few things. Here is the attributes for my XSD file's root xs:schema element: <xs:schema id="awesomeConfig" targetNamespace="http://awesome.com/schemas" xmlns="http://awesome.com/schemas" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> ... </xs:schema> And on creating the element in the Web.config file, Visual Studio 2008 automatically appends: <awesomeConfig xmlns="http://awesome.com/schemas"></awesomeConfig> So have I misunderstood the meaning of the xs:schema attributes at all, or is the proper solution as simple as it seems?

    Read the article

  • .Net Custom Configuration Section and Saving Changes within PropertyGrid

    - by Paul
    If I load the My.Settings object (app.config) into a PropertyGrid, I am able to edit the property inside the propertygrid and the change is automatically saved. PropertyGrid1.SelectedObject = My.Settings I want to do the same with a Custom Configuration Section. Following this code example (from here http://www.codeproject.com/KB/vb/SerializePropertyGrid.aspx), he is doing explicit serialization to disk when a "Save" button is pushed. Public Class Form1 'Load AppSettings Dim _appSettings As New AppSettings() Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click _appSettings = AppSettings.Load() ' Actually change the form size Me.Size = _appSettings.WindowSize PropertyGrid1.SelectedObject = _appSettings End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click _appSettings.Save() End Sub End Class In my code, my custom section Inherits from ConfigurationSection (see below) Question: Is there something built into ConfigurationSection class that does the autosave? If not, what is the best way to handle this, should it be in the PropertyGrid.PropertyValueChagned? (how does the My.Settings handle this internally?) Here is the example Custom Class that I am trying to get to auto-save and how I load into property grid. Dim config As System.Configuration.Configuration = _ ConfigurationManager.OpenExeConfiguration( _ ConfigurationUserLevel.None) PropertyGrid2.SelectedObject = config.GetSection("CustomSection") Public NotInheritable Class CustomSection Inherits ConfigurationSection ' The collection (property bag) that contains ' the section properties. Private Shared _Properties As ConfigurationPropertyCollection ' The FileName property. Private Shared _FileName As New ConfigurationProperty("fileName", GetType(String), "def.txt", ConfigurationPropertyOptions.IsRequired) ' The MasUsers property. Private Shared _MaxUsers _ As New ConfigurationProperty("maxUsers", _ GetType(Int32), 1000, _ ConfigurationPropertyOptions.None) ' The MaxIdleTime property. Private Shared _MaxIdleTime _ As New ConfigurationProperty("maxIdleTime", _ GetType(TimeSpan), TimeSpan.FromMinutes(5), _ ConfigurationPropertyOptions.IsRequired) ' CustomSection constructor. Public Sub New() _Properties = New ConfigurationPropertyCollection() _Properties.Add(_FileName) _Properties.Add(_MaxUsers) _Properties.Add(_MaxIdleTime) End Sub 'New ' This is a key customization. ' It returns the initialized property bag. Protected Overrides ReadOnly Property Properties() _ As ConfigurationPropertyCollection Get Return _Properties End Get End Property <StringValidator( _ InvalidCharacters:=" ~!@#$%^&*()[]{}/;'""|\", _ MinLength:=1, MaxLength:=60)> _ <EditorAttribute(GetType(System.Windows.Forms.Design.FileNameEditor), GetType(System.Drawing.Design.UITypeEditor))> _ Public Property FileName() As String Get Return CStr(Me("fileName")) End Get Set(ByVal value As String) Me("fileName") = value End Set End Property <LongValidator(MinValue:=1, _ MaxValue:=1000000, ExcludeRange:=False)> _ Public Property MaxUsers() As Int32 Get Return Fix(Me("maxUsers")) End Get Set(ByVal value As Int32) Me("maxUsers") = value End Set End Property <TimeSpanValidator(MinValueString:="0:0:30", _ MaxValueString:="5:00:0", ExcludeRange:=False)> _ Public Property MaxIdleTime() As TimeSpan Get Return CType(Me("maxIdleTime"), TimeSpan) End Get Set(ByVal value As TimeSpan) Me("maxIdleTime") = value End Set End Property End Class 'CustomSection

    Read the article

  • Web.config encryption/decryption

    - by Akshay
    In my applications we.config file I have a connection string stored. I encrypted it using '---open the web.config file Dim config As Configuration = _ ConfigurationManager.OpenWebConfiguration( _ Request.ApplicationPath) '---indicate the section to protect Dim section As ConfigurationSection = _ config.Sections("connectionStrings") '---specify the protection provider section.SectionInformation.ProtectSection(protectionProvider) '---Apple the protection and update config.Save() Now I can decrypt it using the code Dim config As Configuration = _ ConfigurationManager.OpenWebConfiguration( _ Request.ApplicationPath) Dim section As ConfigurationSection = _ config.Sections("connectionStrings") section.SectionInformation.UnProtectSection() config.Save() I want to know where is the key stored. Also If somehow my web.config file is stolen, will it be possible for him/her to decrypt it using thhe code above.

    Read the article

  • Is it possible to protect a single element in the appSettings section instead of the entire section?

    - by hambonious
    I would like to protect one key/value pair in my appSettings but not the others using something like I've previously done with the ProtectSection method as seen below. var configurationSection = config.GetSection("appSettings"); configurationSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider"); Ideally I would like to do something like the following: var configurationElement = config.GetSection("appSettings").GetElement("Protected"); configurationElement.ElementInformation.ProtectElement("DataProtectionConfigurationProvider"); Here is the example appSettings I would be operating on: <configuration> <appSettings> <add key="Unprotected" value="ChangeMeFreely" /> <add key="Protected" value="########"/> </appSettings> </configuration> I've been searching but haven't found a way to do this. Is this possible?

    Read the article

  • How can I share Configuration Settings across multiple projects in Visual Studio?

    - by Muneeb
    Ok I know this may be a design issue, so I would love to have remarks on that as well. I have a Visual Studio web application solution. I have three projects as UserInterface, BusinessLogic and DataAccess. I had to store some user defined settings and I created configSections in the config file. I access these configSections through classes which inherit from .NET's ConfigurationSection base class. So in short for every project I had a separate configSection and for that corresponding configSection I had a class in that project inheriting from ConfigurationSection to access the config section settings. This works all sweet. But the problem arises if there is any setting which I need to use across multiple projects. So If I need to use a setting defined in UserInterface project configSection in, let say, BusinessLogic project I have to actually make a copy of that setting in the BusinessLogic's configSection. This ends up having the same setting copied across multiple configSections. Isn't this a bit too redundant?

    Read the article

  • Adding and accessing custom sections in your C# App.config

    - by deadlydog
    So I recently thought I’d try using the app.config file to specify some data for my application (such as URLs) rather than hard-coding it into my app, which would require a recompile and redeploy of my app if one of our URLs changed.  By using the app.config it allows a user to just open up the .config file that sits beside their .exe file and edit the URLs right there and then re-run the app; no recompiling, no redeployment necessary. I spent a good few hours fighting with the app.config and looking at examples on Google before I was able to get things to work properly.  Most of the examples I found showed you how to pull a value from the app.config if you knew the specific key of the element you wanted to retrieve, but it took me a while to find a way to simply loop through all elements in a section, so I thought I would share my solutions here.   Simple and Easy The easiest way to use the app.config is to use the built-in types, such as NameValueSectionHandler.  For example, if we just wanted to add a list of database server urls to use in my app, we could do this in the app.config file like so: 1: <?xml version="1.0" encoding="utf-8" ?> 2: <configuration> 3: <configSections> 4: <section name="ConnectionManagerDatabaseServers" type="System.Configuration.NameValueSectionHandler" /> 5: </configSections> 6: <startup> 7: <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> 8: </startup> 9: <ConnectionManagerDatabaseServers> 10: <add key="localhost" value="localhost" /> 11: <add key="Dev" value="Dev.MyDomain.local" /> 12: <add key="Test" value="Test.MyDomain.local" /> 13: <add key="Live" value="Prod.MyDomain.com" /> 14: </ConnectionManagerDatabaseServers> 15: </configuration>   And then you can access these values in code like so: 1: string devUrl = string.Empty; 2: var connectionManagerDatabaseServers = ConfigurationManager.GetSection("ConnectionManagerDatabaseServers") as NameValueCollection; 3: if (connectionManagerDatabaseServers != null) 4: { 5: devUrl = connectionManagerDatabaseServers["Dev"].ToString(); 6: }   Sometimes though you don’t know what the keys are going to be and you just want to grab all of the values in that ConnectionManagerDatabaseServers section.  In that case you can get them all like this: 1: // Grab the Environments listed in the App.config and add them to our list. 2: var connectionManagerDatabaseServers = ConfigurationManager.GetSection("ConnectionManagerDatabaseServers") as NameValueCollection; 3: if (connectionManagerDatabaseServers != null) 4: { 5: foreach (var serverKey in connectionManagerDatabaseServers.AllKeys) 6: { 7: string serverValue = connectionManagerDatabaseServers.GetValues(serverKey).FirstOrDefault(); 8: AddDatabaseServer(serverValue); 9: } 10: }   And here we just assume that the AddDatabaseServer() function adds the given string to some list of strings.  So this works great, but what about when we want to bring in more values than just a single string (or technically you could use this to bring in 2 strings, where the “key” could be the other string you want to store; for example, we could have stored the value of the Key as the user-friendly name of the url).   More Advanced (and more complicated) So if you want to bring in more information than a string or two per object in the section, then you can no longer simply use the built-in System.Configuration.NameValueSectionHandler type provided for us.  Instead you have to build your own types.  Here let’s assume that we again want to configure a set of addresses (i.e. urls), but we want to specify some extra info with them, such as the user-friendly name, if they require SSL or not, and a list of security groups that are allowed to save changes made to these endpoints. So let’s start by looking at the app.config: 1: <?xml version="1.0" encoding="utf-8" ?> 2: <configuration> 3: <configSections> 4: <section name="ConnectionManagerDataSection" type="ConnectionManagerUpdater.Data.Configuration.ConnectionManagerDataSection, ConnectionManagerUpdater" /> 5: </configSections> 6: <startup> 7: <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> 8: </startup> 9: <ConnectionManagerDataSection> 10: <ConnectionManagerEndpoints> 11: <add name="Development" address="Dev.MyDomain.local" useSSL="false" /> 12: <add name="Test" address="Test.MyDomain.local" useSSL="true" /> 13: <add name="Live" address="Prod.MyDomain.com" useSSL="true" securityGroupsAllowedToSaveChanges="ConnectionManagerUsers" /> 14: </ConnectionManagerEndpoints> 15: </ConnectionManagerDataSection> 16: </configuration>   The first thing to notice here is that my section is now using the type “ConnectionManagerUpdater.Data.Configuration.ConnectionManagerDataSection” (the fully qualified path to my new class I created) “, ConnectionManagerUpdater” (the name of the assembly my new class is in).  Next, you will also notice an extra layer down in the <ConnectionManagerDataSection> which is the <ConnectionManagerEndpoints> element.  This is a new collection class that I created to hold each of the Endpoint entries that are defined.  Let’s look at that code now: 1: using System; 2: using System.Collections.Generic; 3: using System.Configuration; 4: using System.Linq; 5: using System.Text; 6: using System.Threading.Tasks; 7:  8: namespace ConnectionManagerUpdater.Data.Configuration 9: { 10: public class ConnectionManagerDataSection : ConfigurationSection 11: { 12: /// <summary> 13: /// The name of this section in the app.config. 14: /// </summary> 15: public const string SectionName = "ConnectionManagerDataSection"; 16: 17: private const string EndpointCollectionName = "ConnectionManagerEndpoints"; 18:  19: [ConfigurationProperty(EndpointCollectionName)] 20: [ConfigurationCollection(typeof(ConnectionManagerEndpointsCollection), AddItemName = "add")] 21: public ConnectionManagerEndpointsCollection ConnectionManagerEndpoints { get { return (ConnectionManagerEndpointsCollection)base[EndpointCollectionName]; } } 22: } 23:  24: public class ConnectionManagerEndpointsCollection : ConfigurationElementCollection 25: { 26: protected override ConfigurationElement CreateNewElement() 27: { 28: return new ConnectionManagerEndpointElement(); 29: } 30: 31: protected override object GetElementKey(ConfigurationElement element) 32: { 33: return ((ConnectionManagerEndpointElement)element).Name; 34: } 35: } 36: 37: public class ConnectionManagerEndpointElement : ConfigurationElement 38: { 39: [ConfigurationProperty("name", IsRequired = true)] 40: public string Name 41: { 42: get { return (string)this["name"]; } 43: set { this["name"] = value; } 44: } 45: 46: [ConfigurationProperty("address", IsRequired = true)] 47: public string Address 48: { 49: get { return (string)this["address"]; } 50: set { this["address"] = value; } 51: } 52: 53: [ConfigurationProperty("useSSL", IsRequired = false, DefaultValue = false)] 54: public bool UseSSL 55: { 56: get { return (bool)this["useSSL"]; } 57: set { this["useSSL"] = value; } 58: } 59: 60: [ConfigurationProperty("securityGroupsAllowedToSaveChanges", IsRequired = false)] 61: public string SecurityGroupsAllowedToSaveChanges 62: { 63: get { return (string)this["securityGroupsAllowedToSaveChanges"]; } 64: set { this["securityGroupsAllowedToSaveChanges"] = value; } 65: } 66: } 67: }   So here the first class we declare is the one that appears in the <configSections> element of the app.config.  It is ConnectionManagerDataSection and it inherits from the necessary System.Configuration.ConfigurationSection class.  This class just has one property (other than the expected section name), that basically just says I have a Collection property, which is actually a ConnectionManagerEndpointsCollection, which is the next class defined.  The ConnectionManagerEndpointsCollection class inherits from ConfigurationElementCollection and overrides the requied fields.  The first tells it what type of Element to create when adding a new one (in our case a ConnectionManagerEndpointElement), and a function specifying what property on our ConnectionManagerEndpointElement class is the unique key, which I’ve specified to be the Name field. The last class defined is the actual meat of our elements.  It inherits from ConfigurationElement and specifies the properties of the element (which can then be set in the xml of the App.config).  The “ConfigurationProperty” attribute on each of the properties tells what we expect the name of the property to correspond to in each element in the app.config, as well as some additional information such as if that property is required and what it’s default value should be. Finally, the code to actually access these values would look like this: 1: // Grab the Environments listed in the App.config and add them to our list. 2: var connectionManagerDataSection = ConfigurationManager.GetSection(ConnectionManagerDataSection.SectionName) as ConnectionManagerDataSection; 3: if (connectionManagerDataSection != null) 4: { 5: foreach (ConnectionManagerEndpointElement endpointElement in connectionManagerDataSection.ConnectionManagerEndpoints) 6: { 7: var endpoint = new ConnectionManagerEndpoint() { Name = endpointElement.Name, ServerInfo = new ConnectionManagerServerInfo() { Address = endpointElement.Address, UseSSL = endpointElement.UseSSL, SecurityGroupsAllowedToSaveChanges = endpointElement.SecurityGroupsAllowedToSaveChanges.Split(',').Where(e => !string.IsNullOrWhiteSpace(e)).ToList() } }; 8: AddEndpoint(endpoint); 9: } 10: } This looks very similar to what we had before in the “simple” example.  The main points of interest are that we cast the section as ConnectionManagerDataSection (which is the class we defined for our section) and then iterate over the endpoints collection using the ConnectionManagerEndpoints property we created in the ConnectionManagerDataSection class.   Also, some other helpful resources around using app.config that I found (and for parts that I didn’t really explain in this article) are: How do you use sections in C# 4.0 app.config? (Stack Overflow) <== Shows how to use Section Groups as well, which is something that I did not cover here, but might be of interest to you. How to: Create Custom Configuration Sections Using Configuration Section (MSDN) ConfigurationSection Class (MSDN) ConfigurationCollectionAttribute Class (MSDN) ConfigurationElementCollection Class (MSDN)   I hope you find this helpful.  Feel free to leave a comment.  Happy Coding!

    Read the article

  • How to Write to a User.Config file through ConfigurationManager?

    - by Josh G
    I'm trying to persist user settings to a configuration file using ConfigurationManager. I want to scope these settings to the user only, because application changes can't be saved on Vista/Win 7 without admin privileges. This seems to get me the user's configuration, which appears to be saved here in Win 7 ([Drive]:\Users\[Username]\AppData\Local\[ApplicationName]\[AssemblyName][hash]\[Version\) Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal); Whenever I try to save any changes at all to this config I get this exception: InnerException: System.InvalidOperationException Message="ConfigurationSection properties cannot be edited when locked." Source="System.Configuration" StackTrace: at System.Configuration.SectionInformation.VerifyIsEditable() at System.Configuration.MgmtConfigurationRecord.GetConfigDefinitionUpdates(Boolean requireUpdates, ConfigurationSaveMode saveMode, Boolean forceSaveAll, ConfigDefinitionUpdates& definitionUpdates, ArrayList& configSourceUpdates) I have tried adding a custom ConfigurationSection to this config. I have tried adding to the AppSettingsSection. Whenever I call config.Save() it throws the exception above. Any ideas? I tried using the ApplicationSettingsBase class through the Project-Settings designer, but it doesn't appear that you can save custom types with this. I want similar functionality with the ability to save custom types. Thanks.

    Read the article

  • Trabajando el redireccionamiento de usuarios/Working with user redirect methods

    - by Jason Ulloa
    La protección de las aplicaciones es un elemento que no se puede dejar por fuera cuando se elabora un sistema. Cada parte o elemento de código que protege nuetra aplicación debe ser cuidadosamente seleccionado y elaborado. Una de las cosas comunes con las que nos topamos en asp.net cuando deseamos trabajar con usuarios, es con la necesidad de poder redireccionarlos a los distintos elementos o páginas dependiendo del rol. Pues precisamente eso es lo que haremos, vamos a trabajar con el Web.config de nuestra aplicación y le añadiremos unas pequeñas líneas de código para lograr dar un poco mas de seguridad al sistema y sobre todo lograr el redireccionamiento. Así que veamos como logramos lo deseado: Como bien sabemos el web.config nos permite manejar muchos elementos dentro de asp.net, muchos de ellos relacionados con la seguridad, asi como tambien nos brinda la posibilidad de poder personalizar los elementos para poder adaptarlo a nuestras necesidades. Así que, basandonos en el principio de que podemos personalizar el web.config, entonces crearemos una sección personalizada, que será la que utilicemos para manejar el redireccionamiento: Nuestro primer paso será ir a nuestro web.config y buscamos las siguientes líneas: <configuration>     <configSections>  </sectionGroup>             </sectionGroup>         </sectionGroup> Y luego de ellas definiremos una nueva sección  <section name="loginRedirectByRole" type="crabit.LoginRedirectByRoleSection" allowLocation="true" allowDefinition="Everywhere" /> El section name corresponde al nombre de nuestra nueva sección Type corresponde al nombre de la clase (que pronto realizaremos) y que será la encargada del Redirect Como estamos trabajando dentro de la seccion de configuración una vez definidad nuestra sección personalizada debemos cerrar esta sección  </configSections> Por lo que nuestro web.config debería lucir de la siguiente forma <configuration>     <configSections>  </sectionGroup>             </sectionGroup>         </sectionGroup> <section name="loginRedirectByRole" type="crabit.LoginRedirectByRoleSection" allowLocation="true" allowDefinition="Everywhere" /> </configSections> Anteriormente definimos nuestra sección, pero esta sería totalmente inútil sin el Metodo que le da vida. En nuestro caso el metodo loginRedirectByRole, este metodo lo definiremos luego del </configSections> último que cerramos: <loginRedirectByRole>     <roleRedirects>       <add role="Administrador" url="~/Admin/Default.aspx" />       <add role="User" url="~/User/Default.aspx" />     </roleRedirects>   </loginRedirectByRole> Como vemos, dentro de nuestro metodo LoginRedirectByRole tenemos el elemento add role. Este elemento será el que posteriormente le indicará a la aplicación hacia donde irá el usuario cuando realice un login correcto. Así que, veamos un poco esta configuración: add role="Administrador" corresponde al nombre del Role que tenemos definidio, pueden existir tantos elementos add role como tengamos definidos en nuestra aplicación. El elemento URL indica la ruta o página a la que será dirigido un usuario una vez logueado y dentro de la aplicación. Como vemos estamos utilizando el ~ para indicar que es una ruta relativa. Con esto hemos terminado la configuración de nuestro web.config, ahora veamos a fondo el código que se encargará de leer estos elementos y de utilziarlos: Para nuestro ejemplo, crearemos una nueva clase denominada LoginRedirectByRoleSection, recordemos que esta clase es la que llamamos en el elemento TYPE definido en la sección de nuestro web.config. Una vez creada la clase, definiremos algunas propiedades, pero antes de ello le indicaremos a nuestra clase que debe heredar de configurationSection, esto para poder obtener los elementos del web.config.  Inherits ConfigurationSection Ahora nuestra primer propiedad   <ConfigurationProperty("roleRedirects")> _         Public Property RoleRedirects() As RoleRedirectCollection             Get                 Return DirectCast(Me("roleRedirects"), RoleRedirectCollection)             End Get             Set(ByVal value As RoleRedirectCollection)                 Me("roleRedirects") = value             End Set         End Property     End Class Esta propiedad será la encargada de obtener todos los roles que definimos en la metodo personalizado de nuestro web.config Nuestro segundo paso será crear una segunda clase (en la misma clase LoginRedirectByRoleSection) a esta clase la llamaremos RoleRedirectCollection y la heredaremos de ConfigurationElementCollection y definiremos lo siguiente Public Class RoleRedirectCollection         Inherits ConfigurationElementCollection         Default Public ReadOnly Property Item(ByVal index As Integer) As RoleRedirect             Get                 Return DirectCast(BaseGet(index), RoleRedirect)             End Get         End Property         Default Public ReadOnly Property Item(ByVal key As Object) As RoleRedirect             Get                 Return DirectCast(BaseGet(key), RoleRedirect)             End Get         End Property         Protected Overrides Function CreateNewElement() As ConfigurationElement             Return New RoleRedirect()         End Function         Protected Overrides Function GetElementKey(ByVal element As ConfigurationElement) As Object             Return DirectCast(element, RoleRedirect).Role         End Function     End Class Nuevamente crearemos otra clase esta vez llamada RoleRedirect y en este caso la heredaremos de ConfigurationElement. Nuestra nueva clase debería lucir así: Public Class RoleRedirect         Inherits ConfigurationElement         <ConfigurationProperty("role", IsRequired:=True)> _         Public Property Role() As String             Get                 Return DirectCast(Me("role"), String)             End Get             Set(ByVal value As String)                 Me("role") = value             End Set         End Property         <ConfigurationProperty("url", IsRequired:=True)> _         Public Property Url() As String             Get                 Return DirectCast(Me("url"), String)             End Get             Set(ByVal value As String)                 Me("url") = value             End Set         End Property     End Class Una vez que nuestra clase madre esta lista, lo unico que nos queda es un poc de codigo en la pagina de login de nuestro sistema (por supuesto, asumo que estan utilizando  los controles de login que por defecto tiene asp.net). Acá definiremos nuestros dos últimos metodos  Protected Sub ctllogin_LoggedIn(ByVal sender As Object, ByVal e As System.EventArgs) Handles ctllogin.LoggedIn         RedirectLogin(ctllogin.UserName)     End Sub El procedimiento loggeding es parte del control login de asp.net y se desencadena en el momento en que el usuario hace loguin correctametne en nuestra aplicación Este evento desencadenará el siguiente procedimiento para redireccionar.     Private Sub RedirectLogin(ByVal username As String)         Dim roleRedirectSection As crabit.LoginRedirectByRoleSection = DirectCast(ConfigurationManager.GetSection("loginRedirectByRole"), crabit.LoginRedirectByRoleSection)         For Each roleRedirect As crabit.RoleRedirect In roleRedirectSection.RoleRedirects             If Roles.IsUserInRole(username, roleRedirect.Role) Then                 Response.Redirect(roleRedirect.Url)             End If         Next     End Sub   Con esto, nuestra aplicación debería ser capaz de redireccionar sin problemas y manejar los roles.  Además, tambien recordar que nuestro ejemplo se basa en la utilización del esquema de bases de datos que por defecto nos proporcionada asp.net.

    Read the article

  • Unable to create dynamic web application in IIS7 and above

    - by Dhwani
    Not able to view application in IIS after successfully calling below method: ServerManager serverMgr = new ServerManager(); Configuration config = serverMgr.GetApplicationHostConfiguration(); ConfigurationSection isapiCgiRestrictionSection = config.GetSection("system.webServer/security/isapiCgiRestriction"); ConfigurationElementCollection isapiCgiRestrictionCollection = isapiCgiRestrictionSection.GetCollection(); //ConfigurationElement addElement = isapiCgiRestrictionCollection.CreateElement("add"); //addElement["path"] = @"C:\Inetpub\wwwroot\"; //addElement["allowed"] = true; //addElement["groupId"] = @"ContosoGroup"; //addElement["description"] = @"Contoso Extension"; //isapiCgiRestrictionCollection.Add(addElement); //serverMgr.CommitChanges(); Site defaultSite = serverMgr.Sites["PharmaConnect"]; defaultSite.Applications.Add("/blogs3", @"C:\inetpub\wwwroot\blogs1"); serverMgr.CommitChanges(); I don't know how to create dynamically sub domain though c# code. We just tried to implement above. But unable to view application/virtual directory in iis. I have tried this, but didn't get success.

    Read the article

  • Custom Configuration Section Handlers

    Most .NET developers who need to store something in configuration tend to use appSettings for this purpose, in my experience.  More recently, the framework itself has helped things by adding the <connectionStrings /> section so at least these are in their own section and not adding to the appSettings clutter that pollutes most apps.  I recommend avoiding appSettings for several reasons.  In addition to those listed there, I would add that strong typing and validation are additional reasons to go the custom configuration section route. For my ASP.NET Tips and Tricks talk, I use the following example, which is a simple DemoSettings class that includes two fields.  The first is an integer representing how many attendees there are present for the talk, and the second is the title of the talk.  The setup in web.config is as follows: <configSections> <section name="DemoSettings" type="ASPNETTipsAndTricks.Code.DemoSettings" /> </configSections>   <DemoSettings sessionAttendees="100" title="ASP.NET Tips and Tricks DevConnections Spring 2010" /> Referencing the values in code is strongly typed and straightforward.  Here I have a page that exposes two properties which internally get their values from the configuration section handler: public partial class CustomConfig1 : System.Web.UI.Page { public string SessionTitle { get { return DemoSettings.Settings.Title; } } public int SessionAttendees { get { return DemoSettings.Settings.SessionAttendees; } } } Note that the settings are only read from the config file once after that they are cached so there is no need to be concerned about excessive file access. Now weve seen how to set it up on the config file and how to refer to the settings in code.  All that remains is to see the file itself: public class DemoSettings : ConfigurationSection { private static DemoSettings settings = ConfigurationManager.GetSection("DemoSettings") as DemoSettings; public static DemoSettings Settings{ get { return settings;} }   [ConfigurationProperty("sessionAttendees" , DefaultValue = 200 , IsRequired = false)] [IntegerValidator(MinValue = 1 , MaxValue = 10000)] public int SessionAttendees { get { return (int)this["sessionAttendees"]; } set { this["sessionAttendees"] = value; } }   [ConfigurationProperty("title" , IsRequired = true)] [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;\"|\\")] public string Title { get { return (string)this["title"]; } set { this["title"] = value; }   } } The class is pretty straightforward, but there are some important components to note.  First, it must inherit from System.Configuration.ConfigurationSection.  Next, as a convention I like to have a static settings member that is responsible for pulling out the section when the class is first referenced, and further to expose this collection via a static readonly property, Settings.  Note that the types of both of these are the type of my class, DemoSettings. The properties of the class, SessionAttendees and Title, should map to the attributes of the config element in the XML file.  The [ConfigurationProperty] attribute allows you to map the attribute name to the property name (thus using both XML standard naming conventions and C# naming conventions).  In addition, you can specify a default value to use if nothing is specified in the config file, and whether or not the setting must be provided (IsRequired).  If it is required, then it doesnt make sense to include a default value. Beyond defaults and required, you can specify more advanced validation rules for the configuration values using additional C# attributes, such as [IntegerValidator] and [StringValidator].  Using these, you can declaratively specify that your configuration values be in a given range, or omit certain forbidden characters, for instance.  Of course you can write your own custom validation attributes, and there are others specified in System.Configuration. Individual sections can also be loaded from separate files, using syntax like this: <DemoSettings configSource="demosettings.config" /> Summary Using a custom configuration section handler is not hard.  If your application or component requires configuration, I recommend creating a custom configuration handler dedicated to your app or component.  Doing so will reduce the clutter in appSettings, will provide you with strong typing and validation, and will make it much easier for other developers or system administrators to locate and understand the various configuration values that are necessary for a given application. Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • ConfigurationManager.OpenExeConfiguration() vs XML file

    - by Vince
    Hi, Could someone tell me the advantages to using the ConfigurationManager class which load's a config file for manipulation VS an XML file with a class you build to read it yourself? Recently, I built a class which inherits from ConfigurationSection in order to manipulate a custom section within app.config. This was quite a bit of work compared to just opening and reading an XML file. Some people chose the first approach, others chose the second. What's good practice?

    Read the article

  • How to publish an ASP.NET MVC application to a free host

    - by Lirik
    Hi, I'm using a free web host (0000free) which supports ASP.NET MVC, but it uses Mono. This is the first time I deploy an MVC application, so I'm a little confused as to where I need to deploy it. I have Visual Studio 2010 and I used its Publish Feature (i.e. right click on the project name and click publish) and I tried several things: Publish method: FTP to the root folder. Publish method: FTP to the publich_html folder. Publish method: File System to the root folder. Publish method: File System to the publich_html folder. Publish method: File System to a local directory on my computer and then FTP to root and also tried the public_html folder. I went into the cPanel (control panel) to try and see if ASP.NET has to be added/enabled for my web site, but I didn't see anything there. I can't browse to Index.aspx nor can I redirect to it from index.html (as suggested from other posts on the host forum), right now I have a link from index.html to Index.aspx but it's not working either (see http://www.mydevarmy.com) I've also tried renaming Index.aspx to Default.aspx, but that doesn't work either. The search utility of the forum of the host is somewhat weak, so I use google to search their forum: http://www.google.com/search?q=publish+asp.net+site%3A0000free.com%2Fforum%2F&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a I've been reading Pro ASP.NET MVC Framework and they have a chapter about publishing, but it doesn't provide any specific information with respect to the location of publishing, this is all they say (and it's not very helpful in my case): Where Should I Put My Application? You can deploy your application to any folder on the server. When IIS first installs, it automatically creates a folder for a web site called Default Web Site at c:\Inetpub\wwwroot\, but you shouldn’t feel any obligation to put your application files there. It’s very common to host applications on a different physical drive from the operating system (e.g., in e:\websites\ example.com). It’s entirely up to you, and may be influenced by concerns such as how you plan to back up the server. Here is the exception I get when I try to view my Index.aspx page: Unrecognized attribute 'targetFramework'. (/home/devarmy/public_html/Web.config line 1) Description: HTTP 500. Error processing request. Stack Trace: System.Configuration.ConfigurationErrorsException: Unrecognized attribute 'targetFramework'. (/home/devarmy/public_html/Web.config line 1) at System.Configuration.ConfigurationElement.DeserializeElement (System.Xml.XmlReader reader, Boolean serializeCollectionKey) [0x00000] in <filename unknown>:0 at System.Configuration.ConfigurationSection.DoDeserializeSection (System.Xml.XmlReader reader) [0x00000] in <filename unknown>:0 at System.Configuration.ConfigurationSection.DeserializeSection (System.Xml.XmlReader reader) [0x00000] in <filename unknown>:0 at System.Configuration.Configuration.GetSectionInstance (System.Configuration.SectionInfo config, Boolean createDefaultInstance) [0x00000] in <filename unknown>:0 at System.Configuration.ConfigurationSectionCollection.get_Item (System.String name) [0x00000] in <filename unknown>:0 at System.Configuration.Configuration.GetSection (System.String path) [0x00000] in <filename unknown>:0 at System.Web.Configuration.WebConfigurationManager.GetSection (System.String sectionName, System.String path, System.Web.HttpContext context) [0x00000] in <filename unknown>:0 at System.Web.Configuration.WebConfigurationManager.GetSection (System.String sectionName, System.String path) [0x00000] in <filename unknown>:0 at System.Web.Configuration.WebConfigurationManager.GetWebApplicationSection (System.String sectionName) [0x00000] in <filename unknown>:0 at System.Web.Compilation.BuildManager.get_CompilationConfig () [0x00000] in <filename unknown>:0 at System.Web.Compilation.BuildManager.Build (System.Web.VirtualPath vp) [0x00000] in <filename unknown>:0 at System.Web.Compilation.BuildManager.GetCompiledType (System.Web.VirtualPath virtualPath) [0x00000] in <filename unknown>:0 at System.Web.Compilation.BuildManager.GetCompiledType (System.String virtualPath) [0x00000] in <filename unknown>:0 at System.Web.HttpApplicationFactory.InitType (System.Web.HttpContext context) [0x00000] in <filename unknown>:0

    Read the article

  • Monitoring settings in a configsection of your app.config for changes

    - by dotjosh
    The usage:public static void Main() { using(var configSectionAdapter = new ConfigurationSectionAdapter<ACISSInstanceConfigSection>("MyConfigSectionName")) { configSectionAdapter.ConfigSectionChanged += () => { Console.WriteLine("File has changed! New setting is " + configSectionAdapter.ConfigSection.MyConfigSetting); }; Console.WriteLine("The initial setting is " + configSectionAdapter.ConfigSection.MyConfigSetting); Console.ReadLine(); } }  The meat: public class ConfigurationSectionAdapter<T> : IDisposable where T : ConfigurationSection { private readonly string _configSectionName; private FileSystemWatcher _fileWatcher; public ConfigurationSectionAdapter(string configSectionName) { _configSectionName = configSectionName; StartFileWatcher(); } private void StartFileWatcher() { var configurationFileDirectory = new FileInfo(Configuration.FilePath).Directory; _fileWatcher = new FileSystemWatcher(configurationFileDirectory.FullName); _fileWatcher.Changed += FileWatcherOnChanged; _fileWatcher.EnableRaisingEvents = true; } private void FileWatcherOnChanged(object sender, FileSystemEventArgs args) { var changedFileIsConfigurationFile = string.Equals(args.FullPath, Configuration.FilePath, StringComparison.OrdinalIgnoreCase); if (!changedFileIsConfigurationFile) return; ClearCache(); OnConfigSectionChanged(); } private void ClearCache() { ConfigurationManager.RefreshSection(_configSectionName); } public T ConfigSection { get { return (T)Configuration.GetSection(_configSectionName); } } private System.Configuration.Configuration Configuration { get { return ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); } } public delegate void ConfigChangedHandler(); public event ConfigChangedHandler ConfigSectionChanged; protected void OnConfigSectionChanged() { if (ConfigSectionChanged != null) ConfigSectionChanged(); } public void Dispose() { _fileWatcher.Changed -= FileWatcherOnChanged; _fileWatcher.EnableRaisingEvents = false; _fileWatcher.Dispose(); } }

    Read the article

  • Error in Encrypting web.config connection string

    - by Mohan
    Hi everybody, I am encrypting web.config file. My code is below. Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); ConfigurationSection section = config.GetSection("connectionStrings"); if (!section.SectionInformation.IsProtected) { section.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider"); config.Save(); } but this gives me error Object already exists. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Security.Cryptography.CryptographicException: Object already exists.

    Read the article

1 2  | Next Page >