XAML Peak new feature in Visual Studio 2015

The latest version of the Visual Studio 2015 is bringing a lot of new features for WPF and XAML programming language. For this blog post I would like to share the XAML Peak Definition. Peak Definition is not new, the current version of Visual Studio 2013 supports peak definition only for C# and VB. Now we have the same functionality within XAML. Event more, in the Visual Studio 2015 peak definition is working in mixed mode, so you can reach any definition regladless of the programming languges (C#, VB or XAML).

XAML peak allows you to get definition or content of any name defined in the XAML code. For example lets see the following XAML code. Right click on the MainWindow class and choose “Peak Definition”:


After the command is selected, the new inline window appears within xaml, and the user can easily see or change the code behind selected definition. Peak Definition works for any proper name in the XAML.


Lets see more interesting thing. Peak Definition is very handy when you want to see or modify the defined style or control template. For Example if we right click on the Style defined resource and choose Peak Definition like the following picture:


Inline window will appears and show the style implementation of the selected xaml element. This is very useful and long waited option of XAML editor:



Inline windows are edited windows so you can edit or add new code without leaving xaml editor.

This is one of the plenty of the new features coming with the latest version of the Visual Studio 2015. More features in the coming post.




How to extract default file icon in WPF application


In Windows every file has default icon, and it is shown in Windows Explorer while browsing files on disk. If you want to grab this icon in WPF application there are several ways. One of the solution is by using ExtractAssociatedIcon from Icon class located in System.Drawing namespace.

The following code shows how to extract default icon from the file specified by file name:

var sysicon = System.Drawing.Icon.ExtractAssociatedIcon(filePath);
var bmpSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(

Explanation of the code above is straightforward.First we need file path, then we need to call Icon.ExtractAssociatedIcon(filePath) to get Icon object. From the icon object we can create BitmapSource which can be show everywhere in the WPF application.


Complete source code demo can be found here.

Drag and Drop Item Outside WPF Application

In WFP applications drag and drop functionality is provided by subscribing several events. First of all you need LeftMouseButtonClick and MouseMove events in order to start Drag and Drop.

This is accomplished by the following code:

private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    this._startPoint = e.GetPosition(null);

private void Window_MouseMove(object sender, MouseEventArgs e)
    //drag is heppen
    //Prepare for Drag and Drop
    Point mpos = e.GetPosition(null);
    Vector diff = this._startPoint - mpos;

    if (e.LeftButton == MouseButtonState.Pressed &&
        (Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
        Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance))

        //hooking on Mouse Up
        InterceptMouse.m_hookID = InterceptMouse.SetHook(InterceptMouse.m_proc);

        //ataching the event for hadling drop
        this.QueryContinueDrag += queryhandler;
        //begin drag and drop
        DataObject dataObj = new DataObject(this.text1);
        DragDrop.DoDragDrop(this.text1, dataObj, DragDropEffects.Move);


As we can see from the code above, first with LeftMouseButtonClick event, we captured the starting point, then by MouseMove event, calculated distance between starting point and the current mouse position. If the distance is big enough we start DragDrop.

When the Drag starts it is necessary to prepare Drag functionality by providing the object to be dragged. In our case (code sample above) we are going to drag TextBox. In order to drag TextBox first we create DragData object by specifying TextBox object in the Constructor, and call DragDrop static method by passing objects we mentioned.
Beside preparing data to be dragged, we need to subscribe to QueryContinueDrag event in order to track dragging status.

This is all we need to prepare Drag and Drop in our application. If we want to drag object out of WPF aplication, we have no enough information to accomplish drop. As soon as the mouse is outside the app, mousemove event is not firing any more. One of the solution of the problem could be capturing the mouse move position outside the WFP application, and when the left mouse button is up, start with dropping item functionality.

In order to track mouse position outside the WPF application we need to hook and subscribe to the messages of whole Windows OS and filter only we are interesting in. Great blog post about how to capture  mouse messages regardless of the  mouse position can be found here.

Implementation of Low Level Mouse Hook in C# blog post can be modified quickly in order to adopt to our case.

First we need a property to indicate when the mouse is outside the application.

public static bool IsMouseOutsideApp 

Then we need to modify HookCallback method so that when the Left mouse button is up, and set the property (IsMouseOutsideApp ) to true if the mouse outside the application.

internal static IntPtr HookCallback( int nCode, IntPtr wParam, IntPtr lParam)
    if (nCode >= 0 && MouseMessages.WM_LBUTTONUP == (MouseMessages)wParam)
        MSLLHOOKSTRUCT hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));

        //check if POint in main window
        Point pt = new Point(hookStruct.pt.x, hookStruct.pt.y);
        var ptw = App.Current.MainWindow.PointFromScreen(pt);
        var w = App.Current.MainWindow.Width;
        var h = App.Current.MainWindow.Height;
        //if point is outside MainWindow
        if (ptw.X < 0 || ptw.Y < 0 || ptw.X > w || ptw.Y > h)
            IsMouseOutsideApp = true;
            IsMouseOutsideApp = false;
    return CallNextHookEx(m_hookID, nCode, wParam, lParam);

