Monthly Archives: October 2011

Customization of WPWidgetLibrary


In only 12 days WPWidgetLibrary reach more that 800 page views and over 50 downloads. This is good start of the library since building HTML5 apps in Windows Phone is coming. We have also got several feedbacks and questions about the library, and we can say the WPWidgetLibrary is indeed solution for developing hybrid mobile applications for Windows Phone 7.
One of the question about WPWIdgetLibrary is how to customise some features. For example default library no support avi file format. For that reason we have opened Discussion section of the library and put some answers. Here is one of them Damir has posted:
WpWidgetLibrary installs HTML app by calling:

InstalHTMLContent(string htmlFolder, string[] htmlDirs) ;

where htmlFolder is the folder in solution which contains all required web files. In other words this is the root of web-application which will be executed from isolated storage. Because you are free to use any kind of extension like “myfile.tiff” the framework can either copy any file in your project or specific files. We decided to copy specific files only.
Here is how we do it:

protected virtual bool IsWebExtension(string ext)       {
bool res = false;
switch (ext.ToLower())
{
 case "htm":
 case "html":
 case "js":
 case "jpg":
 case "jpeg":
 case "png":
 case "css":
 res = true;
 break;
 }
return res;
}

If your HTML mobile app requires other file formats eg. “abc.avi”, just derive the WPWIdgetLibrary class and override this method like the following sample.

public class MyWPWidgetLibrary: WPWidgetLibrary{
protected override bool IsWebExtension(string ext){
bool res = false;
 switch (ext.ToLower())
 {
 case "avi":
 return true;
 //break;
 }
 return base.IsWebExtension(ext);
 }
}

Now WPWidgetLibrary supports custom avi files.
On similar way you can implement support of any file format you want.

In only 12 days WPWidgetLibrary reach more that 800 page views and over 50 downloads. This is good start of the library since building HTML5 apps in Windows Phone is coming. We have also got several feedbacks and questions about the library, and we can say the WPWidgetLibrary is indeed solution for developing hybrid mobile applications for Windows Phone 7.

One of the question about WPWIdgetLibrary is how to customise some features. For example default library no support avi file format. For that reason we have opened  Discussion section of the library and put some answers. Here is one of them Damir has posted:

WpWidgetLibrary installs HTML app by calling:


 InstalHTMLContent(string htmlFolder, string[] htmlDirs) ;

where htmlFolder is the folder in solution which contains all required web files. In other words this is the root of web-application which will be executed from isolated storage. Because you are free to use any kind of extension like “myfile.tiff” the framework can either copy any file in your project or specific files. We decided to copy specific files only.

Here is how we do it:


protected virtual bool IsWebExtension(string ext)       {
bool res = false;
switch (ext.ToLower())
{
 case "htm":
 case "html":
 case "js":
 case "jpg":
 case "jpeg":
 case "png":
 case "css":
 res = true;
break;
}
return res;
}

If your HTML mobile app requires other file formats eg. “abc.avi”, just derive the WPWIdgetLibrary class and override this method like the following sample.

public class MyWPWidgetLibrary: WPWidgetLibrary{
protected override bool IsWebExtension(string ext){
bool res = false;
switch (ext.ToLower())
{
 case "avi":
 return true;
 //break;
}
return base.IsWebExtension(ext);
}
}

Now WPWidgetLibrary supports custom avi files.

On similar way you can implement support of any file format you want.

Advertisements

Skrgic Selection in GPdotNET


Introduction

This document presents Skrgic Selection Method, the one of several selection methods in GPdotNET. While I was developing GPdotNET I have had several conversation with my friend Fikret Skrgic (master in computer scinence and math) regarding selection in Evolutionary algorithms. He is an incredible man, and in just a few minutes while I was describing to him what I want from a new way of selection, he came out with the basic idea of the new selection method. After that time in just a few mails I had a new selection method ready for implementation in GPdotNET. I gave the name to the new selection method by his surname. It is a little thankfulness to him.

In the flowing text it will be presented the idea behind Skrgic Selection.

Liner Skrgic Selection (LSS)

The Idea behind this selection is based on chromosome fitness. The rule is simple: The bigger chromosome fitness gives bigger chance to select better chromosome. In Population, chromosomes are already sorted from best to worst chromosomes.
The process of selection is the following:

  1. Find the maximum and minimum fitness value from the population.
  2. The best chromosome (maximum fitness) has position 0 in the population (zero based index), and the worst chromosome has index N-1.
  3. Let’s give them name as f_{max} and f_{min} respectively.
  4. Choose random number r between f_{min} and f_{max}.
  5. Choose random chromosome from the Population chrom.
  6. Compare the values of r and f_{chrom}. If the f_{chrom} is greater than r, select chrom.
  7. Repeat steps 3 and 4 until you select one chromosome.
  8. Repeat steps 2,3,4,5 until you select n chromosomes.

The following picture shows graph of linear Skrgic selection:

Linear Skrgic Selection (LSS)

Nonlinear Skrgic Selection (NSS)

