Blog Archives

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.

Add EULA to ClickOnce Installation using Visual Studio 2015


ClickOnce technology is very smart and useful when you want simple, small and smart piece of software for deploying your Windows Forms or WFP application. This is specially useful if you deliver application which doesn’t require administrator rights during installation. ClickOnce is very powerful if you wants automatic update of your product, you can decide whenever the update appears before or after app is run. Also by using certificate you can deliver reliable and secure product to your customers. Long time ago I wrote detailed blog post  how to make ClickOnce deployment.

But one big thing is missing in ClickOnce deployment and for most of dev community is the feature which should be included by default. The feature which missing is “End User License Agreement” (EULA).  There is no simple way to implement it. Searching the internet I have found one forum post on Microsoft site describing how to implement it. Only way you can get ELUA at the beginning of the ClickOnce installation proces is by using it as prererquested component. Actually you build a redistributable component which would be seen as prerequsites dialog box under the publish window. To build custom prerequisites component you need a three files:

  1. Product.xml. – which is the file for bootstrapper and Visual Studio to show  a component in prerequisites dialog,
  2. Package.xml – which is the file containing all information about the component to be installed,
  3. EULA.txt – your ELUA text for user to accept.

Those three files must be installed in the location where all components are registered: C:\Program Files (x86)\Microsoft Visual Studio 14.0\SDK\Bootstrapper\Packages

For this blog post I have prepare demo sample which look like the following picture:

clickoncelicsl015

As can be seen, there is a two folders and one xml file. Each folder contains two files described earlier. Folders “en” and “de” means we are going to have EULA translated on two languages.

In order to successfully registered perquisites to be visible by Visual Studio we need to define proper content of the product.xml. The following xml code show content of our demo sample:

<?xml version="1.0" encoding="utf-8" ?>

<Product xmlns="http://schemas.microsoft.com/developer/2004/01/bootstrapper" ProductCode="EULA.Bootstrap.Component">
  <!-- Defines list of files to be copied on build -->
  <PackageFiles>
    <PackageFile Name="en/eula.txt"/>
  </PackageFiles>
  <Commands>
    <!-- Open eula.txt without any parameters -->
    <Command PackageFile="en/eula.txt" Arguments='' >
	
	  <!-- These checks determine whether the package is to be installed -->
	  <!-- No install conditions -->
      <InstallConditions>
        
      </InstallConditions>
	  
	   <!-- Exit codes -->
	   <ExitCodes>
        <ExitCode Value="0" Result="Success" />
        <DefaultExitCode Result="Fail" FormatMessageFromSystem="false" String="GeneralFailure" />
      </ExitCodes>

    </Command>
  </Commands>
</Product>

As we can see xml content is self-described, it contains product information, files to be installed, installation conditions and exit codes.

Each folder (en, de, …) contains package.xml file which holds localized messages and list of files to copied on build. The following xml content shows content of our en demo sample:

<?xml version="1.0" encoding="utf-8" ?>
<Package xmlns="http://schemas.microsoft.com/developer/2004/01/bootstrapper" Name="ClickOnceWithLicenseAgreement" Culture="Culture" LicenseAgreement="eula.txt">
  <!-- Defines list of files to be copied on build -->
    <PackageFiles>
        <PackageFile Name="eula.txt"/>
    </PackageFiles>

  <!-- Defines a localizable string table for error messages and url's -->
  <Strings>
    <String Name="DisplayName">ClickOnceWithLicenseAgreement 1.0 (x86 and x64)</String>
    <String Name="Culture">en</String>

    <String Name="CancelFailure">User Refuse to Accept to ClickOnceWithLicenseAgreement End User License Agreement.</String>
    <String Name="GeneralFailure">A fatal error occurred during the installation of ELUA Component Execution</String>
    <String Name="AdminRequired">You do not have the permissions required to install this application.  Please contact your administrator.</String>
  </Strings>    
</Package>

The EULA.txt file contains the text user need to accept in order to install the product.

For this demo we created folder EULAPackage, put product.xml and two folders en and de because we are going to support two installation languages (see picture above).

Copy the EULAPackage folder in to : C:\Program Files (x86)\Microsoft Visual Studio 14.0\SDK\Bootstrapper\Packages

Now we have set all necessary information about ELUA component and can be included in our demo sample.

  1. Open Visual Studio 2015 and create new WFP application.Name it as “ClickOnceWithLicenseAgreement

clickoncelicsl011

2. Right-Click on the Project and select Property menu option, then select Publish tab item of the Project Property window.

clickoncelicsl016

3. Click on Prerequisites Button, then you will see your prerequisite component in the standard prerequisites lists.

clickoncelicsl013

4. Select ClickOnceWithLicenseAgreement component and click Ok button. Afterwards click Publish button to build installation package.

5. Open publish folder from the disk. DoubleClick Setup.exe and the ELUA window should be appeared:

clickoncelicsl014

6. Now user has two choises to accept or Refuse the EULA, which means install or not install the app.

Prerequested demo sample component for EULA can be downloaded from here.

Happy programming.

 