The Last thing we need to implement is DragSourceQueryContinueDrag event. The implementation is straightforward:
1. check the keystate value None – this is the case when the mouse is released.
2. unhook from the mouse intercepting messages
3. show the message text based on the result of drag and dropping.

/// <summary>
/// Continuosly tracking Dragging mouse position
/// </summary>
private void DragSourceQueryContinueDrag(object sender, QueryContinueDragEventArgs e)
    //when keystate is non, draop is heppen
    if (e.KeyStates == DragDropKeyStates.None)
        //unsubscribe event
        this.QueryContinueDrag -= queryhandler;
        e.Handled = true;
        //Unhooking on Mouse Up

        //notifiy user about drop result
            () =>;
                //Drop hepend outside Instantly app
                if (InterceptMouse.IsMouseOutsideApp)
                    MessageBox.Show("Dragged outside app");
                    MessageBox.Show("Dragged inside app");

Complete demo with source code can be found here:

CrossNumber- puzzle with numbers for WP7, Silverlight, Android and Win8 metro game

Recently I decided to start with implementation of my first game which is going to be CrossNumber  puzzle.


CrossNumbers is puzzle game which can be played from 7 year old children to mans in late year who like puzzle and math. The game is going to be for fun as well as for education propose which you can train your brain with math and problem solving. The game will be ported in Silverlight, WP7, Win8 Metro and Android.

Game contains originally designed problems which need to be solved in measured time, with penalty points for failed attempts. The game starts with simple cross number problems and rising its difficulties as you passing levels.

How to enter the number

clip_image004Each game needs input number provided by the player. The numbers are entered by special InputKeyboard showed on the left picture.

Before you input the number you need to select cell by clicking or taping grayed (hidden) cell. Picture left shows selected cell which holds sum of 2 and 6. By clicking on the clip_image005key you enter the correct value. If the value is incorrect the red rectangle will appear.

If you need to enter number greater than 9, you need to use combination of key clip_image006 and certain number.



Type of Games

Currently there are two kind of games (curreently on two variant are implemented in alpha version):

· HDV Sum

· Sum to 11


HDV Sum stands for Horizontal, Vertical and Diagonal summation. This is classic CrossNumber puzzle. The simple problem is depicted below:

Suppose we have 4×4 grid (yellow area), with random numbers in cells. Red bottom and right row/column hold sum of the yellow cell in Horizontal, Vertical and Diagonal (right and left) direction .


If we want to sumthe first yellow column the sum is equal to 7. On the same way we are having sums for the next 2 columns and they are 6 and 8 respectively.

Now we are going to sum in horizontal direction. So, for the first, second and third row we have 4,6 and 13 respectively.

Now remain part is diagonal summation from the top-left to the right-bottom corner and left-bottom to the right-top. The values are 12 and 7.

This type of game will have 3 different grids: 2×2, 3×3 and 4×4 grids.

Sum to 11

The next type game is Sum to 11. This is game which is real ultimate brain puzzle and is not easy as you may think.

The picture below shows the rules for this game. This is math intensive game and represents real challenge for players.


On the upper part there is a 4 of 4by4 grids, which are indexed for constructing the equations bellow. You need to follow equation below in order to solve puzzle successfully. This game will also have some variants probably for summation of 11, 21, 33 and 55.

The game is already in alpha stage of Silverlight and WP7 platform, and it is accessed by very limited number of people. But very soon it will be opened to all who is interesting in game.

Asynchronous Call of Entity Framework in C# 5.0

