How To Use Java Packages In .Net

Gallery

Ray Yagubyan

Ray Yagubyan

Introduction

In this tip, I am going to describe how to use Java Packages in .NET using IKVM.NET. In my previous tip, I have briefly described all about IKVM.NET. So before reading this tip, you can refer to that one. IKVM.NET provides this facility with the help of OpenJDK Project.

Using the Code

So for using IKVM.NET library, first of all you have to download it from here. After downloading IKVM.NET , unzip the file. You can see the following folders and files inside unzip file.

Now suppose you are creating a project  in C#.NET and you want to use Java packages in this project, then we need to add reference of the package which is required. For each package, there is a separate DLL file so you can add any package.

As you can see in the above image, there are lots of packages present as DLL file so you can add references of the required packages.

Here, I am going to use GZIP Compression class present in Java.util.zip package of Java. I know all of you have a question now, why I am using GZIP compression of Java while it presents in .NET already. So the reason behind that is GZIP compression provided by Java is better than .NET.

Let’s see how to use it. So here we need to add IKVM.OpenJDK.Util.dll and IKVM.OpenJDK.Code.dll because  GZIPOutputStream class is present in  IKVM.OpenJDK.Util package and FileInputStream class which is required for file manipulation is present in Java.io that resides in IKVM.OpenJDK.Code package.

Collapse | Copy Code
using java.io;
using java.util.zip;
namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            string srcfile="c:\\source.txt";
            string dstfile="c:\\destination.txt";

            FileInputStream fin = new FileInputStream(srcfile);
            GZIPOutputStream fout = new GZIPOutputStream(new FileOutputStream(dstfile));
            byte[] buffer = new byte[1024];
            int bytesRead;

            while ((bytesRead = fin.read(buffer)) != -1) //srcfile.getBytes()
            {

                System.Console.WriteLine(bytesRead);
                fout.write(buffer, 0, bytesRead);
            }

            fin.close();
            fout.close();

            //CompressStringToFile(dstfile, srcfile);
        }      
    }
}

So as you can see in the above code by using IKVM.NET, we can use any Java package very easily without any overhead. You can use the same code that you have used in Java.

Points of Interest

You can use many powerful facilities that are provided by Java packages, without any overhead. In this tip, I am using a very simple utility of Java but if you want, you can use it accordingly and find it more useful later on.

Survey Web App using ASP.Net MVC 4, Entity Framework 5

Standard

83cb5-ray-yagubyan

Introduction

A survey application using ASP.NET MVC 4, Entity Framework 5 and SimpleMembership.

Azure Benefit

I believe that Azure can help in simplifying the deployment process using the Publish Profile within Visual Studio 2012. I don’t have to worry about configuring the database and website to play nice… Azure just takes care of it.

Background

I work for a consulting company and noticed that we send out Excel documents with simple questions for the client to fill out. But what if we just sent them a link and they login using Google, Twitter or Facebook? What if…

The database design is based from this Stack Overflow question/answer: http://stackoverflow.com/questions/540885/db-design-survey-quiz-with-questions-and-answers

It will likely morph as the project moves along. I decided against using “Code First” database design as I found it easier to generate the tables within SQL Server Management Studio and then have Entity Framework generate my Models.

I know there are some .NET OpenSource survey projects out there. But nothing has been updated within those projects in the past few years. I’m looking to create something that is flexible, secure and easy to use.

Using the code

This is a work in progress… I will upload the script to create the database and also the important pieces of code.

Source Control…because we can

First, let’s create a new project in source control using Team Foundation Server (TFS) at tfs.visualstudio.com … it’s free and all you will need is a Microsoft  Account (Windows Live ID). You can create a Microsoft Account here https://signup.live.com/signup.aspx?lic=1 Note: All steps were completed using Internet Explorer 10 . 

  1. Go to http://tfs.visualstudio.com/
  2. Click “Sign up for free” in the upper right or click the “Sign In” if you already have an account
  3. Create your unique Account URL by entering your choice into the text box … you can make it easy and just use your first name and last name.
  4. Click the “Create Account” button.
  5. You will be redirected to sign in using your Microsoft Account.
  6. Once logged in the Team Foundation Service homepage is displayed. Click the “New Team Project” button on the left.

Create Project in TFS

  1. Enter a Project Name (ie: MySurveyProject)
  2. Enter a Description (optional)
  3. Select your Process template (I kept the default of Microsoft Visual Studio Scrum 2.2)
  4. Select Version control  (again, leave the default Team Foundation Version Control)
  5. Click the Create Project button
  6. After the project is created click the Navigate to Project button
  7. Under Activities click Open a new instance of Visual Studio
  8. Click Allow on the popup… it’s just making sure you want the webpage to open the application (Visual Studio)
  9. Enter your Microsoft Account credentials to complete the connection to Team Foundation Server
  10. Congratulations! You have successfully created a new project in TFS and configured Visual Studio to connect to your project. Now… let’s create a new ASP.NET MVC 4 Web application.

