none
reading/saving properties .net Core RRS feed

  • Question

  • Hi,

    I am trying to convert a .net 4.8 winforms application to .net core. The only thing that seems to be different is how settings are used. I used to read settings like this:

    this.ActivateLogging = Properties.Settings.Default.LoggingActivate;


    and save them like this:

    Properties.Settings.Default.LoggingActivate = this.ActivateLogging;

    With .net Core this is not possible anymore. I googled for it but didn't find anything for winforms. How can i save and load settings wit .net Core?

    Greetings Hans

    Friday, March 6, 2020 8:12 AM

Answers

All replies

  • Hi HansvB69,

    You can use Settings file in .Net Core as an old version

    Add Settings.settings file in.NET Core windows from


    Please remember to mark the replies as answers if they helped you :) ~


    Friday, March 6, 2020 9:02 AM
  • Hello friend

    0- Properties.Settings.Default.Save();

    1-Actualy this.ActivateLogging -> what is the type of this field .

    2- what is the type of Properties.Settings.Default.LoggingActivate  if define.

    3-Look url for assign of properties

    https://codedocu.com/Net-Framework/WinForms/Code/C_hash_,-WinForms_colon_-Save-and-read-settings?1936


    Friday, March 6, 2020 10:38 AM
  • While you can use the old-style settings stuff in Core there really isn't a good reason to do so except for backwards compatibility or temporarily while you're updating all your code. So I would see this as a short term solution.

    The reason this functionality was added was to give you compile time support for settings with optional defaults. Core supports this as well via the IOptions functionality. I cannot say that I'm exactly impressed with how this implementation works but it does provide the same general set of functionality.

    You'll create a separate type for each related group of settings (or you could create 1 monolothic type if you wanted). The type can have simple properties (with defaults) and/or nested types. At runtime you can have an instance created and populated from the config sources you've defined. For Core the config sources can be configured to include the appsettings.json file, memory, env vars, etc. In ASP.NET apps this is done automatically. In a Winforms app you probably have to do this yourself at app startup.

    If you're also using DI then you can register the options with DI so they can be injected as well. If you want to support the existing XML config files for a while you can add your custom configuration source to read the "old" config files to load settings from a previous version of your app.

    //Not tested
    public class MyOptions 
    {
       public string Setting1 { get; set; }
       public int Setting2 { get; set; } = 20;
    }
    
    //When using with DI 
    public class SomeService
    {
       //This is the documented way but most people don't like it
       public SomeService ( IOptions<MyOptions> options )
       {
       }
    
       //This is the way most ppl want to go but requires extra configuration at startup
       public SomeService ( MyOptions options )
       {
       }
    }
    
    //Configuration for DI, if you're using it and want to be able to pass just the type
    var options = new MyOptions();
    services.Configure<MyOptions>(options => Configuration.GetSection("MyOptions").Bind(options));
    services.AddSingleton(options);

    There are a couple of downsides to the current implementation to be aware of.

    1) You don't really have design time/run time consistency. It is quite possible to define a property in your type and it not actually exist at runtime in a config source. That is why the default value is important.

    2) The options infrastructure is overly complex with IOptions<T>, IOptionsMonitor<T>, etc. If you just want to be able to dynamically load a settings type then stick with the type, configure the DI container to return an instance of that type by reading it from the options subsystem directly and forgo IOptions<T> and friends.

    3) AFAIK there isn't any infrastructure in place to actually save options. The infrastructure supports refreshing when a change occurs but not making the change itself. You'll have to implement this outside the provided infrastructure but it shouldn't be too hard.


    Michael Taylor http://www.michaeltaylorp3.net

    Friday, March 6, 2020 2:37 PM
    Moderator
  • With .net Core this is not possible anymore. I googled for it but didn't find anything for winforms. How can i save and load settings wit .net Core?

    You would have to use an appsettings.json file. The appsettings.json file will need to be at  the location of the exe file.

    https://www.adamrussell.com/appsettings-json-in-a-net-core-console-application/

    https://stackoverflow.com/questions/41653688/asp-net-core-appsettings-json-update-in-code

    You have to come up with your own code.

    In ASP.NET Core MVC project,  the Startup.cs is part of the project template called by the Program.cs, and I just duplicated  a StartUp.cs called by Program.cs in Win Core 3.0 program.    the other code you see in Program.cs is for global exception handling.

     

    using System;
    using System.Windows.Forms;
    
    namespace PubCompanyWinCore
    {
        static class Program
        {
            /// <summary>
            ///  The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                // Add handler to handle the exception raised by main threads
                Application.ThreadException +=
                    new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
    
                // Add handler to handle the exception raised by additional threads
                AppDomain.CurrentDomain.UnhandledException +=
                    new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
    
                new Startup();
    
                // Stop the application and all the threads in suspended state.
                Environment.Exit(-1);
            }
            static void Application_ThreadException
                (object sender, System.Threading.ThreadExceptionEventArgs e)
            {
                // All exceptions thrown by the main thread are handled over this method
    
                ShowExceptionDetails(e.Exception);
            }
    
            static void CurrentDomain_UnhandledException
                (object sender, UnhandledExceptionEventArgs e)
            {
                // All exceptions thrown by additional threads are handled in this method
    
                ShowExceptionDetails(e.ExceptionObject as Exception);
            }
    
            static void ShowExceptionDetails(Exception Ex)
            {
                // Do logging of exception details
                MessageBox.Show(Ex.Message, Ex.TargetSite.ToString(),
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
    
                // Stop the application and all the threads in suspended state.
                Environment.Exit(-1);
            }
        }
    }
    
    
    
    using System.IO;
    using System.Windows.Forms;
    using Microsoft.Extensions.DependencyInjection;
    using BLL;
    using DAL;
    using DAL.Models;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Configuration;
    
    namespace PubCompanyWinCore
    {
        public class Startup
        {
          public Startup()
          {
                var serviceCollection = new ServiceCollection();
    
                ConfigureServices(serviceCollection, new DbContextOptionsBuilder());
    
                var _serviceProvider = serviceCollection.BuildServiceProvider();
                
                Application.SetHighDpiMode(HighDpiMode.SystemAware);
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
    
                MainView view = _serviceProvider.GetService<MainView>();
                
                Application.Run(view);
          }
           
          private void ConfigureServices(IServiceCollection services, DbContextOptionsBuilder optionsBuilder)
          {
                var builder = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())  //location of the exe file
                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
    
                IConfigurationRoot configuration = builder.Build();
    
                var connectionstring = configuration.GetConnectionString("DefaultConnection");
    
                //BLL
                services.AddTransient<IPayRollDM, PayRollDM>();
                services.AddTransient<IAuthorDM, AuthorDM>();
    
                //DAL
                services.AddTransient<IDaoAuthor, DaoAuthor>();
                services.AddTransient<IDaoPayroll, DaoPayroll>();
                services.AddTransient<IDaoArticle, DaoArticle>();
                services.AddDbContext<PublishingCompanyContext>(options => options.UseSqlServer(connectionstring));
    
                //Presentation
                services.AddSingleton<MainView>();
                services.AddSingleton<PayRollView>();
                services.AddSingleton<AuthorView>();
          }  
        }
    }
    


    Saturday, March 7, 2020 1:12 AM
  • Hi,

    I go for the first reply, otherwise i have to take a lot of dll files for a simple configuration file.

    Thanks.

    Saturday, March 7, 2020 8:49 AM
  • Hi,

    I go for the first reply, otherwise i have to take a lot of dll files for a simple configuration file.

    Thanks.

    You have a lot of DLL(s) in the project to begin with normally, and I don't see that as being a problem. 
    Saturday, March 7, 2020 11:05 AM
  • Hi,

    I changed it. I now use newtonsoft.json and write my own json file for the settings. (I know, 1 extra dll file).

    Greetings, Hans

    Sunday, March 8, 2020 6:05 PM