Monthly Archives: September 2012

Developing Windows Store App Part 2: REST Service implementation


Today’s blog post will discass how to implement REST service by using ASP.NET Web API. To expose data to our Windows Store app, we need to implement some kind of REST or Soap service. For this sample we are going to create Rest service, which will expose basic data operation to our Windows 8 Store client.

1. Open you previous EFModel solution in Visual Studio 2012.

2. Right click at the solution and choose Add New Project

3. Select ASP.NET MVC 4 Web Application, Enter the name of the project.

4. Click OK button.

5. On the next Dialog select Web API, and click OK button.

6. Initial skeleton for RESTService is created.

7. Add Reference of EFModel project.

Now we are going to implement Controller.

8. Right Click on RestService project ->Add New Controller.

9. Enter CExplorer name, and click OK.

Implementation of the controller shows the next listing:

 public class CExplorerController : ApiController
    {
        // GET CExplorer
        [HttpGet]
        public List Place()
        {
            /// return new string[] { "value1", "value2" };
            ///
            try
            {
                using (CExplorerContext ctx = new CExplorerContext())
                {
                    var lst = ctx.Places.ToList();
                    return lst;
                }
            }
            catch (Exception)
            {

                throw;
            }

        }

        // GET CExplorer/5
        [HttpGet]
        public Place Place(int id)
        {
            try
            {
                using (CExplorerContext ctx = new CExplorerContext())
                {
                    return ctx.Places.Where(x => x.PlaceID == id).FirstOrDefault();
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        // GET CExplorer/5
        [HttpGet]
        public IEnumerable Search(string queryText)
        {
            try
            {
                //queryText = queryText;
                using (CExplorerContext ctx = new CExplorerContext())
                {

                    var lst11 = ctx.Dishes.Where(x => x.Name.ToLower().Contains(queryText.ToLower())).Select(x => x.DishID).ToList();
                    var lst22 = ctx.Towns.Where(x => x.Name.ToLower().Contains(queryText.ToLower())).Select(x => x.TownID).ToList();

                    var lst = ctx.Places.ToList();

                    var ll = from p in ctx.Places
                             where
                             lst11.Contains(p.DishID) ||
                             lst22.Contains(p.TownID) ||
                             p.Name.ToLower().Contains(queryText.ToLower()) ||
                             p.Slogan.ToLower().Contains(queryText.ToLower())

                             select p;

                    var rr = ll.ToList();
                    return rr;
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        // POST CExplorer
        [HttpPost]
        public void Place([FromBody]Place plc)
        {
            try
            {
                if (plc == null)
                    return;
                using (CExplorerContext ctx = new CExplorerContext())
                {
                    if (plc.PlaceID == -1)
                    {
                        ctx.Places.Add(plc);
                        ctx.SaveChanges();
                    }
                    else
                    {
                        var p = ctx.Places.Where(x => x.PlaceID == plc.PlaceID).FirstOrDefault();
                        if (p == null)
                            return;

                        p.Name = plc.Name;
                        p.Slogan = plc.Slogan;
                        p.Description = plc.Description;
                        p.DishID = plc.DishID;
                        p.TownID = plc.TownID;
                        p.Image = plc.Image;
                        ctx.SaveChanges();
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        // GET Town
        [HttpGet]
        public List Town()
        {
            /// return new string[] { "value1", "value2" };
            ///
            try
            {
                using (CExplorerContext ctx = new CExplorerContext())
                {
                    return ctx.Towns.ToList();
                }
            }
            catch (Exception)
            {

                throw;
            }

        }

        // GET Dish
        [HttpGet]
        public List Dish()
        {
            /// return new string[] { "value1", "value2" };
            ///
            try
            {
                using (CExplorerContext ctx = new CExplorerContext())
                {
                    // var ss= ctx.Dishes.ToString();
                    return ctx.Dishes.ToList();
                }
            }
            catch (Exception)
            {

                throw;
            }

        }
    }

10. Resolve using statement, that you can compile project.

11. Modify App_Start/WebApiConfig.cs file like the following listing:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                 name: "DefaultApi",
                 routeTemplate: "{controller}/Place/{id}",
                defaults: new { action = "Place", id = RouteParameter.Optional }
             );

            config.Routes.MapHttpRoute(
                name: "DefaultApi1",
                routeTemplate: "{controller}/Town",
               defaults: new { action = "Town" }
            );

            config.Routes.MapHttpRoute(
                name: "DefaultApi2",
                routeTemplate: "{controller}/Dish",
                defaults: new { action = "Dish" }
            );

            config.Routes.MapHttpRoute(
                 name: "DefaultApi3",
                 routeTemplate: "{controller}/Search/{queryText}",
                defaults: new { action = "Search", queryText = RouteParameter.Optional }
             );
        }
    }

Defining connection string. For propery connection string definition you need to provide valid SQL login. You can achive this by creating new Login at SQL Server database, similar like picture below.

12. Add connection string to WebConfig file similar like the following.

<connectionStrings>
  <add name="cexplorer_db" providerName="System.Data.SqlClient" connectionString="Data Source=.\sqlexpress;Initial Catalog=cevap_db;Persist Security Info=True;User ID=testuser;Password=123;"/>
  </connectionStrings>

13. Set RestService as Startup project, and hit F5.

14. When IE appear, enter the following url adress: http://localhost:4636/cexplorer/place, to get all Places from the db.

Note: This is exactly what we inserted in Place Table, while we run EFTest console app from the previos blog post.

Now we have all instrastructure to start developing Windows Store app Ćevap Explorer. Source code for this blog can be found here.

Advertisements

Golden Ratio and GPdotNET v2 User Interface


First of all, I am not a designer. In fact I don’t think I can design anything beautiful. Mostly, if I want to design something first asked some of my friends or people who knows about design, before decided to do. So design implementation of GPdotNET v2 was very frustrated for me. Anything I have implemented, I thought it was not so good. I still think that the current design of GPdotNET v2 is not something which I can say very well. But something interesting happen while I have designed current UX. I knew if something needs to be designed well, it must be based on golden ratio. So I have decided to implement golden ration anywhere where is possible in the app.

This blog post is going to present one approach of implementation of golden ratio in Application, as a good recipe for design. If you don’t know what is golden ratio you can found on this link.

So let’s first see the Start Screen.

Start Screen of GPdotNET

The first implementation of golden Ratio was dimension of the main window. So when you open GPdotNET, the size of initial Window is size=(932:579) which means that the height=579, and width=579*1,61=932, which is depicted on picture below as well.

Then I concentrate on my main toolbar to see if possible to implement golden ratio there. So if you look for example Common group, you can see that the width and height are designed by golden ratio, as well as height = width=H/Φ of tool button.

I have also implement golden ration to parts of group bar. The number a, b, c are implemented based on golden ratio on the following way: c=(a+b)*Φ, b=a*Φ (see picture below).

Other group bars are also implemented with golden ratio by simple adding half width of Common group toolbar for each additional tool button.

Create new Model Dialog

Other full implementation of golden ration was in Create New Dialog
From picture you can see that the size of dialog is based on golden Ration, as well as parts of the dialog. One interesting thing is that the position of Cancel and OK buttons are also based on golden ratio. Length of line a, is the same as length b multiple by Φ.

Export Dialog

Export dialog is pretty simple so golden ratio is implemented in 3 elements height (a) of ListBox, height (b) and width (c) of dialog in relations b=a*Φ , c= b*Φ, which you can see from the picture below.

I don’t know is my design is better than previous but I know you can find some interesting proportions in form of golden ration. :)

GPdotNET v2.0 Feature Complete Milestone Reached


I’m happy to announce that GPdotNET is feature complete. All features planned for this version are successfully implemented. For few days GPdotNET v2.0 Beta 2, will be published at Codeplex, so you can download and taste the software.

There is a brand new Start Page to show some of  predefined and calculated samples. With Start page it will be easier to learn how GPdotNET works. Samples shown at the start page are some of my works, and other authors which I mentioned in the Info tab page of the model.

Export feature is also implemented, so you can export Model in CSV and Excel format. Excel format is supported only on Windows. For Linux user only CSV format is supported. In the coming post it will be describe all new feature coming with this version.

Post Updated:

You can download beta 2 version from the following link: http://gpdotnet.codeplex.com/releases/view/94804 

Any feedback is appreciated.

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.

MSCommunity BiH Session: Developing Windows Store LOB apps


After great 3 days of KulenDayz and CEE MVP Summit in Baranja (north-east part of Croatia), the next conference I will be speaking is MSCommunity BiH konferencija in Sarajevo.
For the first time, Microsoft Community in Bosnia and Herzegovina is organizing the event dedicated for launching new Microsoft products Windows 8, Windows Server 2012 and Visual Studio 2012. For this conference I prepared a session about developing Windows Store LOB apps. This presentation has a lot of cool demos integrated in to one app called ĆevapExplorer.
Through the session I will be presenting how to design Windows Store app, by describing main design requirements of each WinStore app. Beside design feature, Win Store app requires data and connection to data source. Through the demo it will be presenting how to develop data model by using the latest Microsoft ORM Entity Framework V5.
After DB model is implemented, we need some way to provide data to Windows Store app. Windows Store app is running in some kind of isolated storage provided by Windows Run-Time, so there is no way to connect EF model directly to Win Store app. The only way to provide EF data to Win Store app is by implementing some kind of web service (REST or WCF in our case).
The second part of the demo will be presenting how to implement WCF service by using the latest version of the .NET 4.5 and WCF 4.5. If you want to develop lighter service infrastructure, beside WCF, you can use ASP.NET Web API to implement RES service.
The further demo will be presenting how to implement REST service that will be used by Win Store app. Implementation of REST service by using ASP.NET Web API is very popular MS Technology today, and it is recommended for developing this kind of services.
After backend infrastructure is presented, the main demo can starts using data of EF Model through REST or WCF service. In the first part of the main demo it will be presenting how to develop UI for presenting data, by describing how to use predefined visual studio 2012 templates, how to use HttpClient and how to integrated our app with Windows 8, by implementing Windows 8 contracts. By implementation Search Contract, demo will show how to integrate Windows 8 Search mechanism in to our app.
As the last part of demo, it will be presenting how to implement data source without using .NET infrastructure, but using only WinRT. For this we will use SQLite library. SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. SQLite is the most widely deployed SQL database engine in the world. Because of native support of WinRT, this library can be easily compiled and built in Windows RunTime, so we used it as a C/C++ class library in our C# WinStore app. This part of demo present how to used native nature of WinRT to use C/C++ library in our C# application, without complex implementation seen in .NET with P/Invoke and DLL Import.

Because of importance of accepting new Windows 8 develop technology in the future development, this blog post is part of several post which will give detail information about each mentioned part of the demo. Each blog post will be describe in form of tutorial one part of the demo. The name of demo is ĆevapExplorer. Ćevap stands for the most populate Bosnian national dish which can be found in every restaurant, but only few of them serve the best Ćevap. The application is collecting data about the best restaurants around the Bosnia not only for Ćevap, but the main Bosnian dishes. The app present location about restaurants serving the best dish.
After conference event, blog post will be published periodicaly.
See you in Sarajevo.