Archive of entries posted on November 2009

Getting Started with Velocity (AppFabric Caching Library)

I have worked through my first Velocity project today, and I would like to blog about  the steps necessary to use caching.

First, you should read my previous post and install AppFabric on your machine.

I used Visual Studio 2010 beta 2 to create the solution.  You can download the solution here.  I create WPF project in order to prove that caching is not limited to web applications, although web farm would probably be an ideal application for caching.  Once project is created, I added references to DLLs for Velocity.  On my machine they were located in C:\Windows\System32\ApplicationServerExtensions.  Two DLLs I needed were CacheBaseLibrary.dll and  ClientLibrary.dll.  They contain key classes that can be used to utilize caching.  I could not add them directly from that folder, I was getting an error from Add Reference dialog.  So, I copied them into a folder under my Solution (“Bin” folder).

Then I added a complex class that I intended to cache.  I wanted to prove to myself that complex object graphs are OK since all the demos I saw just used strings.  Here is the class I used:

 

    public class CachablePerson

    {

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public List<CachableAddress> Addresses { get; set; }

        public CachablePerson()

        {

            FirstName = "Sergey";

            LastName = "Barskiy";

            Addresses = new List<CachableAddress>();

            Addresses.Add(new CachableAddress() { Street = "Main Street", City = "Atlanta" });

            Addresses.Add(new CachableAddress() { Street = "Second Street", City = "Lilburn" });

        }

    }

 

    public class CachableAddress

    {

        public string Street { get; set; }

        public string City { get; set; }

    }

 

I put the class into its own project and referenced this project from two separate WPF application projects.

First step in using caching is to configure cache object.  Here is how we can configure cache object using cache factory:

        private void SetupCache()

        {

            DataCacheServerEndpoint[] servers = new DataCacheServerEndpoint[1];

            servers[0] = new DataCacheServerEndpoint("Sergey-Laptop", 22233, "DistributedCacheService");

            _cacheFactory = new DataCacheFactory(servers, false, true);

            _defaultCache = _cacheFactory.GetCache("default");

        }

 

Now we are ready to add object to cache.  We will do this in steps.  First we check to see if an object is already in cache, and if so, we will remove it from cache.  Cache basically is using a string as the object key.  In addition to that you can also version objects, thus having multiple copies of the same object with the same key existing in cache at any given time.

            if (_defaultCache.Get("person") != null)

            {

                _defaultCache.Remove("person");

            }

            _defaultCache.Add("person", _person);

 

 

Now I am going to get the object from cache.  Just as simple as adding it:

_person = (CachablePerson)_defaultCache.Get("person");

 

Simple and easy.  I think Velocity is super powerful yet simple to use.  Event though it would be an abuse, but one could possibly use caching to communicate between different applications. 

You can download my sample solution here

Windows AppFabric and Velocity

I downloaded Windows AppFabric Beta 1 version this week.  You can find this download here. It took a few hours to install it.  I could surely tell I was dealing with beta 1 of version 1 of the product.  I finally installed it using new cluster option and XML configuration option.  I tried SQL Server configuration  option a few times, but it never installed without errors.  I think at the end I ran the install about a dozen times before it succeeded.

Anyway, three hours later or so I was done.  Next I tried to run a downloaded sample.   No matter what I tried, I could not get the sample to work.  It looked pretty obvious that I still need to configure something.  Finally after another 30 minutes I found an answer – I had to start the cache cluster.  To do so, I went to Programs –> Microsoft Distributed Cache –> Administration tool.  I was sort of surprised that this launched PowerShell window.  I guess we need to wait until release to get real nice configuration software with GUI.  In the mean time, I had to type “start-cachecluster”.  Once I ran that and saw that the server was started, I went back to run the samples.  They worked perfectly well this time.

Once I write my own sample, I will post source code on this blog.

Windows Azure Application

This is purely a bragging post :-)

I just deployed a test application to the cloud (Microsoft Azure): http://rolodex.cloudapp.net/

Here is the technology stack for it:

  1. Windows Azure
  2. SQL Azure
  3. CSLA 3.8.1
  4. Silverlight
  5. Entity Framework
  6. WCF
  7. Prism (Composite Application Guidance)
  8. Silverlight Toolkit

I promise to write a blog entry in the near future, the steps one has to follow through to create an Azure application.

Dynamically Styling Silverlight Applications

I spoke at GGMUG (Gwinnett Georgia Microsoft Users Group) on Thursday.  I was speaking about dynamically styling Silverlight applications using Implicit Style Manager from Silverlight Toolkit

Silverlight toolkit comes with about a dozen themes that anyone can use to style there applications.  In the example I am posting I use four of them,  A theme file is essentially a XAML file that contains styles for all native Silverlight controls as well as all Toolkit controls.  Implicit style manager allows developers to dynamically (or statically) load a theme and apply it to any FrameworkElement in the visual tree. 

There are only a few steps you need to do to implement this type of styling.

1.  Download and install Toolkit.

2.  Create new Silverlight application.

3.  Create new folder under applications (UserThemes in my example) and copy some or all themes from toolkit (C:\Program Files\Microsoft SDKs\Silverlight\v3.0\Toolkit\Oct09\Themes is the default folder) into that folder.  Once you include all the themes into the project, set compile action to Content.