Since there is asynchronous pattern in C# 5.0 and .NET 4.5, we can think about how to apply this pattern in to EntityFramework. Natively EntityFramework doesn’t support of asynchronous calls, and you have to use classic DBReader to achieve it. In previous post about WCF and async and await keyword, we saw that asynchronous patter is already implemented when we add service in to client as Service Reference. Entity Framework probably will not have such an option, and you will have to deal with custom implementation.
If we look in to implementation of  DBReader and SqlReader in .NET 4.5 we can see that there is also async implementation as well. We don’t need to use begin/end execute reader ayn more. It is a good idea to try to implement similar pattern in Entity Framework.
So, first create a new project in Visual studio 11 DP, and create sample database, so we can test our async solution against EntityFramework.

  • Create new WPF project in Visual Studio 11 Developer Preview.
  • Give it a name AsyncEntityFrameworkDemo.

  • Within VS 11 DP open Server Explorer and create new Database DemoDb.
  • Create table Customers, with columns show on picture below

After you create a Table you need to insert a large number of rows that the retrieving data takes at least several seconds.
For that demo I have inserted about 500.000 rows. You can download my database with the Demo sample too.

After you prepare database, let’s create Entity Framework model. After that drag some controls to the MainPage.xaml designer like picture shows. You need to drag one DataGrid, Button and some other controls that we can test unblocking thread while data is retrieving from database.
Define OnLoaded event handle of the MainPage. In the event method we are going to call asynchronous implemented method.

private void OnLoaded(object sender, RoutedEventArgs e)

The implementation of LoadCustomersAsync(); is showed of the following listing.

&lt;summary&gt; /// Retieves data asynchoronous by calling EntityFramework Translate method. It uses the DbCommand and ExecuteReaderAsync
/// for retreiving data from database
/// &lt;/summary&gt;
private async void LoadCustomersAsync()
    using (DemoDbEntities ent = new DemoDbEntities())
        IDbConnection conn = (ent.Connection as EntityConnection).StoreConnection;
        using (DbCommand cmd = (DbCommand)conn.CreateCommand())
                var query = from p in ent.Customers
                        where p.Name.Contains(&quot;Name&quot;) &amp;&amp; p.Surname.Contains(&quot;Surname&quot;) &amp;&amp; (p.Name+p.Surname).Length&gt;3
                        select p;

            //Above linq code convert to SQL statement
            string str = ((ObjectQuery)query).ToTraceString();
            cmd.CommandText = str;

            //New method in C# 5.0 Execute reader async
            var task= await cmd.ExecuteReaderAsync();

            //translate retieved data to entity customer
            var cust1 = await Task.Run(
                () =&gt; ent.Translate(task).ToList());

            //put retrieved data to obesrvable coll
            var data = new ObservableCollection(cust1);
            //Notify about collection changed


The method is constructed of calling ExecuteReaderAsync: – the new asynchronous implementation of the SqlReader. Further, we have translated the data in to EntitySet and return the list of customers.
The complete data retrieval is implemented with the async pattern.
When we run the demo, we can see that the main UI Thread is not blocked while data is retrieving from the database.
After this implementation it will be nice that we can make an extension method for asynchronous Entity Framework call. So the following list represent extension method for asynchronous call for any Entity Framework query.

&lt;summary&gt;/// Asynchronous call of Entity Framework query
/// &lt;/summary&gt;public static class AsyncExtensions
    public static async Task&gt; ExecuteAsync(this IQueryable source,SqlTransaction transaction=null)
        where T : EntityObject
        var query = (ObjectQuery)source;

        //Find conncetion from query context
        var conn = ((EntityConnection)query.Context.Connection).StoreConnection as SqlConnection;
        if (conn == null)
            return null;

        //parse for sql code from the query
        var cmdText = query.ToTraceString();
        if (string.IsNullOrEmpty(cmdText))
            return null;

        //Create SQL Command object
        var cmd = new SqlCommand(cmdText);

        //if query contains parametres append them
        cmd.Parameters.AddRange(query.Parameters.Select(x =&gt; new SqlParameter(x.Name, x.Value ?? DBNull.Value)).ToArray());

        //Configure connection string
        cmd.Connection = conn;
        cmd.Connection.ConnectionString = new SqlConnectionStringBuilder(conn.ConnectionString) { AsynchronousProcessing = true }.ToString();

        //Now open the connection
        if(cmd.Connection.State!= System.Data.ConnectionState.Open)

        //New method in C# 5.0 Execute reader async
        var reader = await cmd.ExecuteReaderAsync();
        var data = await Task.Run(() =&gt; { return query.Context.Translate(reader).ToList(); });

        return data;


