Archive of posts filed under the .NET category.

Velocity Presentation

As I mentioned previously, I presented on the topic of Velocity at the Atlanta Leading Edge Microsoft Users Group on Tuesday, January 19th.

The talk went pretty well, we had a lot of technical questions.  I really enjoyed this presentation, as I am always excited to speak on a new topic that I have not covered previously. 

You can download materials here.

 

Please let me know if you have any questions.

AppFabric Caching (Velocity) and Versioning

To continue on the topic of Velocity, I will explore versioning today.

As I showed previously, you can use DataCache.Add method to add an item to cache.  This, of course, requires that this item’s key was not to be found in the cache already, or an exception will be thrown.  This puts a damper on versioning,  So, let’s look at a different method – Put.

You can use Put method to add/replace an item in cache.  If a key already exists, the item will be replaced, otherwise it will be added.

// add an item to cache

CachablePerson person1 = new CachablePerson();

person1.FirstName = "Version1";

DataCacheItemVersion version1 = _defaultCache.Put("personwithversion", person1);

 

 

Now, I will explore versioning of items.  In order to control versioning, I will use GetAndLock method to get an item from cache while locking it to ensure safe updates.  I will update a property of an object I got from cache, then I will put it back into cache.

// get an item and lock it

DataCacheLockHandle handle;

CachablePerson temp = _defaultCache.GetAndLock("personwithversion", TimeSpan.FromSeconds(1), out handle, true) as CachablePerson;

/update an item

temp.FirstName = "Version2";

//put it back and get the new version

DataCacheItemVersion version2 = _defaultCache.PutAndUnlock("personwithversion", temp, handle);

Now I will version that versioning actually works by getting both initial and new items

// get initial item

CachablePerson ver1 = (CachablePerson)_defaultCache.Get("personwithversion");

// get the item with version 2

CachablePerson ver2 = (CachablePerson)_defaultCache.GetIfNewer("personwithversion", ref version1);

To proof that the process worked, I will output the results to a window or console.  In my case ver1.FirstName is Version1 and ver2.FirstName is Version2 which is what is expected.

In this post I looked at the Put method that makes it easier to put items into cache without worrying if an item with the same key already exists.  I also looked at the way to maintain many versioned items with the same key in cache in case versioning is important to the consuming application.

You can download the updated initial sample here.

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.

C# 4.0 (.NET 4.0) Features

As part of our first ALEMUG meeting I did a presentation on some of the new features in C# 4.0.  Here is what I talked about.

First topic was on optional and named parameters in C#.  Here is how you would define a function with optional parameters:

public static int AddTwoOrThreeOrFourNumbers(int numberOne = 0, int numberTwo = 0, int numberThree = 0, int numberFour = 0)

{

    int returnValue = numberOne + numberTwo + numberThree + numberFour;

    return returnValue;

}

All you need to do to define optional parameters is to provide a default value for each one. Here is how you could call this function by providing values only for some parameters:

ClassWithOptionalParameters.AddTwoOrThreeOrFourNumbers(1, 2)

As you see, I only supplied two out of three parameters.  All the magic is preformed by the compiler.  If you look at disassembled code, you will find that call to the function actually has all three parameters defined, just the last one is zero.

Another related feature is named parameters.  You can actually specify the name and the value for each parameters explicitly and out of order even:

ClassWithOptionalParameters.AddTwoOrThreeOrFourNumbers(numberOne: 1, numberFour: 4)

 

There are a few great uses for named / optional parameters.  One is COM Interop, specifically Office Interop.  Many functions in the Office take a number of optional parameter.  Right now you have to specify all of them.  With C# 4.0 you can specify just the ones you need.  Here is an example for SavedAs:

var format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument97;

Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();

var doc = word.Documents.Add();

doc.SaveAs(FileName: fileNameSaved, FileFormat: format);

In general, there are many features in C# to make Office development easier.  One of them (pointed out by Jim Wooly)  is No PIA – No Primary Interop Assembly distribution. To use this feature just go to properties of office interop assembly in the references window and set Embed Interop Types to True.  If you do, you do not have to distribute Interop assembly! 

Another features I talked about is dynamics.  Here is you declare a dynamic variable:

dynamic person = ExpandoClass.GetExpando();

Looks very similar to var, doesn’t it?  There is a big difference though between vars and dynamics.  The key difference is the resolution time.  Vars are resolved at compile time, and they are actually strongly typed in the running program.  Dynamics on the other hand are resolved at run time.  As a result, you can compile pretty much any code that refers to dynamics.  For example, you can type

dynamic thing = GetSomeDynamicObject();

thing.SomeProperty = 1;

SomeProperty actually does not exist anywhere in the source code, it is called dynamically at run time and it will succeed as long as whatever object is returned by GetSomeDynamicObject function has this property.  Very powerful feature when it comes to interacting with objects unknown at compile time.  You can use it to interact with dynamic languages such Python or COM objects or even other .NET objects.  Here is some code I came up with (not that I would write something like this, but it demonstrate the power of the feature) – universal sorter that can sort any collection:

    public static class DynamicDemo

    {

        public static IEnumerable<dynamic> GetSortedData(IEnumerable<dynamic> initialCollection, Func<dynamic, dynamic> sortExpression)

        {

            dynamic retVal = (from one in initialCollection

                              orderby sortExpression(one)

                              select one);

            return retVal;

        }

Dynamics is a very powerful features, but can be easily abused.  Also, anything can be dynamic, not just objects.  You can also have dynamic properties and methods and their parameters.

Another related feature is ExpandoObject.  This is a dynamic object that can be “expanded” at run time to contain custom properties and values:

dynamic expando = new System.Dynamic.ExpandoObject();

expando.Name = "Sergey Barskiy";

expando.Age = 18;

Seems pretty weird – I actually define the object at run time.

You can download sample solution (requires VS 2010) here.