Create ASP.NET MVC 4 Web Application

  1. Back to your newly opened instance of Visual Studio. From the Start Page click the New Project… link.
  2. Select the ASP.NET MVC 4 Web Application project
  3. Enter MySurvey in the Name textbox.
  4. Make sure the checkbox is ticked for Create directory for Solution and Add to source control
  5. Make sure the checkbox for Create a unit test project is ticked. Leave the View engine as Razor
  6. Leave the defaults for the Add Solution MySurvey to Source Control and click the OK button.
  7. The web application has been created but it has not been uploaded/saved to TFS. Once the project is done loading click VIEW -> Team Explorer. Then click the Pending Changes link. Enter Initial check-in in the Comment field.
  8. Click the Check In button above the comment field.
  9. Click Yes to the Check-in Confirmation dialog box. Your first check-in will take the longest because you are checking in everything. Future check-in’s won’t take as long as you will only be checking in a few files at a time.
  10. Press F5 to build and see your new ASP.NET MVC 4 Web Application. Now, let’s make some quick changes to it and get it deployed to Azure Websites.

Update header and page title

 

  1. Within the MySurvey project expand the Views folder then the Shared folder. Double click and open _Layout.cshtml
  2. On line 15 change the text from “your logo here” to “MySurvey“. This will change the text in the upper left of all pages to read MySurvey
  3. _Layout.cshtml is referenced on all pages and allows you to make quick site wide changes easily.
  4. Now lets update the homepage title. Open the HomeController.cs in the Controller folder.
  5. Add the following line in the “ActionResult Index()” function   ViewBag.Title = “MySurvey HomePage”;
  6. The whole thing should look like this:
Collapse | Copy Code
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
ViewBag.Title = "MySurvey HomePage";
return View();
}

Now run the web application. When the page is displayed it still says “Homepage” when it should say “MySurvey HomePage”. What gives?

Well the Title property is currently set on the view. Let’s open up the view and comment out that line.

 

  1.  Expand the View folder then the Home folder. Open up the Index.cshtml file.
  2.  Comment out line two. Should look like this
Collapse | Copy Code
@{
//ViewBag.Title = "Home Page";
}

Now run the web application. The title is correct! I show you this just to get a little more comfortable around ASP.NET MVC. Now that we know how to make simple changes and our default ASP.NET MVC Web App is now customized (a little Smile | <img src= ” />  let’s go create an account on Windows Azure, create a website and then deploy to that website.

Sign up for Windows Azure

 

  1. Go to http://www.windowsazure.com
  2. Sign up for a free 90 trial using your Microsoft Account you used for TFS.

Create Azure Website

 

Now that you have successfully created a Windows Azure account, let’s create a website that we can deploy our ASP.NET MVC 4 Web Application to.

 

  1.  Once logged into the Windows Azure Portal click the New button in the lower left then Compute -> Website -> Custom Create 
  2. Enter a URL and select the Region that is closest to you. Under Database select Create a new SQL Database. Leave the DB Connection String Name as DefaultConnection. Make sure to tick the checkbox Publish from source control. (I knew there was a reason we were putting this into Source Control). Click the “Next” arrow.
  3. Database settings. I usually leave the default database name. I don’t know if Microsoft is practicing “security through obscurity” or if they just randomize the name to avoid name conflicts. In the Server dropdown select New SQL database server.  Enter a username and password. I like to use http://correcthorsebatterystaple.net/ to generate passwords. Again I select the region that is closest to me. Click the “Next” arrow.
  4. Where is your source code? Select Team Foundation Server and click the “Next” arrow.
  5. Enter the URL to TFS that you created earlier. And click the Authorize Now button/arrow.
  6. A new window will be displayed asking if it’s “OK” if Windows Azure connects to TFS. Click the green Accept button.
  7. Choose a repository to deploy page. Select the MySurveyProject under the Repository Name drop down list. Then click the “Check mark”.
  8. Your website will be displayed in the portal and the status will be “Creating”. Once complete it will say “Running” and the URL will be displayed. Click on the URL to view your site. You will see the default Windows Azure Web Site.

And you are thinking to yourself, “Self, we told Azure to use source control for deployment… why don’t we see our awesome ASP.NET MVC 4 website?”  Let’s go take a look at the Windows Azure Portal and see what’s going on.

If you log into the portal and click on your newly created website you will see the “Quick start” screen. At the bottom of that screen click the View deployments link under the Integrate  source control heading. I SPY!

The website will deploy automatically when we check-in some code. Remember those files we edited? We never checked those in! Let’s get to it.

Check-in and Engage Deploy!

I apologize for the Star Trek reference, couldn’t resist. Back on track…

 

  1.  Go back to Visual Studio 2012 and view Team Explorer (View -> Team Explorer). If it doesn’t show the Pending Changes section click the “Home” button at the top and then click the Pending Changes link.
  2. Enter a comment. You can see I entered “Updated homepage title”. Click the “Check In” button
  3. Confirm the check-in.
  4. Now go back to Windows Azure Portal. Click on your website and go to the Deployments section. It may take a minute or two… but it will automatically show that it is deploying.
  5. And once the deployment is complete it will tell you that it is the Active Deployment.
  6. Go to your website now. (You may have to hold down the Shift key while you click the refresh button. Doing this pulls directly from the server and not from cache.) You should now see your ASP.NET MVC 4 website.

That was the easy stuff. Let’s add a database.

Ten Caching Mistakes That Break Your App

Standard

Ray Yagubyan

Ray Yagubyan

Introduction

Caching frequently used objects, that are expensive to fetch from the source, makes application perform faster under high load. It helps scale an application under concurrent requests. But some hard to notice mistakes can lead the application to suffer under high load, let alone making it perform better, especially when you are using distributed caching where there’s separate cache server or cache application that stores the items. Moreover, code that works fine using in-memory cache can fail when the cache is made out-of-process. Here I will show you some common distributed caching mistakes that will help you make better decisions when to cache and when not to cache.

Here are the top 10 mistakes I have seen:

  1. Relying on .NET’s default serializer
  2. Storing large objects in a single cache item
  3. Using cache to share objects between threads
  4. Assuming items will be in cache immediately after storing them
  5. Storing entire collection with nested objects
  6. Storing parent-child objects together and also separately
  7. Caching Configuration settings
  8. Caching Live Objects that have open handle to stream, file, registry, or network
  9. Storing same item using multiple keys
  10. Not updating or deleting items in cache after updating or deleting them on persistent storage

Let’s see what they are and how to avoid them.

I am assuming you have been using ASP.NET Cache or Enterprise Library Cache for a while, you are satisfied, now you need more scalability and have thus moved to an out-of-process or distributed cache like Velocity or Memcache. After that, things have started to fall apart and thus the common mistakes listed below apply to you.

Relying on .NET’s Default Serializer

When you use an out-of-process caching solution like Velocity or memcached, where items in cache are stored in a separate process than where your application runs; every time you add an item to the cache, it serializes the item into byte array and then sends the byte array to the cache server to store it. Similarly, when you get an item from the cache, the cache server sends back the byte array to your application and then the client library deserializes the byte array into the target object. Now .NET’s default serializer is not optimal since it relies on Reflection which is CPU intensive. As a result, storing items in cache and getting items from cache add high serialization and deserialization overhead that results in high CPU, especially if you are caching complex types. This high CPU usage happens on your application, not on the cache server. So, you should always use one of the better approaches shown in this article so that the CPU consumption in serialization and deserialization is minimized. I personally prefer the approach where you serialize and deserialize the properties all by yourself by implementing ISerializable interface and then implementing the deserialization constructor.

Collapse | Copy Code
[Serializable]
    public class Customer : ISerializable
    {
        public string FirstName;
        public string LastName;
        public int Salary;
        public DateTime DateOfBirth;

        public Customer()
        {
        }

        public Customer(SerializationInfo info, StreamingContext context)
        {
            FirstName = info.GetString("FirstName");
            LastName = info.GetString("LastName");
            Salary = info.GetInt32("Salary");
            DateOfBirth = info.GetDateTime("DateOfBirth");
        }

        #region ISerializable Members

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("FirstName", FirstName);
            info.AddValue("LastName", LastName);
            info.AddValue("Salary", Salary);
            info.AddValue("DateOfBirth", DateOfBirth);
        }

        #endregion        
    }

