# Category Archives: WPF

Članci koji se odnose na WPF

## 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

Each 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 key 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 and certain number.

Example

13=+

# Type of Games

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

· HDV Sum

· Sum to 11

# HVD Sum

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.

```///
<summary> /// Retieves data asynchoronous by calling EntityFramework Translate method. It uses the DbCommand and ExecuteReaderAsync
/// for retreiving data from database
/// </summary>
{
using (DemoDbEntities ent = new DemoDbEntities())
{
IDbConnection conn = (ent.Connection as EntityConnection).StoreConnection;
conn.Open();
using (DbCommand cmd = (DbCommand)conn.CreateCommand())
{
var query = from p in ent.Customers
where p.Name.Contains("Name") && p.Surname.Contains("Surname") && (p.Name+p.Surname).Length>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

//translate retieved data to entity customer

//put retrieved data to obesrvable coll
var data = new ObservableCollection(cust1);
Customer_CollectionChanged(data);
}
}

}
```

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.

```///
<summary>/// Asynchronous call of Entity Framework query
/// </summary>public static class AsyncExtensions
{
public static async Task> 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 => 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)
cmd.Connection.Open();

//New method in C# 5.0 Execute reader async

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("Name") && p.Surname.Contains("Surname") && (p.Name + p.Surname).Length > 3
select p;

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

//When the result come from database continue with and  assign to datagrid
{
//Fill ItemsSource collection by data from database using Dispatcher, since probably we are not in UI thread
this.Dispatcher.Invoke(
DispatcherPriority.Normal,
);

});
}
```

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.

## 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ć
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.
ConnectionStrings["ConnStringDemo1.Properties.Settings.NorthwindConnectionString"];
```

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)
{
try
{

//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
{

//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.