Handling with Connection String at Run-Time in developing desktop applications


Almost every desktop application deals with some kind of external memory to save data for further use. The most part of them, use a database. On the other hand an Application needs connection string to connect to the database, for handling its memory. So, how to use connection string and how to manipulate with it, that’s the question which this post wants to answer.

If we want to change the connection string during the application run-time, it is not a simple task, because the connection string is placed in to an application scope that is read only.

The reason why we need to change the connection string is the different settings and environment between users, as well as different environment between developer and end-user. So when we are planning application deployment we must have that in mind, and  provide the implementation custom modification of the connection string.

clip_image002

If we look files of an Application (for example on the picture above) we can see two exe file, and two corresponding configuration files. This is the .NET rule, that every exe file may have only one configuration file.

The structure of configuration file

clip_image004

The picture above shows content of the configuration file and the connection string data. .NET Application can access this data with the API placed in to System.Configuration namespace, by using specific XML schema developed by Microsoft for that purpose.

To access NorthwindConncetionString from the configuration file we can achieve that with the following code:

//Read connection string from configuration file
var connStringFromConfig = System.Configuration.ConfigurationManager.
ConnectionStrings["ConnStringDemo1.Properties.Settings.NorthwindConnectionString"];

If we want to change connection string, exception will throw with the following message:

clip_image005

So the question is how to change connection string anyway?

To change connection string we need to open configuration file with XML API functions, find the connection string and change the data manually then save changes back to file then restart the application. This is in short how to do that, the following code do exactly what we said before:

private bool ChangeConnectionString(string connStringName, string newValue)
{
 try
 {
 //CreateXDocument and load configuration file
 XDocument doc = XDocument.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

 //Find all connection strings
 var query1 = from p in doc.Descendants("connectionStrings").Descendants()
 select p;

 //Go throught each connection string elements find atribute specified by argument and replace its value with newVAlue
 foreach (var child in query1)
 {
 foreach (var atr in child.Attributes())
 {
 if (atr.Name.LocalName == "name" && atr.Value==connStringName)
 if (atr.NextAttribute != null && atr.NextAttribute.Name == "connectionString")
 atr.NextAttribute.Value = newValue;
 }
 }

 doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

 return true;
 }
 catch (Exception ex)
 {
 Console.WriteLine(ex.Message);
 return false;
 }
}

Change connection string for Entity Framework at run-time

As you already know the connection string for Entity Framework is little bit different than the connection string used by DataSet and Lin2SQL. In order to modify the Entity framework connection string the previous code must be modified. The following code modified the entity framework connection string.

