Category Archives: CodeProject

Using external config files in .NET applications


The config file is place where common variables, database connection strings, web page settings and other common stuff are placed. The config file is also dynamic, so you can change the value of the variable in the config file  without compiling and deploying the .NET app. In multi tenancy environment config file can be complicate for deployment, because  for each tenant different value must be set for most of the defined variables. In such a situation you have to be careful to set right value for the right tenant.

One way of handling this is to hold separate config file for each tenant. But the problem can be variables which are the same for all tenants, and also the case where some variables can be omitted for certain tenant.

One of the solution for this can be defining external config files for only connection strings or appSettings variables, or any other custom config section. In this blog post, it will be presenting how to define connection strings as well as appSettings section in separate config file.

Lets say you have appSettings and connectionStrings config sections, similar like code below:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>

	<connectionStrings>
		<add name="SQLConnectionString01" connectionString="Data Source=sourcename01;Initial Catalog=cat01;Persist Security Info=True;Integrated Security=true;"/>
		<add name="SQLConnectionString02" connectionString="Data Source=sourcename02;Initial Catalog=cat02;Persist Security Info=True;Integrated Security=true;"/>
	</connectionStrings>

	<appSettings>
		<clear />
		<!-- Here are list of appsettings -->
		<add key="Var1" value="Var1 value from config01" />
		<add key="Var2" value="Varn value from config01"/>
		<add key="Var3" value="Var3 value from main config file"/>
	</appSettings>

</configuration>

There are three appSetting keys Var1 , Var2 and Var3  and two connectionstrings in the app.config.

The config file above can be split in such a way that variables Var1 and Var2 be defined in separated file, but the Var3 can be remain in the main cofing file. Separate config file may be unique for each tenant.

Now the main config file looks like the following:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>

	<connectionStrings configSource="config\connString01.config"/>

	<appSettings file="config\config01.config">
		
		<add key="Var3" value="Var3 value from main config file"/>
	</appSettings>

</configuration>

In the Visual Studio Solution there is config folder in which we created two config files for appSettings section and two config files for Connectionstrings section, in case we have two separate environments for deployments.

exconfigfile01
The flowing code snippet shows the appSettings section implemented in the external file:

<appSettings file="appSettings.config">

	<!-- Here are list of appsettings -->
	<add key="Var1" value="Var1 value from config02" />
	<!-- ... -->
	<add key="Varn" value="Varn value from config02"/>
</appSettings>

The external config file for connection strings looks similar like the flowing:

exconfigfile02

The simple console application shows how to use this config variables in the code:

static void Main(string[] args)
{
    var var1Value= ConfigurationManager.AppSettings["Var1"];
    var var2Value = ConfigurationManager.AppSettings["Var2"];
    var var3Value = ConfigurationManager.AppSettings["Var3"];
    var conn1 = ConfigurationManager.ConnectionStrings["SQLConnectionString01"];
    var conn2 = ConfigurationManager.ConnectionStrings["SQLConnectionString02"];

    Console.WriteLine("Values from config01.config and connString01.config files");

    Console.WriteLine("Var1={0}",var1Value);
    Console.WriteLine("Var2={0}", var2Value);
    Console.WriteLine("Var3={0}", var3Value);
    Console.WriteLine("ConnStr01={0}", conn1);
    Console.WriteLine("ConnStr01={0}", conn2);

    Console.Read();
}

The complete source code can be downloaded from this link.

New Features in C# 6.0 – Primary Constructors


Update: This feature is removed from the C# 6.0 specification, probably for the next version of C#.
Primary constructors reduced declaration of various constructors with different arguments. Primary constructors is declare on the type declaration and this is why it so special. For example:


public class Person (string defaultName)
{
 private string m_Name=defaultName;
 public string Name {get;set;}
 public Person()
 {
   Name=defaultName;
 }

}

We can define Primary Constructor in combination on Auto-Property Initializer on the following way:

public class Person (string defaultName)
{
 private string m_Name=defaultName;
 public string Name {get;set;}=defaultName

}

How to run code daily at specific time in C# Part 2


dailyruncode

Few months ago I wrote blog post about how to run code daily at specific time. I dint know that the post will be the most viewed post on my blog. Also there were several questions how to implement complete example. So today I have decided to write another post, and extend my previous post in order to answer thise question as well as to generalize this subject in to cool demo called Scheduler DEMO.

The post is presenting simple Windows Forms application which calls a method for every minute, day, week, month or year. Also demo shows how to cancel the scheduler at any time.

The picture above shows simple Windows Forms application with two  numeric control which you can set starting hour and minute for the scheduler. Next there is a button Start to activate timer for running code, as well as Cancel button to cancel the scheduler. When the time is come application writes the message on the Scheduler Log.

Implementation of the scheduler

Scheduler is started by clicking the Start button which is implemented with the following code:

/// <summary>
/// Setting up time for running the code
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void startBtn_Click(object sender, EventArgs e)
{

    //retrieve hour and minute from the form
    int hour = (int)numHours.Value;
    int minutes = (int)numMins.Value;

    //create next date which we need in order to run the code
    var dateNow = DateTime.Now;
    var date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, hour, minutes, 0);

    listBox1.Items.Add("**********Scheduler has been started!*****");

    //get nex date the code need to run
    var nextDateValue=getNextDate(date,getScheduler());

    runCodeAt(nextDateValue, getScheduler());

}

When the time is defined then the runCodeAt method is called which implementation can be like the following;

/// <summary>
/// Determine the timeSpan Dalay must wait before run the code
/// </summary>
/// <param name="date"></param>
/// <param name="scheduler"></param>
private void runCodeAt(DateTime date,Scheduler scheduler )
{
    m_ctSource = new CancellationTokenSource();

    var dateNow = DateTime.Now;
    TimeSpan ts;
    if (date > dateNow)
        ts = date - dateNow;
    else
    {
        date = getNextDate(date, scheduler);
        ts = date - dateNow;
    }

    //enable the progressbar
    prepareControlForStart();

    //waits certan time and run the code, in meantime you can cancel the task at anty time
    Task.Delay(ts).ContinueWith((x) =>
        {
            //run the code at the time
                methodToCall(date);

                //setup call next day
                runCodeAt(getNextDate(date, scheduler), scheduler);

        },m_ctSource.Token);
}

The method above creates the cancelationToken needed for cancel the scheduler, calculate timeSpan – total waiting time, then when the time is come call the method methodToCall and calculate the next time for running the scheduler.

This demo also shows how to wait certain amount of time without blocking the UI thread.

The full demo code can be found on OneDrive.

New Features in C# 6.0 – Auto-Property Initializers


Initialize property is repetitive task, and cannot be done in the same line as we can can done for fields. For example we can write:


public class Person
{
 private string m_Name="Default Name";
 public string Name {get;set;}
 public Person()
 {
   Name=m_Name;
 }

}

As we can see Property can be initialized only in the constructor, beside the filed which can be initialized in the same line where it is declared. The new feature in C# 6.0 defines Auto-Property initializer alowing property to be initialized like fields. The following code snippet shows the Auto-Property Initializer;


public class Person
{
 static string m_Name="Default Name";
 static string Name {get;set;}=m_Name;
}
Follow

Get every new post delivered to your Inbox.

Join 672 other followers