The use of this method is simple. Include in your project, and call against any Entity Framework query. In our Demo the new method looks like the folowing:

private void LoadCustomersAsyncExtensionMethod()
    DemoDbEntities ent = new DemoDbEntities();
    var query = from p in ent.Customers
                where p.Name.Contains(&quot;Name&quot;) &amp;&amp; p.Surname.Contains(&quot;Surname&quot;) &amp;&amp; (p.Name + p.Surname).Length &gt; 3
                select p;

    //Execute EF query asynchronous
    var result = query.ExecuteAsync();

    //When the result come from database continue with and  assign to datagrid
    result.ContinueWith((asyncTask) =&gt;
        //Fill ItemsSource collection by data from database using Dispatcher, since probably we are not in UI thread
            (Action)(() =&gt; customersDataGrid.ItemsSource = asyncTask.Result)


After we define a query, we call ExecuteAsync extension method. We need to wait the data from database by calling ContinueWith task method.
When the data is come, assign the to ItemSource of DataGrid.

The Demo sample and database you can download here.

MVVM u razvoju WPF/SL poslovnih aplikacija na MSNetwork

Upate 20.03.2011: Izvorni kod za demo sa predavanja, kao i prezentacijsku datoteku možete skinuti sa ovog linka.

U sklopu konferencije MSNetwork 18. marta u 9 sati u hotelu Vidivić biće održano predavanje na temu MVVM tehnika u razvoju WPF/SL poslovnih aplikacija u kojoj će biti prezentirana ova tehnika razvoja WPF i Silverlight aplikacija.

Podaci o prezentaciji:

Prezentator: Bahrudin Hrnjica, DataSoft Bihać
Twitter: @bhrnjica
Trajanje: 45-60 min.
Level: 300-400

Kratki opis:

Model View ViewModel (MVVM) predstavlja tehniku pri razvoju i dizajnu  aplikacija na WPF i Silverlight UI platformama, a koncipirana je na odvajanju korisničkog iskustva(UX) i poslovne logike (BL). Ova tehnika predstavlja novi koncept razvoja, dizajna i implementacije poslovnih aplikacija. Prezentacija prikazuje  MVVM tehniku razvoja, kroz pojašnjenje 3 sloja: Model, View i ViewModel. U sklopu prezentacije biće pojašnjen koncept komunikacije između View i ViewModela kroz Commands i Behaviors klase, te pojam tzv. ChildWindows pomoću Messenger klase, preko koje se vrši povratna veza između ViewModel i View slojeva. Tokom prezentacije svi pojmovi i modeli prezentiraju se kroz demo primjer: BugTracker aplikacija urađen u Silverlight i WPF. Primjer demonstrira upotrebu MVVM tehnike, kroz dijeljenje izvornog koda sa WPF i Silverlight, dijeljenje jednog modela (Entity Framework) baze podataka između Silverlight i WPF preko implementacije posebnog servisa kojim se, s jedne strane rasterećuje ViewModel klasa, a s druge strane unificira pristup bazi podataka iz Silverlight i WPF  implementacijom zajedničkih metoda definisanih u baznom intrfejsu. BugTracker aplikacija sadrži i upotrebu lokalizacije, RIA Servisa i drugih primarnih dijelova aplikacije koji svaka poslovna aplikacija sadrži. Aplikacija sadrži preko 95% zajedničkog izvornog koda kojeg dijele WPF i Silverlight. BugTracker je posebno radjen za ovu konferenciju te će se objaviti upravo po završetku prezentacije. Screenshot aplikacije u Silverlight i WPF prikazan je u narednoj slici.

Screenshot Demo aplikacije koje će biti prezentirana na MSNetwork 18. marta.









Prezentacijska datoteka kao i demo aplikacija biće objavljena poslije konferencije.

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.


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


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.

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


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)
 //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;


 return true;
 catch (Exception ex)
 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)
//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();


return true;
catch (Exception ex)
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.