4.  Now write a few lines of code in key places to apply a chosen theme.  Here is what this code would look like:

        private void ApplyeTheme(string themeName)

        {

            Uri uri = new Uri(string.Concat("UserThemes/", themeName, ".xaml"), UriKind.Relative);

            ImplicitStyleManager.SetResourceDictionaryUri(this, uri);

            ImplicitStyleManager.SetApplyMode(this, ImplicitStylesApplyMode.OneTime);

            ImplicitStyleManager.Apply(this);

        }

5.  You can even allow application user to select a theme by creating for example a combo box loaded with available themes.

Implicit style manager does carry some overhead with it.  To minimize the overhead try to use apply mode of OneTime.  Ap0ply mode of Auto will watch for LayoutUpdated event and restyle attached element.  If you use this mode, you can apply this code to your shell (outer application frame), and any loaded control will be styled.  It sounds easy, but it will slow down your application.

As you can see, you cheaply and easily implement dynamic styling using free! software from Silverlight Toolkit.

You can download full example here.

Rocky Lhotka is Talking Oslo at ALEMUG

At out next Atlanta Leading Edge Microsoft Users Group Rocky Lhotka will be talking about Oslo.  Please visit ALEMUG.NET home page to register for this exciting event!

Here are the details of this event.

Microsoft code-name “Oslo” includes the ability to define your own domain specific  language (DSL), a metadata repository hosted in SQL Server and a graphical tool (“Quadrant”) to edit that metadata. One part of the Oslo vision is that you might define a DSL, build code in your language, compile that code into the repository and then create a runtime to dynamically execute that metadata. Taking this vision and combining it with the popular CSLA .NET framework, the result is MCsla. This is a prototype DSL grammar, repository schema and runtime that dynamically creates and executes CSLA .NET business objects with a WPF UI. The result is a fully functional application that you can create with a fraction of the code you’d need to write with traditional programming techniques. Learn how MCsla was created and how it works in this rapid-fire walk through the depths of the Olso technology.

Rockford Lhotka is the creator of the popular CSLA .NET development framework, and is the author of numerous books, including Expert C# 2008 Business Objects and Expert VB 2008 Business Objects. He is a Microsoft Regional Director, MVP and INETA speaker. He contributes to several major magazines and regularly presents at major conferences around the world. Rockford is the Principal Technology Evangelist for Magenic (www.magenic.com), a company focused on delivering business value through applied technology and one of the nation’s premiere Microsoft Gold Certified Partners. For more information go to www.lhotka.net.

Getting Started with SQL Azure

I setup an account with SQL Azure last week, and I would like to document each step I took in order. 

There is a lot of information on SQL Azure FAQ and Zack Owens’ blog.  I still ran into some issues though, and I wanted to provide detailed instruction on how to work through them.

Step 1 – Get SQL Azure token.  You need to Microsoft Azure site and scroll down the page to request tokens.

Step 2 – Wait for the email you will receive that will contain the token (invitation code) and instructions on how to activate it. Follow those step to setup an account.

Step 3 – Create new project in SQL Azure.  You will setup user ID and password as part of that process.

Step 4 – Create a database with a name you choose and setup firewall

image

 

image 

 

image

You can see your own IP address on this window above as well.  You can just copy that address and paste it into both IP ranges – low and high,

Step 5 – Start SSMS (SQL Server Management Studio).  Hit Cancel on initial login screen.

image

Step 6 – Click New Query button

image

Step 7 – Enter your server information, but do NOT click Connect

image

Step 8 – Click Options and enter your database name

image

Step 9 – Click “Connect”.  You should not get any errors and now you can see a query window.  You are ready to add tables.

Step 10 – Type in script to create database structure.  Important: not all standard SQL commands are supported.  If you are scripting an existing database, you will need to remove all file group references, such as “ON PRIMARY”. 

image

Step 11 – Create a standard .NET application.  You can get exact connection string on your SQL Azure management page:

image

You are done!

Find more information on SQL Azure FAQ and Zack Owens’ blog.

Entity Framework 4.0 CTP

I just installed CTP of entity framework 4.0 (2.0 technically).  I decided to test the most advertized feature – ability to have actual foreign keys (IDs) in addition to navigation properties.  The lack of this feature has been the biggest annoyance for me while working with Entity Framework for many months now.

Here is the model I created

image

As you can see Companies have Contacts, and each contact object now has CompanyID in addition to Company navigation property.  I had to select this option while generating the model from the database.  The checkbox for option to include foreign key values was available on one of the wizard screens.

Here is the code I wrote for testing:

 

            using (RolodexEntities context = new RolodexEntities())

            {

                CompanyContact newConact = new CompanyContact();

                newConact.CompanyId = 2;

                newConact.BaseSalary = 1;

                newConact.Birthday = DateTime.Today;

                newConact.FirstName = "Sergey";

                newConact.LastName = "Barskiy";

                newConact.RankId = 1;

                context.AddToCompanyContacts(newConact);

                context.SaveChanges();

            }

Hurray!  It worked!  New contact was added to the database and linked to Company with ID of 2 and Rank with ID of 1.

This feature to me is invaluable in n-Tier development when a developer has to replay the changes on the server after allowing the user to edit the data on the client.  Now, we can just transmit all properties of a Contact to the server, (probably with IsNew, IsUpdated, IsDeleted flags), set the foreign keys via IDs, then save.