How to convert your old sequential code in to async


There are plenty of ansyc samples over the internet, and most of them are different and not satisfy your requirements. Actually, async pattern depends of its creator, and can be implement on various ways. It is important to understand the async pattern in order to use it. Only on this way, you can stop searching for exact sample you need, and start coding your own async code.  More that year ago, I wrote simple blog post about async pattern (part 1 and part 2) (Bosnian language), and also wrote how to call Entity Framework with async pattern as well.

Today I am going to show you how old synchronous code block convert in to asynchronous. I think it is interesting because async pattern can improve your existing applications on various ways. First of all async pattern can increase responsiveness of  an application, performance, etc.

First of all, create simple Windows Forms sample and implement synchronous code.This will represent our old application, in which we are going to implement new programming paradigm.

1. Create Windows Forms Project, Name it “WinFormsAsyncSample

2. Design your main form (Form1.cs) exactly as picture shows below, and implement events.

As picture shows we have few labels, one text box, one progress bars, and two buttons.

Note: At the end of the blog you can download both versions (nonasync and async) of this sample.

The sample application calculates how many prime numbers exist in range. You need to enter number, press run button. The program starts counting. The progress bars informs user status of counting.

Lets see the implementation of runBtn_Click event:

private void btnRun_Click(object sender, EventArgs e)
{
    if(!int.TryParse(textBox1.Text,out m_number))
        m_number= 1000000;

    textBox1.Text = m_number.ToString();
    progressBar1.Maximum = m_number;
    progressBar1.Minimum = 0;
    progressBar1.Value = 0;

    //call start calculation
    startCounting();
}

At the beginning of the btnRun_Click we prepare progressBar, and also convert text from textbox in to int type.At the end of the function startConting method is called. Here is the source code of the method:

private void startCounting()
{
    int counter=0;
    for(int i=2;i<m_number; i++)
    {
        bool retVal= IsPrime(i);
        progressBar1.Value++;
        if (retVal)
        {
            counter++;
            label3.Text = "Result is: " + counter.ToString();
        }
    }
}

The method is very simple. It iterates from 2 to specified number by calling helper method IsPrime (see source code of the blog post) to check if certain number is prime. Then the method increased the counter variable and tried to update label about current count value.  If  you run the sample and press run button, you can see that the application is not responsive on user input, and represent classic sequential, synchronous single thread application.

Now I am going to show how this implementation can be converted in to async with minimum code changes.We are going to change only startCounting method, other code will remain the same. Explanation is divided in only 3 steps, which is enough to convert our code in to full async pattern.

  • Put async keyword right after public modifier of startCounting method.

Explanation: Every method which implements async patter needs to be decorated with async.

  • Put sequential implementation in to Task action, and wait.

Explanation: With this, you define a Task object which will run the code without blocking main thread. The simplest implementation is the following:

private async void startCalculation()
{
    var task = new Task(() =>
        {
            int counter = 0;
            for (int i = 2; i < m_number; i++)             {                 bool retVal = IsPrime(i);                 this.Invoke((Action)(()=>
                {
                    progressBar1.Value++;
                    if (retVal)
                    {
                        counter++;
                        label3.Text = "Result is: " + counter.ToString();
                    }

                }));
            }
        });

    task.Start();
    await task;
}

Now if you run the sample, you have fully asynchronous implementation. Main thread is free and can receive user input. So this is the simplest way how to convert your sync code in to async. This is the case when Task object create another thread in order to execute the code. That’s why we called this.Invoke method in order to set controls properties progressBar.Value and label3.Text. Everything else remain the same as in previous implementation.

  • Create global variable of type CancellationTokenSource and call Cancel method from Cancel Event handler.

Explanation: On this way we can cancel counting at any time.With this case we need to implements extra code in our previous implementation like the following.

private async void RunProces()
{
    if (m_IsRunning)
        return;
    m_IsRunning = true;
    int counter=0;
    if (m_ct != null)
    {
        m_ct.Dispose();
        m_ct = null;
    }
    m_ct = new CancellationTokenSource();

    var task = new Task(() =>
        {
            for (int i = 0; i < m_number; i++)             {                 bool retVal = IsPrime(i);                 this.Invoke((Action)(()=>
                {
                    progressBar1.Value++;
                    if (retVal)
                    {
                        counter++;
                        label3.Text = "Result is: " + counter.ToString();
                    }

                }));

                if (m_ct.IsCancellationRequested)
                {
                    m_IsRunning = false;
                    return;
                }
            }
        }, m_ct.Token);

    task.Start();
    await task;
}

With the last code implementation you have full of async patter in yur old application.

In this blog post I have tried to explain as simple as possible the way how you can convert you old sync code in to new async programming pattern.

Source code sample used in this blog post:

On this link you can find sequential version of the sample.

On this link you can find the final solution of async pattern.


			

Developing Windows Store App Part 1: Database Model


This is the first of several blog posts about developing Windows 8 Store app. The first blog post will show how to implement database model which will be used in our application. If you want to get more information about the application we are developing please see the previous announcment post. Before we start with the tutorial, several requirements must be satisfied:

