Interesting Links, June 25, 2012

I have been directed to two posts below from my twitter feed.

The first post is by Infragistics. It should answers the common questions about Windows 8, Surface, Windows RT, and Windows Phone 8 include:

  • Can Windows 8 run my current Windows app?
  • Can I build Windows 8 Metro apps in .NET?
  • Are Windows 8 games built in C++ or XNA?
  • Can I build apps for both Windows 8 and Windows Phone?
  • What are all developer platforms for each devices?

Infragistics is one of the leaders in providing UI tools and .NET components . They also provide developer support, training, and consulting services. For anyone who is interested in UX and UI patterns, you should also visit Quince. There are many UI/UX patterns that you can search and learn.

The second post is about Infographics which is another topic that I try to learn as much as possible. I believe good understanding in how to design infographic can help you design the software dealing with complex and large amount of data. The post by Hyperkat’s Josh Smith is talking about how to design an infographic in 10 steps.

“Information can be useful–and even beautiful–but only when it’s presented well.”

The quote above said it all. With the advance of information technology, we can store almost any information that we have gathered. However, without the way to present them comprehensively, the information is useless. The writing is talking about the ten steps process of transforming data into a visually compelling graphic (aka Infographic).
I like this step as data/information can be boring. Attaching some story with them helps clarifying a complex set of data and highlighting a trend.

Enjoy coding!

Advertisements

Join NoSQL movement with RavenDB – Part 1

NoSQL (aka Not Only SQL which Martin Fowler does not actually like the term) database is a database that does not totally adhere to relational concept. Another important characteristic is that some NoSQL implementation may not give full ACID guarantee. However, because of their distributed architecture in mind, most NoSQL database are very scalable in contrast to a classic relational database which can suffer from scalability issue. I won’t discuss RDBMS vs. NoSQL here as they are both invented to solve problems and I believe that what you choose should depend on your problem.

Although I have heard about NoSQL Database for a while, I haven’t had a chance to try it yet until I learned about one of the NoSQL database, RavenDB in the Nashville .NET Usergroup meeting last week.

RavenDB is a document-oriented database which is one of NoSQL implementations. The main concept of document-oriented database is that it stores document with a key (i.e., key/value). A document encapsulates data and can be encoded by using JSON (in RavenDB case), XML, Microsoft Word, etc. Every document has unique key (i.e., id) that represents that document. RavenDB has been written entirely in .NET, stores data as schema-free JSON (i.e., key/value) and provide a RESTful API for interaction with the database. Any client that supports HTTP/JSON communication should be able to use RavenDB. For .NET client, RavenDB provides LINQ support as well.

RavenDB can be run in as a console application, Windows service, IIS application, or embedded with client.

In this post, I will introduce RavenDB in embedded mode which is the easiest way to get started as I don’t need to set up and run the RavenDB server separately. With the help of NuGet, I can install everything in just one click.

After I create a console application, I go to NuGet package manager, and look for RavenDB Embedded. The embedded package will install both RavenDB Client, Database, and Embedded into the console project.

image

image

After I agree and accept all license terms, in the Solution Explorer, there will be a whole bunch of references added into the project.

image

Before I start using embedded RavenDB, I will need to specify where the database should be located by specify connection string.  This is not so different from how other databases such as SQL Server or Oracle connection string is setup. I create a new folder called Database in my project just to separate database from the code, but I can have RavenDB use any location to which my application has access.

image

<connectionStrings>
   <add name="RavenDB" connectionString="DataDir = .\Database" />
</connectionStrings>

In the code, I start by creating a DocumentStore instance which is thread-safe. However, DocumentStore is not cheap to create (similar to SessionFactory in NHibernate), the instance should be created once per database and application. Although the sample code is using ConntectionStringName, I can also use DataDictionary to specify the location directly in my code.

 using (var docStore = new EmbeddableDocumentStore { ConnectionStringName = "RavenDB" }.Initialize()) 

After I have a DocumentStore instance, then I can get a session from it (very similar to Session in NHibernate as well). The full sample code below just show how I can create a new document (i.e., Person instances), store them to RavenDB and query them later using LINQ.