This prevents the formatter from using reflection. The performance improvement you get using this approach is sometimes 100 times better than the default implementation when you have large objects. So, I strongly recommend that at least for the objects that are cached, you should always implement your own serialization and deserialization code and not let .NET use Reflection to figure out what to serialize.

Storing Large Objects in a Single Cache Item

Sometimes we think large objects should be cached because they are too expensive to fetch from the source. For example, you might think caching an object graph of 1 MB might give you better performance than loading that object graph from file or database. You would be surprised how non scalable that is. It will certainly work a lot faster than loading the same thing from database when you have only one request at a time. But under concurrent load, frequent access to that large object graph will blow up server’s CPU. This is because Caching has high serialization and deserialization overhead. Every time you will try to get an 1 MB object graph from an out of process cache, it will consume significant CPU to build that object graph in memory.

Collapse | Copy Code
var largeObjectGraph = myCache.Get("LargeObjectGraph");
var anItem = 
    largeObjectGraph.FirstLevel.SecondLevel.ThirdLevel.FourthLevel.TheItemWeNeed;

Solution is not to cache the large object graph as a single item in the cache using a single key. Instead you should break that large object graph into smaller items and then cache those smaller items individually. You should only retrieve from cache the smallest item you need.

Collapse | Copy Code
// store smaller parts in cache as individual item
var largeObjectGraph = new VeryLargeObjectGraph();
myCache.Add("LargeObjectGraph.FirstLevel.SecondLevel.ThirdLevel", 
  largeObjectGraph.FirstLevel.SecondLevel.ThirdLevel);
...
...
// get the smaller parts from cache
var thirdLevel = myCache.Get("LargeObjectGraph.FirstLevel.SecondLevel.ThirdLevel");
var anItem = thirdLevel.FourthLevel.TheItemWeNeed;

The idea is to look at the items that you need most frequently from the large object (say the connection strings from a configuration object graph) and store those items separately in the cache. Always keep in mind that the item that you retrieve from cache is always small, say max 8 KB.

Using Cache to Share Objects Between Multiple Threads

Since you can access cache from multiple threads, sometimes you use it to conveniently pass data between multiple threads. But cache, like static variables, can suffer from race conditions. It’s even more common when the cache is distributed since storing and reading an item requires out-of-process communication and your threads get more chance to overlap on each other than in-memory cache. The following example shows how in-memory cache rarely demonstrates the race condition but an out-of-process cache almost always shows it:

Collapse | Copy Code
myCache["SomeItem"] = 0;