1. You need to have installed at least Visual Studio 2012 Express

2. You need to have at least SQL Server 2008 or 2012 Express.

Our database model is very simple. We have three tables: Places, Dishes and Towns. Relation of those tables shows the picture below.

SQL database will also be provided by the end of the blog post. Now that we have database model on the paper, we can start with implementation. We will use Entity Framework 5, and Code First technology in order to implement db model.
Start Visual Studio 2012, choose File->New->Project. Choose ClassLibrary similar as picture below.

After we created the empty Class Library project, we can start with implementation of the entities. According to db model shoed earlier, we are going to create three .NET classes: Dish, Town, Place. In order to do that:

  • Right Click at the Project
  • Add New Class
  • Give name: Dish

Repeat the process for Town and Place. Text below shows the implementation of classes.
Town class:

public partial class Town
{
public int? TownID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Image { get; set; }
//relation 0-oo
//many places can be in one Town
public ICollection Places { get; set; }
}

Dish class:

public partial class Dish
{
    public int? DishID { get; set; }
    public string Name { get; set; }
    public string Slogan { get; set; }
    public string Description { get; set; }
    public string Image { get; set; }
    //relation 0-oo
    //many places can have one dish
    public ICollection<Place> Places { get; set; }
}

Place class:

public partial class Place
{
    public int? PlaceID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int? DishID { get; set; }
    public string Slogan { get; set; }
    public string Type { get; set; }
    public int? TownID { get; set; }
    public string Image { get; set; }
    //one relation to Dish
    public Dish PlaceDish { get; set; }
    //one relation to Dish
    public Town PlaceTown { get; set; }
}

Since we are using Code First, we need to specify the relation between entities too. That’s why we have put the last two properties in Place class, and also IColletion property of the previos classes. This is enough information that Code First make relation between tables on SQL Server.  By default PlaceID is primary key for Place table, as well as DishId and TownID for corresponded tables.
Now that we have entities, we need to implement DBContex, central class for handling all operation and transaction against database. Before we implement DBContext we need to add Entity Framework reference. Since EF is separated from the .NET we can use NuGet to accomplish this.
1. Right click on Reference, choose Manage NuGet package

In Search box type: Entity Framework and hit enter. Package will appear in the list. Click Install button. Picture below shows Manage NuGet Package dialog. Accept license agreement, and close the dialog.

CExplorer DataContext class:

public class CExplorerContext: DbContext
{
    public CExplorerContext() : base("cexplorer_db")
    {
        Configuration.LazyLoadingEnabled = false;
    }

    //entity sets
    public DbSet<Place> Places { get; set; }
    public DbSet<Dish>  Dishes  { get; set; }
    public DbSet<Town>  Towns  { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //crating one to many relation between Town and Place
        modelBuilder.Entity<Place>()
            .HasRequired(x => x.PlaceTown)
            .WithMany(d => d.Places)
            .WillCascadeOnDelete(true);

        ////crating one to many relation between Dish and Place
        modelBuilder.Entity<Place>()
            .HasRequired(x => x.PlaceDish)
            .WithMany(d=>d.Places)
            .WillCascadeOnDelete(true);

        base.OnModelCreating(modelBuilder);
    }
}

As you can see, we have overridden ModelCreation virtual method and implement relation between entities. This is classic one to many relation.

At the end of the implementation, we need to provide connection string to SQL Server, it must be with the same name as we specified in the implementation od the DBContext.

1. Add New Item: App.config file and put the following configuration.

Based on SQL instance name, change the connection string. Database could not exist on the SQL server. If there is a database on the SQL with the same name, EF will add table in to existing database.

Before we end the today’s post, lets quickly create Console Test application to make sure we implemented correct model.

1. File->New->Add New Project
2. Console Application

Like previous add Entity Framework by NuGet.
Add reference of EFModel.
Open Program.cs and put the following implementation:

class Program
{
    static void Main(string[] args)
    {

        CExplorerContext ctx = new CExplorerContext();

        var dish = new Dish() { DishID = 1, Description = "Description", Name = "DishName", Slogan = "Slogan", Image = "Default.jpg" };
        var town= new Town(){TownID=1, Name= "TownName", Description="Description", Image=""};
        ctx.Dishes.Add(dish);
        ctx.Towns.Add(town);
        ctx.SaveChanges();
        var place = new Place() { PlaceID = 1, Name = "Place Name", Description = "DEscription", Image = "default.jpg", Slogan = "Slogan title", DishID = 1, TownID = 1 };
        ctx.Places.Add(place);
        ctx.SaveChanges();

        var plc = ctx.Places.FirstOrDefault();
        Console.WriteLine("Place from Database");
        Console.WriteLine("Place from database Name:{0}", plc.Name);
        Console.Read();

    }
}

After we run, output console shows that the entities are inserted successively on database.

In other words Cexplorer_DB database is created on the SQL server, and entities are inserted from the test.

Code First approach is very powerful, we only need to specified connection string, and everything is created just like we do, in Model First approach.  Complete source code for this Demo can be found here.