class Program
    {
        static void Main(string[] args)
        {
            using (var docStore =  new EmbeddableDocumentStore 
                { 
                    ConnectionStringName = "RavenDB" 
                }
                .Initialize())
            {
                using (var session = docStore.OpenSession())
                {
                    // add new person
                    var p = new Person { LastName = "Fuchsia", FirstName = "Cyan" };
                    session.Store(p);
                    
                    // Id is generated by RavenDB
                    Console.WriteLine("{0} generated by RavenDB"
                        , session.Advanced.GetDocumentId(p));
                    session.SaveChanges();

                    #region Add more people
                    session.Store(new Person { LastName = "Hanselman"
                        , FirstName = "Scott" });
                    session.Store( new Person { LastName = "Rahien"
                        , FirstName = "Ayende" });
                    session.Store( new Person { LastName = "Sinofsky"
                        , FirstName = "Steven" });
                    session.Store( new Person { LastName = "The Gu"
                        , FirstName = "Scott" });
                    session.SaveChanges();                    
                    #endregion
                }

                using (var session = docStore.OpenSession())
                {
                    // retrieve people using LINQ
                    var people = from person in session.Query<Person>()
                                 select person;

                    Console.WriteLine("Total: {0}", people.Count());

                    foreach (var doc in people)
                    {
                        Console.WriteLine("{0} : {1}, {2}"
                            , doc.Id, doc.LastName, doc.FirstName);    
                    }                    
                }                
            }            
        }

        public class Person
        {
            public string Id { get; set; }
            public string LastName { get; set; }
            public string FirstName { get; set; }
        }
    }

Every document in RavenDB has to have a key, and RavenDB will generate a new key for the document if it has not been assigned already. Here is what happen when I run the code above.

image

I can go to the bin folder and see database that has been created. The folder is just a normal folder although the RavenDB icon is displayed.

image

image

In next RavenDB post, I will run RavenDB server in the console mode and show the RavenDB management studio which can be used to manage RavenDB server as well as see RavenDB in more detail. Enjoy coding!

C# String.format in JavaScript

As a mainly C# developer who has to work on JavaScript more and more, I do miss the string.format method that I do use very often (like when C++ guys misses the sprintf when they do C# Winking smile ).

I found someone re-implement string.format in JavaScript here.

String.format = function () {
	var s = arguments[0];
	for (var i = 0; i < arguments.length - 1; i++) {
		var reg = new RegExp("\\{" + i + "\\}", "gm");
		s = s.replace(reg, arguments[i + 1]);
	}
	return s;
}

You can find my jsfiddle exmple here. Enjoy coding!

$(window).resize() and Internet Explorer 8

I am almost done with my consumer preview (aka beta) of my interactive HTML5 chart using Raphahël SVG (which I post about it last week). Then I realize that I should test the chart again on IE8.

I use the IE Developer tools (which you can activate by pressing F12 key) to change my current IE9 to 7 and 8 which majority of my users are still using. I have tested the chart before and for IE7 and IE8 which does not support SVG, Raphaël just generates VML and the chart looks pretty much the same.

To make it more responsive to different size of the user’s browser windows as well as their screen resolution, later, I use the JQuery resize() function to detect the window resize event and act accordingly (i.e., clear the chart, re-calculate chart items size and location, and redraw those items).

What happen was that IE8 fires resize event even when any elements on the page is resized which can be triggered by changes of many things such as height, style attributes, and so on. So when my JavaScript/Raphaël performs redraw actions, the resize event is fired again and again and again (infinite loop)!

Fortunately, this can be resolved by simple tricks of checking if the width or height of the browser window really change or not. Here is the code.


var currentHeight;
var currentWidth;

$(window).resize(function () {
   var windowHeight = $(window).height();
   var windowWidth = $(window).width();

   if (currentHeight == undefined || currentHeight != windowHeight
      || currentWidth == undefined || currentWidth != windowWidth) {

      // redraw the chart here will make IE8 fire resize event again
      // ...

      currentHeight = windowHeight;
      currentWidth = windowWidth;
   }
});