In LSS we have linear graph of selection probability. This means that if we have chromosome with f_{chrom} fitness value, and another chromosome with \frac{f_{chrom}}{2} fitness value, the probability of selection of two chromosomes is p and \frac{p}{2} respectively. This means that probability of selection is growing linearly.
If we want to change probability between chromosomes we can define a factor k to be like selection pressure on whole chromosomes in the population. So let the k be a real value, and define the fitness of each chromosome as:

f_{nss}=f_{chrom} (1+k \frac{f_{chrom}}{f_{max}}),

where:

  • f_{chrom} – fitness value of the chromosome,
  • f_{max} – maximum fitness value(fitness of the best chromosome of the population),
  • k – selection pressure,
  • f_{nss} – nonlinear fitness value of the chromosome.

We can conclude that the maximum nonlinear fitness value of the best chromosome is given by:

f_{max(nss)}=f_{max}(1+k).

For various value of parameter k  we can define graph of probability selection like on the following picture:

Graph for various sample of NonLinear Skrgic Selection (NLSS)

On the picture above we can see if k=0 we get the standard Linear Skrgic Selection (LSS). We can also conclude that there is a fitness value when the probability of selection is constant and not depends of parameter k. Very interesting graph is when the k=-1. In this case the selection probability of the worst and the best chromosome are equal.

GPdotNET settings of GP parameters

Announcing WpWidgetLibrary – HTML Widgets for Windows Phone


WpWidgetLibrary - HTML Widgets for Windows Phone

-Do you want to implement apps for cross-browser support?
-Do you want to have HTML5 Widget App which can be published through Windows Phone Marketplace, with ability to be updatable?
-Do you want to develop hybrid app in Windwos Phone 7?

Is so and if you are Windows Phone developer this is the right project for you.

Daenet team is proud to announce the first version of the WpWidgetLibrary – HTML Widget for Windows Phone – library for building HTML5 apps on Windows Phone mango.  The latest update for WP 7 enables the usage of HTML5 content via the Marketplace. These Applications always need to be hosted on a webserver so they are not useable offline. Even for Microsoft itself this issue was a problem without solution. With this library you can build HTML 5 Widgets app as a native WP7 app, which you can publish on the windows phone  marketplace and  easily make update for the app. Widgets for WP also tries to solve problems of running HTML page in offline mode on  Windows Phone. Library works so that on the first time installs the HTML5 content in isolated storage by simulating the real hard disk, and paths of the HTML pages, scripts, images etc.

With Widget library you can build cross –platform jQueryMobile HTML5 apps for Windows Phone, and other kind of HTML mobile apps.

More info about this open source project can be found on codeplex site http://wpwidgetlibrary.codeplex.com.

Inspiration about this library and problems handling HTML5 apps in WP7 you can read on Damir’s blog series HTML5 for Windows Phone 7.1+ – Episode I : HTML5 Support and HTML5 for Windows Phone 7.1+ – Episode II : Browsing HTML content.

Feel free to contact us for any problems you may have, or send us feedback about the library.

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)
{
   LoadCustomersAsync();
}

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>
private async void LoadCustomersAsync()
{
    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
            var task= await cmd.ExecuteReaderAsync();

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

            //put retrieved data to obesrvable coll
            var data = new ObservableCollection(cust1);
            //Notify about collection changed
            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
        var reader = await cmd.ExecuteReaderAsync();
        var data = await Task.Run(() => { 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("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
    result.ContinueWith((asyncTask) =>
    {
        //Fill ItemsSource collection by data from database using Dispatcher, since probably we are not in UI thread
        this.Dispatcher.Invoke(
            DispatcherPriority.Normal,
            (Action)(() => 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.

Osmo okupljanje Bihac .NET User grupe


Nakon ljetne pauze  Bihać .NET User grupa ponovo se okuplja ali sada na novom mjestu. Od ove sezone sastajaćemo se na Tehničkom fakultetu u Bihaću. Razloga ima više a jedan od njih je da se približimo studentima.

Za ovo okupljanje u goste nam dolazi Radenko Zec Software developer iz firme Lanaco iz Banjaluke, te voditelj INETA User grupe u Banjaluci.

Tema sastanka: Razvoj Silverlight i Windows Phone 7 aplikacija koristeci mogucnosti Windows Azure platforme
Opis predavanja:
Silverlight je razvojna platforma za kreiranje interaktivnih, bogatih korisničkih rješenja za web i mobilne aplikacije, dok razvoj aplikacija za Cloud predstavlja najveću promjenu koja je zadesila našu industriju tokom poslednjih nekoliko godina.Kombinujući bogato korisničko iskustvo koje nam pruža Silverlight sa fleksibilnošću i skalabilnošću Windows Azure Cloud-a možemo da napravimo nevjerovatne web i mobilne aplikacije.

Vrijeme i mjesto:

14. oktobar, 2011, na Tehničkom fakultetu u Bihaću, I sprat.

Na sastanku ćemo imati i vrijedne nagrade majice i vjetrovke od MSCommunity BiH te Telerik Licencu koji je naš redovni sponzor.

Vidimo se u petak!