var thread1 = new Thread(new ThreadStart(() =>
{
    var item = myCache["SomeItem"]; // Most likely 0
    item ++;
    myCache["SomeItem"] = item;
});
var thread2 = new Thread(new ThreadStart(() =>
{
    var item = myCache["SomeItem"]; // Most likely 1
    item ++;
    myCache["SomeItem"] = item;
});
var thread3 = new Thread(new ThreadStart(() =>
{
    var item = myCache["SomeItem"];  // Most likely 2
    item ++;
    myCache["SomeItem"] = item;
});

thread1.Start();
thread2.Start();
thread3.Start();
.
.
.

The above code most of the time demonstrates the most likely behavior when you are using in-memory cache. But when you go out-of-process or distributed, it will always fail to demonstrate the most-likely behavior. You need to implement some kind of locking here. Some caching provider allows you to lock an item. For example, Velocity has locking feature, but memcache does not. In Velocity, you can lock an item:

Collapse | Copy Code
// get an item and lock it
DataCacheLockHandle handle;
SomeClass someItem = _defaultCache.GetAndLock("SomeItem", 
   TimeSpan.FromSeconds(1), out handle, true) as SomeClass;
// update an item
someItem.FirstName = "Version2";
// put it back and get the new version
DataCacheItemVersion version2 = _defaultCache.PutAndUnlock("SomeItem", 
    someItem, handle);

You can use locking to reliably read and write to cache items that get changed by multiple threads.

Assuming Items will be in Cache Immediately After Storing It

Sometimes you store an item in cache on a submit button click and assume that upon the page postback, the item can be read from cache because it was just stored in cache. You are wrong.

Collapse | Copy Code
private void SomeButton_Clicked(object sender, EventArgs e)
{
  myCache["SomeItem"] = someItem;
}

private void OnPreRender()
{
  var someItem = myCache["SomeItem"]; // It's gone dude!
  Render(someItem);
}

You can never assume an item will be in cache for sure. Even if you are storing the item in Line 1 and reading it from Line 3. When your application is under pressure and there’s a scarcity of physical memory, cache will flush out items that aren’t frequently used. So, by the time code reaches Line 3, cache could be flushed out. Never assume you can always get an item back from cache. Always have a null check and retrieve from persistent storage.

Collapse | Copy Code
var someItem = myCache["SomeItem"] as SomeClass ?? GetFromSource();

You should always use this format when reading an item from cache.

Storing Entire Collection with Nested Objects

Sometimes you store an entire collection in a single cache item because you need to access the items in the collection frequently. Thus every time you try to read an item from the collection, you have to load the collection first and then read that particular item. Something like this:

Collapse | Copy Code
var products = myCache.Get("Products");
var product = products[1];

This is inefficient. You are unnecessarily loading an entire collection just to read a certain item. You will have absolutely no problem when the cache is in-memory, as the cache will just store a reference to the collection. But in a distributed cache, where the entire collection is deserialized every time you access it, it will result in poor performance. Instead of caching a whole collection, you should cache individual items separately.

Collapse | Copy Code
// store individual items in cache
foreach (Product product in products)
  myCache.Add("Product." + product.Index, product);
...
...
// read the individual item from cache
var product = myCache.Get("Product.0");

The idea is simple, you store each item in the collection individually using a key that can be guessed easily, for example using the index as a padding.

Storing Parent-child Objects Together and Also Separately

Sometimes you store an object in cache that has a child object, which you also separately store in another cache item. For example, say you have a customer object that has an order collection. So, when you cache customer, the order collection gets cached as well. But then you separately cache the individual orders. So, when an individual order is updated in cache, the orders collection containing the same order inside the customer object is not updated and thus gives you inconsistent result. Again this works fine when you have in-memory cache but fails when your cache is made out-of-process or distributed.

Collapse | Copy Code
var customer = SomeCustomer();
var recentOrders = SomeOrders();
customer.Orders = GetCustomerOrders();
myCache.Add("RecentOrders", recentOrders);
myCache.Add("Customer", customer);
...
...
var recentOrders = myCahce.Get("RecentOrders");
var order = recentOrders["ORDER10001"];
order.Status = CANCELLED; 
...
...
...
var customer = myCache.Get("Customer");
var order = customer.Orders["ORDER10001"];
order.Status = PROCESSING; // Inconsistent. The order has already been cancelled

This is a hard problem to solve. It requires clever design so that you never end up having the same object stored twice in the cache. One common approach is not to store child objects in cache, instead store keys of child object so that they can be retrieved from cache individually. So, in the above scenario, you would not store the customer’s order collection in cache. Instead you will store the OrderID collection with Customer and then when you need to see the orders of a customer, you try to load the individual order object using the OrderID.

Collapse | Copy Code
var recentOrders = SomeOrders();
foreach (Order order in recentOrders)
   myCache.Add("Order." + order.ID, order);
...
var customer = SomeCustomer();
customer.OrderKeys = GetCustomerOrders(); // Store keys only
myCache.Add("Customer", customer);
...
...
var order = myCache.Get["Order.10001"];
order.Status = CANCELLED; 
...
...
...
var customer = myCache.Get("Customer");
var customerOrders = customer.OrderKeys.ConvertAll<string, Order>
   (key => myCache.Get("Order." + key));
var order = customerOrders["10001"]; // Correct object from cache

This approach ensures that a certain instance of an entity is stored in the cache only once, no matter how many times it appears in collections or parent objects.

Caching Configuration Settings

Sometimes you cache configuration settings. You use some cache expiration logic to ensure the configuration is refreshed periodically or refreshed when the configuration file or database table changes. Since configuration settings are access very frequently, reading them from cache adds significant CPU overhead. Instead you should just use static variables to store configurations.

Collapse | Copy Code
var connectionString = myCache.Get("Configuration.ConnectionString");

You should not follow such an approach. Getting an item from cache is not cheap. It may not be as expensive as reading from a file or registry. But it’s not very cheap either, especially if the item is a custom class that adds some serialization overhead. So, you should instead store the configuration settings in static variables. But you might ask, how do we refresh configuration without restarting appdomain when it’s stored in static variable? You can use some expiration logic like file listener to reload the configuration when configuration file changes or use some database polling to check for database update.

Caching Live Objects that have Open File, Registry or Network Handle

I have seen developers cache instance of classes which hold open connection to file, registry or external network connection. This is dangerous. When items are removed from cache, they aren’t disposed automatically. Unless you dispose such class, you leak system resource. Every time such a class instance is removed from cache due to expiration or some other reason without being disposed, it leaks the resources it was holding onto.

You should never cache such objects that hold open streams, file handles, registry handles or network connections just because you want to save opening the resource every time you need them. Instead you should use some static variable or use some in-memory cache that is guaranteed to give you expiration callback so that you can dispose them properly. Out of process caches or session stores do not give you expiration callback consistently. So, never store live objects there.

Storing Same Item using Multiple Keys

Sometimes you store objects in cache using the key and also by index because you not only need to retrieve items by key but also need to iterate through items using index. For example,

Collapse | Copy Code
var someItem = new SomeClass();
myCache["SomeKey"] = someItem;
.
.
myCache["SomeItem." + index] = someItem;
.
.

If you are using in-memory cache, the following code will work fine:

Collapse | Copy Code
var someItem = myCache["SomeKey"];
someItem.SomeProperty = "Hello";
.
.
.
var someItem = myCache["SomeItem." + index];
var hello = someItem.SomeProperty; // Returns Hello, fine, when In-memory cache
/* But fails when out of process cache */

The above code works when you have in-memory cache. Both of the items in the cache are referring to the same instance of the object. So, no matter how you get the item from cache, it always returns the same instance of the object. But in an out-of-process cache, especially in a distributed cache, items are stored after serializing them. Items aren’t stored by reference. Thus you store copies of items in cache, you never store the item itself. So, if you retrieve an item using a key, you are getting a freshly made copy of that item as the item is deserialized and created fresh every time you get it from cache. As a result, changes made to the object never reflects back to the cache unless you overwrite the item in the cache after making the changes. So, in a distributed cache, you will have to do the following:

Collapse | Copy Code
var someItem = myCache["SomeKey"];
someItem.SomeProperty = "Hello";
myCache["SomeKey"] = someItem; // Update cache
myCache["SomeItem." + index] = someItem; // Update all other entries
.
.
.
var someItem = myCache["SomeItem." + index];
var hello = someItem.SomeProperty; // Now it works in out-of-process cache

Once you update the cache entry using the modified item, it works as the items in the cache receive a new copy of the item.

Not Updating or Deleting Objects from Cache when Items are Updated or Deleted from Data Source

This again works in in-memory cache, but fails when you go to out-of-process/distributed cache. Here’s an example:

Collapse | Copy Code
var someItem = myCache["SomeItem"];
someItem.SomeProperty = "Hello Changed";
database.Update(someItem);
.
.
.
var someItem = myCache["SomeItem"];
Console.WriteLine(someItem.SomeProperty); // "Hello Changed"? Nope.

This works fine in an in-memory cache, but fails when it’s out-of-process or distributed cache. The reason is you changed the object but never updated the cache with the latest object. Items in cache are stored as a copy, not the original instance.

Another mistake is not deleting items from cache when the item is deleted from the database.

Collapse | Copy Code
var someItem = myCache["SomeItem"];
database.Delete(someItem);
.
.
.
var someItem = myCache["SomeItem"];
Console.WriteLine(someItem.SomeProperty); // Works fine. Oops!

Don’t forget to delete items from cache, all possible ways it has been stored in cache, when you delete an item from database, file or some persistent store.

Conclusion

Caching requires careful planning and clear understanding of the data being cached. Otherwise when cache is made distributed, it not only performs worse but can also fail the code. Keeping these common mistakes in mind while caching will help you cash out from your code.

Building your own Windows Runtime components to deliver great Metro style apps

Standard

 

 

For Windows 8, we completely reimagined the platform, allowing you to choose the programming language and technologies you already know to build apps tailored to the device and form factor. With the Windows Runtime, you can even easily use multiple languages within a single app. You can build a great Metro style app with HTML and JavaScript that can interact with the Xbox 360 controller through building your own Windows Runtime component in C++. You can build reusable XAML controls exposed via Windows Runtime components that are instantly consumable by Metro style apps written in both C++ and C#. Essentially, we have let you build apps on the Windows 8 platform using the languages of your choice with no comprises.

In this blog post, we talk about what you need to know to build your own Windows Runtime components.

The basics

The Windows Runtime is at the heart of empowering language choice. It exposes so that you can call them from JavaScript, C++, C# and Visual Basic in a way that’s natural and familiar. This same foundation is available to you when building your own APIs too.

A Windows Runtime component that you build and package in your app is typically referred to as a 3rd party Windows Runtime component. This differs from 1st party components that are already part of the Windows 8 platform. You can write these 3rd party Windows Runtime components in C++, C# or Visual Basic. You can call into the APIs they expose from anywhere, including other Windows Runtime components packaged into your app. You can also call into the APIs exposed via Windows Runtime components from any language.

The Windows Runtime components that you write for your app can use Windows Runtime APIs, Win32, COM, .NET APIs or 3rd party libraries as long as they are supported for Metro style app development. Note that the Windows Runtime components that you build are different from what you traditionally know as C++ DLLs or .NET assemblies that expose APIs. Creating a class library in .Net or a standalone DLL in C++ is not the same as building a Windows Runtime component. Windows Runtime components are declared in .wnmd files that expose Windows Runtime metadata and enable languages such as JavaScript to naturally consume Windows Runtime APIs (for example, pascalCasedNames support for APIs exposed to JavaScript). The Windows Runtime metadata also enables Visual Studio to provide great tooling capabilities such as IntelliSense support.

Why build your own Windows Runtime components

Creating Windows Runtime components can help you architect for reusability and language interoperability. Let’s take a look at some app scenarios that showcase how you can use 3rd party Windows Runtime components to build better experiences.

    Figure1: Xbox 360 Controller

Using Win32 and COM APIs in your Metro style app

The platform provided by Internet Explorer 10 enables you to create great Metro style app experiences using HTML, CSS and JavaScript. But what if you have built a game using HTML5 canvas and want to integrate with the Xbox 360 controller for Windows? The XInput API, which allows apps to receive input from the controller, exposes Win32 APIs that are not available directly to JavaScript.

This is a great example of where creating a Windows Runtime component can solve this problem and give you the ability to use the XInput APIs in your HTML based Metro style app. The XInput and JavaScript controller sketch sample showcases exactly that. The sample app contains a game controller Windows Runtime component written in C++ which wraps the functionality exposed by the XInput APIs. The controller sketch HTML-based app uses the game controller C++ Windows Runtime component to enable the interaction with the Xbox 360 controller.

This scenario, impossible to accomplish using HTML and JavaScript alone, is a perfect example of where creating a 3rd party Windows Runtime component allows you to complete a complex scenario that you otherwise wouldn’t be able to.

Computationally Intensive Operations

Apps created for fields like science, engineering, and maps/geography often have computationally intensive operations. These intensive operations typically require powerful parallel processing and are well suited for C++ to achieve optimal performance. In Developing Bing Maps Trip Optimizer, a Metro style app in JavaScript and C++ , we see another scenario where creating a Windows Runtime component in C++ allows us to create the best experience in our app.

You wonder why anyone would want to calculate a trip route on local data at all when we could run this computationally intensive task in the cloud on Bing servers. Bing Maps exposes JavaScript APIs to do this, but sometimes an app must run offline. And we also want the user to drag and change the route in real time with touch. If we can run these intense operations locally, we create an even better experience.

By writing our compute-intensive operation in C++ using the parallel task library, we can harness the power of the client to create a great experience for users. Windows Runtime is a great fit for this scenario, allowing us to create our rich client User Interface (UI) in HTML and JavaScript with the Bing Maps AJAX control while running all of our intensive route operations using C++ code that calculates quickly using parallelization.

Libraries

The community is filled with great libraries that developers put together and shared for everyone to use. In the past, you may have found it challenging to reuse some of these libraries if they didn’t match the programming language your app was implemented in. For example, you built a great .NET app, but couldn’t use a library written in C++ without going through painful interop hoops like PInvoke.

Windows Runtime bridges the language gap in Windows 8, making it possible for a single Windows Runtime component library with a single code base to reach a broader set of developers irrespective of the component’s language or your app’s primary programming language.

You can now create a single Windows Runtime-exposed XAML library of custom controls that both C++ and C# app developers can consume. And you can use various data storage Windows Runtime libraries shared out by developers in your XAML or HTML based Metro style apps. All of these scenarios are possible without the burden of writing any interop code.

We think Windows Runtime will be a boon to the libraries that developers create and share broadly for the community of Metro style app developers. Let’s now take a look at two concrete examples showing the basics of building a 3rd party Windows Runtime component in C++/CX and C#.

Scenario 1: Enhancing your app with native audio

Say we are building a software synthesizer app using XAML backed by app logic written in C#. To add filter support to our music app, we would like to use XAudio to have direct control of audio buffers.

Adding the Windows Runtime component to our solution

Using Visual Studio, we add a new C++ Windows Runtime component project to our existing solution. This Windows Runtime component wraps the music processing functionality:

Figure 2: Adding a new C++ Windows Runtime Component

Visual Studio created a C++ project for us to expose APIs for which the implementation will be packaged in a DLL and the Windows Runtime metadata in a winmd file. Both are made available to our C# project.

Defining the class exposed to our XAML C# project

We use C++/CX to build the APIs that will be exposed to our C# project, but you also can use the Windows Runtime C++ Template Library (WRL). We start by defining a fairly basic class to encapsulate the XAudio functionality:

XAudioWrapper.h

#pragma once #include “mmreg.h” #include< vector> #include <memory> namespace XAudioWrapper { public ref class XAudio2SoundPlayer sealed { public: XAudio2SoundPlayer(uint32 sampleRate); virtual ~XAudio2SoundPlayer(); void Initialize(); bool PlaySound(size_t index); bool StopSound(size_t index); bool IsSoundPlaying(size_t index); size_t GetSoundCount(); void Suspend(); void Resume(); private: interface IXAudio2* m_audioEngine; interface IXAudio2MasteringVoice* m_masteringVoice; std::vector<std::shared_ptr<ImplData>> m_soundList; }; }

You will first notice the usage of the public, ref and sealed keywords in the class declaration. For a class to be instantiated from another language such as JavaScript or C# in a Metro style app, the class must be declared as public ref class sealed.

The public functionality (methods, properties …) of the class are limited to C++ built-in types or Windows Runtime types. Those are the only types allowed for crossing the language boundary in Windows Runtime components. That being said, you can use the regular C++ library (i.e.: Standard Template Library collections) for the private data members of your class as shown in this code snippet. Those private data members don’t have to follow the rules associated with crossing the language boundary. The Visual Studio compiler emits error messages and provides guidance if you use unsupported constructs.

Implementing the class exposed in our Windows Runtime component

Now that we have defined the basic interface for our class, let’s take a look at some of the implemented methods:

XAudioWrapper.cpp

XAudio2SoundPlayer::XAudio2SoundPlayer(uint32 sampleRate) : m_soundList() { // Create the XAudio2 engine UINT32 flags = 0; XAudio2Create(&m_audioEngine, flags); // Create the mastering voice m_audioEngine->CreateMasteringVoice( &m_masteringVoice, XAUDIO2_DEFAULT_CHANNELS, sampleRate ); } void XAudio2SoundPlayer::Resume() { m_audioEngine->StartEngine(); } bool XAudio2SoundPlayer::PlaySound(size_t index) { // // Setup buffer // XAUDIO2_BUFFER playBuffer = { 0 }; std::shared_ptr<ImplData> soundData = m_soundList[index]; playBuffer.AudioBytes = soundData->playData->Length; playBuffer.pAudioData = soundData->playData->Data; playBuffer.Flags = XAUDIO2_END_OF_STREAM; HRESULT hr = soundData->sourceVoice->Stop(); if (SUCCEEDED(hr)) { hr = soundData->sourceVoice->FlushSourceBuffers(); } // // Submit the sound buffer and (re)start (ignore any ‘stop’ failures) // hr = soundData->sourceVoice->SubmitSourceBuffer(&playBuffer); if (SUCCEEDED(hr)) { hr = soundData->sourceVoice->Start(0, XAUDIO2_COMMIT_NOW); } return SUCCEEDED(hr); }

In this code snippet, we are just using the XAudio2 COM APIs available for Metro style app development to wire up our audio engine, play sound and resume the engine. Additionally, we can use C++ constructs and types beyond just the Windows Runtime types to implement the necessary functionality.

Adding and consuming the Windows Runtime component

After we define and implement our basic class, we use Visual Studio to add the XAudioWrapper Windows Runtime component to our C++ project from our C# project:

Figure 3: Adding the XAudioWrapper Windows Runtime Component to our music app

As a result, the class that we expose from our C++ project becomes available to our C# project:

MainPage.cs

using XAudioWrapper; namespace BasicSoundApp { public sealed partial class MainPage : Page { XAudio2SoundPlayer _audioPlayer = new XAudio2SoundPlayer(48000); public MainPage() { this.InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { _audioPlayer.Initialize(); } private void Button_Click_1(object sender, RoutedEventArgs e) { _audioPlayer.PlaySound(0); } } }

As shown in the code snippet, we can interact with our XAudio wrapper from C# just as if it were a regular .NET component. We reference its namespace, instantiate the component and start invoking the various methods it exposes. All of this without requiring any DllImports to call into the native code!

Scenario 2: Using built-in APIs to open a zip file from your app

Say we are also building a file viewer app using HTML and want to add functionality to allow users of this app to pick zip files. We want to use the APIs already built-into Windows and exposed in the .NET platform for handling zip files.

Adding the Windows Runtime component to our solution

This is the same step as we have described for our music app, but we now pick the C# Windows Runtime component to wrap the zip processing functionality:

Figure 4: Adding a new C# Windows Runtime Component

Visual Studio has created a C# project for us to expose the APIs for which both the implementation and Windows Runtime metadata are packaged in a .winmd file and made available to our web project.

Implementing the class exposed in our Windows Runtime component

We use C# to build the APIs that will be exposed to our web project, but you can also use Visual Basic. We start by defining a simple C# class to encapsulate the zip functionality:

ZipWrapper.cs

using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.Foundation; using Windows.Storage; public sealed class ZipWrapper { public static IAsyncOperationWithProgress<IList<string>, double> EnumerateZipFileAsync(StorageFile file) { return AsyncInfo.Run(async delegate( System.Threading.CancellationToken cancellationToken, IProgress<double> progress) { IList<string> fileList = new List<string>(); progress.Report(0); using (var stream = await file.OpenStreamForReadAsync()) { using (var archive = new ZipArchive(stream)) { for (int i = 0; i < archive.Entries.Count; i++) { // add code for processing/analysis on the file // content here // add to our list and report progress fileList.Add(archive.Entries[i].FullName); double progressUpdate = ((i + 1) / ((double)archive.Entries.Count)) * 100; // percentage progress.Report(progressUpdate); } } } progress.Report(100.0); return fileList; }); } }

This class is public and sealed. Similarly to building C++ Windows Runtime components, this is necessary for other languages to instantiate the class. The static method exposed in the class uses a mixture of Windows Runtime types (such as StorageFile) and as .NET types (such as IList) in the method signature. The rule of thumb is to use Windows Runtime types for defining the public fields, parameters and return types that will be exposed to the other languages. That being said, you can use certain .NET fundamental types (i.e.: DateTimeOffset and Uri) and primitives (i.e.: IList) as is.

You will also notice that the method above leverages the Windows Runtime infrastructure for async and progress support that you can (and should) use when defining your Windows Runtime components. As far as the implementation for the Windows Runtime component or any private functionality in the class, you are not limited to only using Windows Runtime types and APIs; you are free to use any of the .NET API surface exposed for Metro app development as shown in the code snippet ZipArchive APIs.

Adding and consuming the Windows Runtime component

Now that we have implemented our zip tool wrapper, we use Visual Studio to add a reference to our C# project from our JavaScript project:

Figure 5: Adding the ZipUtil Windows Runtime component to our file viewer app

As a result, the class that we have exposed from our C# project becomes available to our web project:

program.js

function pickSinglePhoto() { // Create the picker object for picking zip files var openPicker = new Windows.Storage.Pickers.FileOpenPicker(); openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail; openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary; openPicker.fileTypeFilter.replaceAll([".zip"]); // Open the picker for the user to pick a file openPicker.pickSingleFileAsync().then(function (file) { if (file) { ZipUtil.ZipWrapper.enumerateZipFileAsync(file).then( function (fileList) { for (var i = 0; i < fileList.length; i++) document.getElementById(‘output’).innerHTML += ” ” + fileList[i]; }, function (prog) { document.getElementById(‘zipProgress’).value = prog; } ); } else { document.getElementById(‘output’).innerHTML = “an error occurred”; } }); };

As you can see, we can interact with our zip tool wrapper from JavaScript just as if it were a regular JavaScript object. We can call into the static method exposed in our Windows Runtime component, and we can do so using JavaScript’s async language constructs such as .then().

General guidance

Not every API you write for your Metro style app should be exposed as a 3rd party Windows Runtime component. In general, use Windows Runtime types when you are communicating between programming languages and use types and constructs that are built into the language that you are using for functionality that is not publicly exposed via a Windows Runtime component. Additionally, there are various language-specific features and rules around crossing the language boundary that you need to take into consideration when building your Windows Runtime component. This includes delegates and events, asynchronous operations, method overloading, handling specific data types such as collections, exception handling and debugging tips. You can dive into those topics further by visiting the section on building Windows Runtime components for your development language.

In closing

With Windows Runtime components, you can now mix programming languages and API technologies to build the apps you envision. Windows 8 is about no compromises. There are even no compromises during development, allowing you to mix and match the programming languages that best fit your scenario. We hope this allows you to spend more time thinking about innovation and less time being forced to learn a completely new programming language.

Happy app building!

Ray Yagubyan

Generate Entity Framework using SQL Azure

Standard

Ray Yagubyan

 

In this example I am going to show you how to generate your Entity Model edmx using SQl Azure database.

Before we start, first lets create a Sample database named called ContactDetail on SQl Azure database.

To create a SQL Azure database you can either Login directly to your SQL Azure account through web or you can Login to your Windows Azure Account, and from the Homepage you can navigate to the Database. In my example below I am using the Second option.

1. Login to your Windows Azure Account and Navigate to the Database, this will give you the below screen.

image_thumb

2. Now Select the Create Button to Create a new database, this will give you the following screen where you can enter your region and provide a new credentials which you will use with this new database.

image_thumb[1][1]

image_thumb[2][1]

3. Once done, Select Next this will provide you with the below screen where you can provide the firewall rule, this is just for extra security. Once you have provided the IP Address Range, you will not be able to connect from any other IP Address which does not fall in this Range.

image_thumb28[1]

4. If you are connecting through any other application which is Hosted on any other Windows Azure accounts then make sure to Select this option, this will allow your Windows Azure applications to connect to this SQL Azure Database.

image_thumb[3][1]

5. Once completed you can see your fully qualified server name in the Dashboard provided. This Server name is used to connect remotely to your Azure DB from your application or from VS 2010 Server Explorers, etc.

image_thumb26

6. Now lets create some sample database which we are going to use to generate our Entity Model, to create a new database you will have to first select the newly created server from the left hand side of the Windows Azure console, and select Create from the Menu, this will present you the windows where you have to provide your Database information. Based on your requirement you can select the Edition and Size, I am keeping my Database names as ContactDetail and Leaving rest as default and Select Ok.

image

7. Now I can see my New database in the Azure Console, select manage to manage the database objects like SP, Tables, etc. This will open the SQL Azure console.

image

8. SQL Azure console will prompt you for credentials, once you are thru, you will get the SQL Azure Dashboard, where once you have to select the Contact Detail Table –> Design – New Table

image

9. In the New Table I have provided the following information, for my Contact table and Click on Save, this will create my ContactDetail Table.

image

Now I am ready with the SQL Azure table, my next task will be to configure my Entity Framework to use this table, to use in my Application. Please note if you want to use any scripts which is used for your SQL Server database, then this will not work with your SQL Azure database, you can read more in the following link: http://blog.sqlauthority.com/2010/06/04/sql-server-generate-database-script-for-sql-azure/

10. Now lets get back to my application, where I am going to create a entity framework entity model, which I am going to configure with this SQL Azure DB, to perform this I am opening my .NET application where I want to add Entity Model, and Select Add New Item – Data –> ADO.NET Entity Data Model.

image

11. Select Next, in the Wizard, Select New Connection and enter the fully qualified Server name, and the credentials and Select Ok and then Next with default options selected.

image

12. You will get the list of your tables, views and Stored procedures, select the desired Database objects with the default options selected and Select Finish, you will get the Designer with the tables, stored procedures or views you have selected.

image

And that’s it, once done you can work like any other Entity Framework you have used to work with your SQL Server 2008/2005 databases.

 

Ray Yagubyan