That is it. You might remember the old day with all alert statement in your JavaScript code. Debugging JavaScript was very painful when before Firebug has been introduced. Thankfully, we can easily debug JavaScript today as most new browsers are now equipped with JavaScript debugger. Enjoy coding!

Windows 8 rises to the Surface

Many people including me wouldn’t know that when the current CEO, Steve Ballmer, joined Microsoft, the best selling product was a hardware called SoftCard. Microsoft is known by most people as a software company.

image

image

However, yesterday, Microsoft just looked totally different in one of the most mysterious and hyped up Microsoft announcement (full video here). It’s not easy to introduce something that will not be available for months and still make many people excited. Yes, I am talking about the Surface, Microsoft- branded tablet. It looks just like a normal tablet, but what sets it apart is how much detail and effort Microsoft put into this product. Microsoft realizes now that if they want Windows 8 to be successful they can’t just rely on good ole OEMs. And it does show what tight integration and craftsmanship can produce.

image

Here are some important keys from the event:

VaporMg: (pronounce Vapor-Mag) which is a process of molding metal (i.e., magnesium) and deposit particles to create very thin and light but strong parts. This process gives Surface a thin and light casing including the integrated Kickstand that is thinner than a typical credit card.

image

image

Touch and Type Cover :  I was impressed with iPad cover which could be used as a stand (Steve Jobs presentation was also help), but the idea of embedded the keyboard and trackpad to the 3 mm thin cover just blew me away. The simple and elegant seems to be what make people most excited as people applauded when Steven Sinofsky introduced it. Touch Cover is a capacitive touch, but it also pressure sensitive, which together sense keystrokes as gesture and should enable fast touch typing. It also helps when it comes with multiple colors!

image

image

By the way, Microsoft also introduces black Type Cover which has the moving keys while the thinner Touch Cover is capacitive touch. However, nobody should expect the keyboards will be comparable to real keyboard like my favorite Microsoft Natural Ergonomic Keyboard 4000, but this is still supposed to be twice as fast comparing to typing on the glass when using on-screen keyboard.

image

Touch and Digital-ink Digitizers: The Windows 8 Pro version (Core i5 Ivy Bridge model) will come with two digitizers, one for touch, and one for digital-ink. A provided stylus looks just like a normal ballpoint pen. The tablet also has Palm Block technology which will disable the touch digitizer when the stylus is close to the screen. This way, the touch action won’t be registered accidentally when the stylus is being used. I think this is also something that other tablets do not have.

image

Others: The other interesting things include the back camera that is angled at 22 degree when you use with the Kickstand which also shows how much attention Microsoft put into the Surface PC. Perimeter Venting design also makes sure that no matter how people hold the Surface, they won’t cover the air venting. I think this is for Windows 8 Pro version only.

image

The Surface is also the first to include a high performance 2×2 MIMO antenna.

Another thing that makes me happy is how background color for Windows 8 will change, when it is attached to the Touch Cover, to match the Touch Cover color. People might think this is just a small gimmick, but for me, this small attention in detail makes me love the device much better.

image

image

Well, the only issue for me is nobody knows when it will be available and how much it will cost. Steven Sinofsky mentions that the Windows RT version should be available the same time Windows 8 is available which can be 2-4 months away. However, the most disappointing news was that the Windows 8 Pro version would be available three months later.

Anyway, this should be a day-one buy for me unless the partners like Asus, Acer, Dell, HP, Lenovo, or even Vizio could come up with something better which I doubt it.  If other OEMs can’t provide better devices, please do not blame Microsoft. As a consumer, I want the best Windows 8 tablet available, and my money will follow. Microsoft is raising the bar and challenging all partners to take their games to the next level!

Local LightSwitch app and Windows Azure SQL Databases

Windows Azure, briefly, is a Microsoft public cloud platform that can be used to build and host web sites, virtual machines, SQL Server database, cloud services (i.e., worker and web roles), blob storage.  LightSwitch is a simple development tool built on top of familiar .NET technologies like VB/C#, Silverlight, and SQL Server. It allows development of line-of-business n-tier application very rapidly.

In this post, I will show how to create a local LightSwitch app which connects to a SQL Database in Windows Azure cloud.

First, we start by creating a SQL Server on Windows Azure. I go to Windows Azure portal then add new SQL Databases. If no SQL server has been created already, Azure will also create a new server.

image

After the database has been created, I can go to the dashboard to check the database status and get information of the database such as connection string. In my case, I want to have my machine to be able to connect to the SQL server, so I have to modify the firewall rule to let my IP address goes through. Azure does show my IP address which is very convenient.

Azure also provides me a very nice Silverlight-based SQL Azure Management Portal allowing me to manage the database online.

image

Indeed, the tool lets me create database tables, queries, and so on. I create a simple table called Blog with Title and Url columns which will be used with my local LightSwitch client. There is a lot of improvement alone from the portal/tool standpoint in the new Windows Azure. Now I am done with Azure side.

image

Next, I create a LightSwitch project and link to the external SQL Azure database has been created above. In the SQL Azure management portal, I can get the connection strings. It provide several types of connection strings, but what I need is only the protocol, server name and port in ADO.NET connection string. My database is displayed in the screen below after the server and login information are added. I can now select the Blog table that has been created with SQL Azure management portal.

image

image

In the LightSwitch Data designer, I now see Blog table. To utilize LightSwitch built-in specific URL validation, I can change the data type of the Url to Web Address, so LightSwitch can provide me more specific validation for this field. In this example, I create a screen using Editable Grid Screen template which creates a simple editable grid layout. LightSwitch also provides a designer allowing me to modify the screen layout.

image

image

image

My sample application is basically done. There are several ways to publish a LightSwitch application. In this post, I publish the LightSwitch application as a local desktop application. I can deploy my application as a web (Silverlight) application and let Windows Azure hosts it too. (Windows Azure SDK has to be installed.)

Once I deploy and install the application on my machine, I can now add the records to the Blog table.

image

Now, I go back to SQL Azure management portal, and I will see the record that I just added.

image

As you see, this is very effortless and no code at all. In few minutes, I now have a local Silverlight application that talks with SQL Azure database. Hosting database in the cloud also allows you to focus and enjoy more on the application itself instead of worrying about setting up a server, networking, OS, database, and so on!

Easy SVG with Raphaël–JavaScript Library

About seven years ago, I was assigned to create a customized interactive timeline chart (similar to Timeline control Telerik provides) for one of our project at my work. At that time, there was not much choice. Canvas did not exist. VML or SVG was not a good choice either if you want cross-browser support.

I pretty much had to rely on using PHP to create an image of the chart on the server-side, and then use <image map> and some JavaScript to show/hide <div> element, so a user can mouse over the chart element and get some information.

Two years ago, I joyfully re-implemented and improved the chart by using Silverlight (our shop moved from PHP to .NET two years earlier).  Then something happened, and our users keep asking why my Silverlight chart wouldn’t work with the thing. 🙂 Microsoft also moved on and commit to HTML5 as a true cross-platform solution.

Anyway, enough with the history, let’s see how Raphaël can help me. The best thing about Raphaël is that it supports **most** browsers including IE 6, 7, and 8 which do not support SVG. For Firefox 3+, IE9, and Chrome, Raphaël generates normal XVG while Raphaël uses VML for IE 6-8.

To start using Raphaël, you just download js files from Raphaël site. For Visual Studio user, it is even easier as you can nuGet it, and all of required files will be there for you.

image

image

Let’s look at sample code in jsfiddle.

var canvas = Raphael("raphael-canvas", 320, 200);                       
cir = canvas.circle(50, 50, 10);
cir.attr("fill", "#f0f");
cir.attr("stroke", "#f0f");
glowSet = cir.glow({color: "#0ff"});

$('#clear-glow').click(function ()
{
  glowSet.remove();                               
    cir.animate({cx: 100, "stroke-width": 2, fill: "#0ff"}, 1000);
});

image

I start by creating a Raphaël canvas in the pre-defined <div/> in HTML body. The sample shows how I create a circle with Fuchsia background. I also make it glow with simple glow() function. The last part is to add some animation with easing using Raphaël API. You can run the sample code via jsfiddle and see how it works.

Enjoy coding!