private bool ChangeEFConnectionString(string connStringName, string newValue)
{
try
{
//CreateXDocument and load configuration file
XDocument doc = XDocument.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

//Find all connection strings
var query1 = from p in doc.Descendants("connectionStrings").Descendants()
select p;

//Go through each connection string elements find atribute specified by argument and replace its value with newVAlue
foreach (var child in query1)
{
foreach (var atr in child.Attributes())
{
if (atr.Name.LocalName == "name" && atr.Value == connStringName)
if (atr.NextAttribute != null && atr.NextAttribute.Name == "connectionString")
{
// Create the EF connection string from existing
EntityConnectionStringBuilder entityBuilder =
new EntityConnectionStringBuilder(atr.NextAttribute.Value);
//
entityBuilder.ProviderConnectionString= newValue;
//back the modified connection string to the configuration file
atr.NextAttribute.Value = entityBuilder.ToString();
}
}
}

doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}

In the previous code we used the EntityConnectionStringBuilder which is very handy in this situation.

The source code for this post you can find on SkyDrive.

Advertisement

Master-details with Entity Framework in WPF by using MVVM pattern


In this short blog post we will present how to implement WPF application with Master-detail relation in Entity Framework by using MVVM pattern. We will start with creating the new Visual Studio 2010 WPF Application project, and add reference to MVVM Light Toolkit library, which you can find on http://mvvmlight.codeplex.com/.  The picture below shows the starting WPF project:

Now that we have starting project, we can add the new ADO.NET Entity Framework model with NorthWind SQL database. Map the only two tables Order and OrderDetails, after that we have the following situation. If you not familiar with this procedure, more details you can find on my previous post.

The next step in implementation will be creating the ModelView of the MainWindow. The ModelView will contain implementation of all logic of the Master-detail relation. To do that point with right-click on the project, select Add-Class of the context menu item and enter the name MainWindowViewModel. If you have full instatlation of the MVVM Light Toolkit you can use MVVM template specialized for creating ModelView class.

After we create file of the MainWindowViewModel, we have to implement class and add two properties MasterCollection, and DetailsCollection.

The Next source code listing shows implementation of the MainWindowViewModel. This is minimal code for work with master – details in Entity Framework.

using GalaSoft.MvvmLight;
using System.Windows.Data;

namespace WPF_EF_MasterDetailsDemo
{
   public class MainWindowViewModel:ViewModelBase
   {
      NorthwindEntities ctx = new NorthwindEntities();
      public MainWindowViewModel()
     {

     }
     private CollectionViewSource _entityMasterView;
     public CollectionViewSource EntityMasterView
     {
       get
       {
        if (_entityMasterView == null)
          GetMasterEntityCollection();
        return _entityMasterView;
       }
    }
    public CollectionViewSource _entityDetailsView;
    public CollectionViewSource EntityDetailsView
    {
     get
     {
      if (_entityDetailsView == null)
           GetMasterEntityCollection();
       return _entityDetailsView;
     }
   }
   private void GetMasterEntityCollection()
   {
       _entityDetailsView = new CollectionViewSource();
       _entityMasterView = new CollectionViewSource();
       _entityMasterView.Source = ctx.Orders;
       _entityMasterView.View.CurrentChanged += (x, y) =>
         {
           _entityDetailsView.Source =((Orders)_entityMasterView.View.CurrentItem).Order_Details;
         };
       _entityMasterView.View.Refresh();
   }
   }
}

After we implemented ViewModel, we have to put some GUI stuff on the MainWindow.xaml, so open the MainWindow.xaml, put two labels and two DataGrid controls in to Main Window. This looks line on the following picture:

The sample is so short that it can fit in to single image ;).

In the code-behind constructor create MainWindowViewModel and assign to Windows DataContext, and that’s it.

This post demonstrate one posible  implementation of the Master-detail relation in EF by using the MVVM pattern. The source code of this project you can find on SkyDrive.

Windows 8 i System on a Chip (SoC) tehnologija


Na najvećem sajmu potrošačke elektronike i inovacija CES koji se održava od 6-9. januara u Las Vegasu u USA, Steve Ballmer šef Microsofta pored zanimljivih stvari oko Windows Phone 7, igraće konzole Xbox 360 i KINECT, kao šlag na tortu najavio je novu verziju Windowsa 8 i prezentirao neke novine koje dolaze s njim.

Naime, u saradnji sa proizvođačima hardvera prikazan je set novih uređaja koji imaju svojstvo System on Chip (SoC), a što će podržavati nova verzija Windows 8.

System on Chip (Soc) kao pojam označava integraciju svih komponenata u jedan čip preko kojeg se mogu obrađivati kako digitalni tako i analogni signali. Tipična primjena ovakvih uređaja su embeded sistemi. S druge strane System on Chip predstavljaju uređaje koji su dizajnirani za mobitele i tablet računare. Ovo svojstvo omogućava istim uređajima dramatično povećanje vijeka trajanja baterije, odnosno smanjenje energije koje je potrebno imati za njihov rad.

SoC predstavljaju ARM bazirane sisteme koje razvijaju microsoftovi partneri NVIDIA Corp., Qualcomm Inc. i Texas Instruments Inc. Tehnologiju koja je demonstrirana na razlčitim uređajima sastojala se od hardverskog ubrzanja grafike i media playbacka, kao i uređaje na kojima je demonstriran rad Office 2010 programa u prirodnom obliku, demonstrirajući printanje dokumenta iz MS Worda. Pogledajte video ove vrlo interesantne prezentacije SoC tehnologije i Windows 8 OS-a.