CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Jul 2003
    Location
    PA
    Posts
    124

    Question Basics on C# Global Variable

    Being a newbie to C#, I have a question on best practices.

    What methodology would you recommend to store local working variable that need to be accessible anywhere in the application? All of these variable are either very slow moving or essentially static but static in that they depend on where the application is being used at (physical location, mobile, desktop, etc...). These variables are determined at start up but typically do not change during usage: but are critical for determining how the app is used and what data is collected (production monitoring system).

    I really want this to be a highly streamlined utility that limits its IO as much as possible.

    Would you suggest the following (or other)? And why?
    Local database?
    Static Class?
    Registry?
    There are 10 types of people in the world, those that understand binary and those that don't.
    Using VS 2010

  2. #2
    Join Date
    Jul 2003
    Location
    PA
    Posts
    124

    Re: Basics on C# Global Variable

    I found the Project Settings options (http://msdn.microsoft.com/en-us/libr...(v=vs.80).aspx)

    This seems to be the way to go.

    Has anyone used this? Pros/cons or things to be aware of?
    There are 10 types of people in the world, those that understand binary and those that don't.
    Using VS 2010

  3. #3
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Basics on C# Global Variable

    Project Settings are useful when you want to read and write settings and/or track different settings for different users.

    If you only need to read settings then you can just put the settings in the app.config file.

    For app config files, keep in mind that you can declare your own configSection which allows you to store more complex data over the standard key/value appSetting. Then you can use XmlSerializer to read the data out.

    For example, say I want to define a list of system folders to monitor for file changes (when the files arrive, they get parsed and the data is save to a db):
    app.config
    Code:
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <configSections>
        <section name="filePressMonitors" type="MyCompany.MyApp.MyComponent.Serialization.FilePressMonitors,MyCompany.MyApp.MyComponent" />
      </configSections>
    
      <!--DatFileMonitors values are read by the DatFileMonitors class which monitor incoming files from presses.-->
      <!--Parameters:
        Name - friendly press name
        Key - Guid which represents the press
        Folder - Unc or local path of folder where the press places the files to read
        Enabled - set to true to monitor this folder. A false setting disables the monitoring for this setting.-->
      <filePressMonitors>
        <filePressMonitor name="PressA" pressKey="8D631EB0-C97F-480C-BD12-F0B0B6262839" folder="C:\File Monitoring\Press A" enabled="true" />
        <filePressMonitor name="PressC" pressKey="B00078B2-90A0-4435-936E-6ADCC49B07F3" folder="C:\File Monitoring\Press C" enabled="true" />
        <filePressMonitor name="PressD" pressKey="9ED6C07B-815D-4FAD-B7D8-7C8B135E4DAB" folder="C:File Monitoring\Press D" enabled="true" />
      </filePressMonitors>
    </configuration>
    Next, you can build a couple of serialization classes to read the data from the app.config
    Code:
    namespace MyCompany.MyApp.MyComponent.Serialization
    {
        /// <summary>
        /// Represents Root Configuration node within the app config file
        /// </summary>
        [XmlType(AnonymousType = true)]
        [XmlRoot(ElementName = "configuration", Namespace = "", IsNullable = false)]
        public class Configuration
        {
            /// <summary>
            /// filePressMonitors node
            /// </summary>
            [XmlElement(ElementName = "filePressMonitors")]
            public FilePressMonitors FilePressMonitors { get; set; }
        }
    
    
        /// <summary>
        /// Represents the filePressMonitors node 
        /// </summary>
        public class FilePressMonitors
        {
            /// <summary>
            /// Default constructor (only used for serialization)
            /// </summary>
            public FilePressMonitors()
            {
                if (_filePressMonitorList == null) { _filePressMonitorList = new List<FilePressMonitor>(); }
            }
    
            /// <summary>
            /// Factory method which creates a FilePressMonitors instance and populates it with
            /// data from the filePressMonitor node in app.config.
            /// </summary>
            /// <returns></returns>
            [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
            public static FilePressMonitors Read()
            {
                // Deserialize the xml into an adapter object
                var xmlSerializer = new XmlSerializer(typeof(Configuration));
    
                var configuration = xmlSerializer.Deserialize(new XmlTextReader(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)) as Configuration;
    
                return configuration.FilePressMonitors;
            }
    
            /// <summary>
            /// Array of FilePressMonitor entries
            /// </summary>
            [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
            [XmlElement(ElementName = "filePressMonitor")]
            public FilePressMonitor[] Monitors
            {
                get
                {
                    return _filePressMonitorList.ToArray();
                }
                set
                {
                    if (null == _filePressMonitorList) { _filePressMonitorList = new List<FilePressMonitor>(); }
                    if (value == null) { return; }
    
                    _filePressMonitorList.AddRange(value);
                }
            }
    
            private List<FilePressMonitor> _filePressMonitorList = new List<FilePressMonitor>();
        }
    
        /// <summary>
        /// Represents filePressMonitor entries under the filePressMonitors node
        /// </summary>
        [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix"), XmlType(AnonymousType = true)]
        public class FilePressMonitor
        {
            /// <summary>
            /// Friendly monitor name
            /// </summary>
            [XmlAttribute(AttributeName = "name")]
            public string Name { get; set; }
    
            /// <summary>
            /// Press guid
            /// </summary>
            [XmlAttribute(AttributeName = "pressKey")]
            public Guid PressKey { get; set; }
    
            /// <summary>
            /// Unc or local path of folder to be monitored
            /// </summary>
            [XmlAttribute(AttributeName = "folder")]
            public string Folder { get; set; }
    
            /// <summary>
            /// Specifies whether the entry should be monitored
            /// </summary>
            [XmlAttribute(AttributeName = "enabled")]
            public bool IsEnabled { get; set; }
        }
    }
    Finally you use call the Read() method to get the list of monitors (File Watcher creation removed for clarity):
    Code:
    foreach (var filePressMonitor in FilePressMonitors.Read())
    {
      // use the monitor variables here to create multiple file watcher objects.
    }

  4. #4
    Join Date
    Jul 2003
    Location
    PA
    Posts
    124

    Re: Basics on C# Global Variable

    Thanks for the feedback, but I am looking for a little of both options here. I need to set those variables that are static to the user/machine it is loaded on. And also on seldom changing or very slow moving variables that need to be retained session to session.

    The majority of these values will be set when the app is installed so the app.config.file while a nice feature, will not work in my case. The settings options appear to be the best option for my usage.
    There are 10 types of people in the world, those that understand binary and those that don't.
    Using VS 2010

  5. #5
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Basics on C# Global Variable

    Quote Originally Posted by rick7423 View Post
    The majority of these values will be set when the app is installed so the app.config.file while a nice feature, will not work in my case.
    I'm not trying to defend my suggestion, but there is nothing that prevents you from doing a one-time modification of the app.config during setup.

    The bottom line is any read-only values can be stored in app.config, but any settings that ever get written to should be stored elsewhere.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured