Skip to content
Archive of posts filed under the .NET category.

Pluralization in Entity Framework

As I am working on my Entity Framework extras project, I found myself needing to determine table name in the database based on class name used with DbSet in my context.  I was unable to find a way to query entity framework for this information, so I resorted to brute force approach, having to query database based on class name or pluralized class name.  I ready this blog post by Scott Hanselman about pluralization.  However, this class has been made internal, and I could not use it directly.  Having enough experience with reflection, I wrote a wrapper class that used internal class via reflection.  This code will break if API changes, but the fix at that point should be trivial.  The code of course is super easy, and looks as following:

    public static class Pluralizer
    {
       
private static object _pluralizer;
       
private static MethodInfo
_pluralizationMethod;
 
       
public static string Pluralize(string
word)
        {
            CreatePluralizer();
           
return (string)_pluralizationMethod.Invoke(_pluralizer, new object
[] {word});
        }
 
       
public static void
CreatePluralizer()
        {
           
if (_pluralizer == null
)
            {
               
Assembly aseembly = typeof(DbContext
).Assembly;
               
var
type =
                    aseembly.GetType(
                       
"System.Data.Entity.ModelConfiguration.Design.PluralizationServices.EnglishPluralizationService"
);
                _pluralizer =
Activator.CreateInstance(type, true
);
                _pluralizationMethod = _pluralizer.GetType().GetMethod(
"Pluralize"
);
            }
        }
    }

 

As you can see, I am loading assembly class by picking a random class from Entity Framework assembly, DbContext in my case.  Then I am getting a type corresponding to English pluralization service.  Once that is done, I am getting a handle of Pluralize method based on name.

Pretty easy, hah?  Here is how I am testing (using) my new class:

        [TestMethod]
       
public void
PluralizationTest()
        {
           
Assert.AreEqual("people", Pluralizer.Pluralize("person"
));
           
Assert.AreEqual("people", Pluralizer.Pluralize("people"
));
        }

 

Ah, the magic of reflection!

Post to Twitter

What I learned at the Build Conference

I returned from Build conference Friday night.  It was a really exciting conference in my opinion with a lot of new ideas revealed.  Microsoft had kept a very tight lid on upcoming changes for many months, and none really knew what was going to be announced at the event.  There were a number of speculations, but nothing concrete showed up on the internet.  The only exception was a 5 minute video that was put out by Microsoft a few months back, giving viewers a glimpse of the new operating system, Windows 8.  In retrospect, I cannot disagree with Microsoft decision, as the changes that were announced are designed to differentiate Microsoft as an operating system provider, thus giving revealing the information prematurely would lessen a competitive advantage over rivals.

So, what was unveiled at the conference?  Microsoft demonstrated in a significant level of details its new operating system, Windows 8.  At the high level, its user interface carries over the investments Microsoft has made in the area of design for Windows Phone 7.  Windows 8 conforms to Metro design principles.  The opening screen in Windows 8 is very similar to Windows Phone 7, consisting of a number of live tiles, grouped into a number of areas.  Those groups are user defined, and this was demonstrated as well.  User will be able to use gestures of course to control the appearance of the OS.  They will be able to zoom out of the detailed view, find a group they are looking for, and zoom back into that group.  Of course they will also be able to re-arrange any part of any group or groups themselves using similar gestures to the ones on the phone.  What about old look and feel you ask?  The new OS is built on top of Windows 7, and one can drop back to classical look and feel by clicking on Desktop tile. 

There are also a number of new features that exist in Windows 8.  One of them is “charms”.  Charms are located in the right hand area of the screen, and are typically hidden.  The user can bring them into view by swiping from right hand edge to toward the center of the screen.  Charms are common features to all the programs, such as printing, devices, networking, sharing, search, etc.  All software written for Windows 8 should incorporate these charms to provide seamless user experience.  Not only charms allow developers to integrate their applications deeply with Windows 8 OS, but also with each other.  There is a number of contracts in WinRT that one application can implement, that other applications can utilize.  For example, you can write a photo editor application, that implements search contract, and another application such as family tree can search photos and show them in its UI.  Pretty cool, hah?  Similar contracts also exist for devices such as printer.

Now let me talk about programming for Windows 8.  Developers will be able to use C#/VB.NET, C++ and JavaScript to write Windows 8 applications.  Sounds strange at the first sight doesn’t it?  Beforehand browser based application were not able to reach deeply into operating system.  This broad functionality is being enabled view new Windows runtime for writing applications, WinRT.  Unlike .NET, this new run time is built into Windows itself, and it not an additional layer on top of existing Windows functions, as it is the case with .NET.  As a result, WinRT will have better performance.  To ensure highly responsive applications, all the functionality in WinRT that is not instantaneous contains asynchronous methods.  This would include things such as file I/O, networking operations, such as internet client, etc.  I heard phrase “fast and fluid” to describe Windows 8 UI and applications dozens of times during the conference.  Of course, not everything is contained within WinRT, thus .NET is also an integral part of building applications for Win 8.  As a matter of fact, new version of Microsoft.NET, 4.5 will ship with Windows 8, and will be available as part of the operating system.  There is a difference however between traditional .NET and new Metro style applications.  When a developer builds Metro applications, only a subset of .NET is available to this person.  For example, file IO functionality is greatly limited in preference to new WinRT pickers.  These pickers such as open file or save file pickers replace traditional IO in favor of safer and asynchronous operations, where entire file system is not exposed to a Metro style application.  You get the idea right?  Metro apps run in a sandboxed environment.  So, if you want to build Metro apps, you will use .NET and WinRT, but your tooling will remain the same.  You will use Visual Studio v. next and your favorite language to build those applications.  What about UI, you ask?  You have options there as well.  If you opt for JavaScript as your language of choice, you build UI in HTML.  If you pick C#, VB.NET or C++, you will build UI for your applications in XAML.  No, not Silverlight or WPF, but XAML.  Your XAML skills transfer over, but namespaces you used will change.  There will also be some new controls, such as GridView and FlipView.  If you ever saw Windows Phone 7 applications, you understand that in order to enable Metro style UI and more importantly touch based UI, you need new set of controls, and Windows 8 is all about touch interfaces. 

A few words about legacy software.  Microsoft pledged that all the software that successfully ran on Windows 7 will run on Windows 8.  This would include platforms such as WinForms, WPF, Silverlight, HTML, etc.

There were a number of devices shown that will run Windows 8.  In addition to tablets, laptops and PCs, which all will incorporate traditional processors and likely solid state hard drives, there will be another class of lighter devices, running Windows 8 on RISC processors.  This is drastically different from Apple’s approach that uses different OS for tablets.  As a result, Microsoft tablets will be more functional, and will contains software such as Microsoft Office and other PC based applications. 

New version of Visual Studio, Expression Blend and Microsoft.NET will all ship to help developers build Metro style applications.  Visual Studio will contain templates for Metro apps, Expression Blend will enable UI design, but not just XAML.  Blend gets new set of functionality, enabling it to design HTML as well.  Cool new editing features found their way into Blend.  Because Blend actually runs your XAML and HTML, you actually see your applications running with data.  All changes you make will update either XAML, HTML or even CSS in your Visual Studio project.  Visual Studio got new XAML designer.  It appears that old designer code name Cider is gone, and is replace with Blend designer!!!  Yeah, it is about 4 times faster now.  Personally, I always hated Cider’s performance and hardly ever used XAML view in studio because of that.  Power tools for studio previously available on NuGet only, will be integrated into Studio directly when it ships.

Another huge news that will interest developers is new Windows 8 App Store.  If you create Metro style application, you will be able to sell it through new app store.  I can only guess that the model will be largely similar to Windows Phone 7 app store.  Potential market though is thousands of times larger.  According to Microsoft, Windows is being run on almost half a billion computers.  If you can imagine, one dollar app can make you a millionaire.  Not that this will happen to too many people, but the promise is certainly there.

Another software release was announced, and that is TFS in the cloud service from Microsoft.  Beta has been released, and attendees all got beta account free of charge. 

Live Services will be an integral part of Windows 8.  It looks like SkyDrive will enable many cool features, such as roaming profiles that will enable users to have exact same desktop on many computers.  Developers will be able to use that feature as well, roaming state of their software across multiple computers, for example making sure that users of a software have the same state of the software available on all machines.

 

In summary, here is are the most important points (IMHO).

  • Windows 8 is all about modern consumer experience.  This includes touch based Metro UI.
  • Developers carry all their existing skills over to Metro applications, including XAML, .NET languages, .NET Framework, HTML and JavaScript. 
  • NET is not dead Smile, it is integral part of Metro applications along with WinRT.
  • Developers get to utilize new WinRT, making applications faster and highly integrated with OS and each other.
  • New tools will be shipped to enable developers to create applications faster with a uniform look and feel.
  • Money making opportunity is there for all developers.

You can watch all the online content, including keynotes and sessions, from the conference on www.BuildWindows.com

Please let me know if you have any questions, I would like to kick off a discussion that would benefit all of us, including me.

Post to Twitter

Events and Lambda Expressions

Something I was pondering about today.  Say, I have a class and I would like to subscribe to an event it raises, handle it once, and unsubscribe.  Pretty easy scenario, and the code is just as simple.

Here is my simple class with event arguments:

using System;

 

namespace EventsDemo

{

  public class EventProvider

  {

    public string RandomData { get; set; }

 

 

    public void RaiseEvent()

    {

      OnRandomEvent(RandomData);

    }

 

    public event EventHandler<RandomEventArgs> RandomEvent;

 

    protected void OnRandomEvent(string data)

    {

      if (RandomEvent != null)

      {

        RandomEvent(this, new RandomEventArgs(data));

      }

    }

  }

}

 

using System;

 

namespace EventsDemo

{

  public class RandomEventArgs : EventArgs

  {

    private RandomEventArgs() { }

 

    public RandomEventArgs(string data)

    {

      Data = data;

    }

    public string Data { get; private set; }

  }

}

 

Of course, my console sample application is just as easy:

using System;

 

namespace EventsDemo

{

  class Program

  {

    static void Main(string[] args)

    {

      string extraData = "extra data";

 

      EventProvider provider = new EventProvider() { RandomData = "something" };

      provider.RandomEvent += new EventHandler<RandomEventArgs>(provider_RandomEvent);

      provider.RaiseEvent();

      Console.ReadKey();

    }

 

    static void provider_RandomEvent(object sender, RandomEventArgs e)

    {

      Console.WriteLine(e.Data);

      EventProvider provider = sender as EventProvider;

      provider.RandomEvent -= new EventHandler<RandomEventArgs>(provider_RandomEvent);

    }

 

 

  }

}

 

However, I am accustomed to just handle events as lambda expressions as I find that syntax much cleaner and easier to follow:

 

using System;

 

namespace EventsDemo

{

  class Program

  {

    static void Main(string[] args)

    {

      string extraData = "extra data";

 

      EventProvider provider = new EventProvider() { RandomData = "something" };

      provider.RandomEvent += (o, e) => { Console.WriteLine(e.Data); };

 

      provider.RaiseEvent();

      Console.ReadKey();

    }

 

 

  }

}

 

Now is the question.  How do I unsubscribe from the event in my lambda expression?  I cannot do what I did before, since I do not have a handler to use for –= call.  So, I have to declare my handler separately.  Here is modified code:

using System;

 

namespace EventsDemo

{

  class Program

  {

    static void Main(string[] args)

    {

      string extraData = "extra data";

      EventProvider provider = new EventProvider() { RandomData = "something" };

 

      EventHandler<RandomEventArgs> handler = null;

      handler = (o, e) => { Console.WriteLine(e.Data); provider.RandomEvent -= handler; };

      provider.RandomEvent += handler;

 

      provider.RaiseEvent();

 

      provider.RaiseEvent();

 

      Console.ReadKey();

    }

 

 

  }

}

 

I am calling RaiseEvent twice to ensure I did indeed unsubscribe.  Now what is the advantage to this approach you say?  Closures is my number one reason along with clean code as close second.  Here is the final version:

using System;

 

namespace EventsDemo

{

  class Program

  {

    static void Main(string[] args)

    {

      string extraData = "extra data";

      EventProvider provider = new EventProvider() { RandomData = "something" };

 

      EventHandler<RandomEventArgs> handler = null;

      handler = (o, e) => { Console.WriteLine(e.Data + "-" + extraData); provider.RandomEvent -= handler; };

      provider.RandomEvent += handler;

 

      provider.RaiseEvent();

 

      provider.RaiseEvent();

 

      Console.ReadKey();

    }

 

 

  }

}

 

As you can see, I use closure and take advantage of the scope in which my extraData variable is declared, thus combining data in the event with that variable.  I could not do this in my first example without making extraData variable public.  In this quick post I demonstrated how to unsubscribe from events where handlers are implemented as lambda expression as well as outlined the reasons why one might want to use this approach.  Why would you want to unsubscribe?  Typically, your handlers would be cleaned up, but what if your code throws an exception inside lambda expression?  In this case next time you raise the event, it will be handled twice.  Also, I am a big fan of cleaning up event handlers as they are a major source of potential memory leaks.

Thanks.

Post to Twitter

How do Determine if Your Application is Running in Cassini

This is really short post, more a tip.

If you need to determine if your application is running in IIS or Developer Web Server (Cassini) that comes with Visual Studio, you can test the process name you are running in.  For example, the following code:

System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName

will return the name of the running process.  In case of developer web server in Visual Studio 2010 it returns

"C:\\Program Files\\Common Files\\Microsoft Shared\\DevServer\\10.0\\WebDev.WebServer40.exe"

So, if you for example want to scan Bin folder, code that you run in IIS will not work running in Cassini.  This simple one line of code will let you know what you are running.

Post to Twitter

Encryption in Silverlight and .NET Applications

Today I would like to cover a specific use case that came up a few times in Silverlight applications I wrote.  For example, I wand a user to enter some sensitive information, encrypt it in Silverlight client, transfer it over to the server, then decrypt it and perforation some operations on that data.

First step of course is to find sufficiently strong encryption protocol that can be implemented in both Silverlight and .NET and be completely compatible between both run times.  I am going to go for AES encryption.  AES stands for “Advanced Encryption Standard”.  This standard is widely used and approved by US government and standard bodies.  See this article for details.

Luckily, AES encryption is implemented in both Silverlight and .NET run times, using exact same set of classes, primary one being AesManaged class.  My goal is to create a class that I can cross-compile in both runt times, so this comes in super handy.  Second, I wand to implement two methods Decrypt and Encrypt, while paying attention to IDisposable interfaces that the vast majority of classes inside Cryptography namespace implement.  Both static methods take two parameters, input string and a password to be used.  Of course, you have to make sure you use the same password in both methods while encrypting and decrypting information.  You should probably dynamically generate a password during handshake process between a Silverlight client and a .NET server.  I will also use maximum key size and block size of encryption.  I will also dynamically generate key (Key) and initialization vector(IV) properties.    I am going to now spare everyone a number of boring details, and will simply post final version of my utility class:  You can include this class in both .NET and Silverlight project, and even link the physical .cs file from one to the other to ensure that you only have a single version in source control.

Thanks

using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;
 
namespace Encryption
{
    public static class EncryptionUtility
    {
 
        /// <summary>
        /// Encrypt the data
        /// </summary>
        /// <param name="input">String to encrypt</param>
        /// <returns>Encrypted string</returns>
        public static string Encrypt(string input, string password)
        {
 
            byte[] utfData = UTF8Encoding.UTF8.GetBytes(input);
            byte[] saltBytes = Encoding.UTF8.GetBytes(password);
            string encryptedString = string.Empty;
            using (AesManaged aes = new AesManaged())
            {
                Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(password, saltBytes);
 
                aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
                aes.KeySize = aes.LegalKeySizes[0].MaxSize;
                aes.Key = rfc.GetBytes(aes.KeySize / 8);
                aes.IV = rfc.GetBytes(aes.BlockSize / 8);
 
                using (ICryptoTransform encryptTransform = aes.CreateEncryptor())
                {
                    using (MemoryStream encryptedStream = new MemoryStream())
                    {
                        using (CryptoStream encryptor = 
                            new CryptoStream(encryptedStream, encryptTransform, CryptoStreamMode.Write))
                        {
                            encryptor.Write(utfData, 0, utfData.Length);
                            encryptor.Flush();
                            encryptor.Close();
 
                            byte[] encryptBytes = encryptedStream.ToArray();
                            encryptedString = Convert.ToBase64String(encryptBytes);
                        }
                    }
                }
            }
            return encryptedString;
        }
 
        /// <summary>
        /// Decrypt a string
        /// </summary>
        /// <param name="input">Input string in base 64 format</param>
        /// <returns>Decrypted string</returns>
        public static string Decrypt(string input, string password)
        {
 
            byte[] encryptedBytes = Convert.FromBase64String(input);
            byte[] saltBytes = Encoding.UTF8.GetBytes(password);
            string decryptedString = string.Empty;
            using (var aes = new AesManaged())
            {
                Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(password, saltBytes);
                aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
                aes.KeySize = aes.LegalKeySizes[0].MaxSize;
                aes.Key = rfc.GetBytes(aes.KeySize / 8);
                aes.IV = rfc.GetBytes(aes.BlockSize / 8);
 
                using (ICryptoTransform decryptTransform = aes.CreateDecryptor())
                {
                    using (MemoryStream decryptedStream = new MemoryStream())
                    {
                        CryptoStream decryptor = 
                            new CryptoStream(decryptedStream, decryptTransform, CryptoStreamMode.Write);
                        decryptor.Write(encryptedBytes, 0, encryptedBytes.Length);
                        decryptor.Flush();
                        decryptor.Close();
 
                        byte[] decryptBytes = decryptedStream.ToArray();
                        decryptedString = 
                            UTF8Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length);
                    }
                }
            }
 
            return decryptedString;
        }
    }
}

Post to Twitter

First Stab at Reactive Framework

Today I made an attempt to make some sense of Reactive Framework(Rx).  Rx allows developers to write queries against events.  I know, I had hard time wrapping my head around this concept as well.  I hope the example below will help.

I downloaded and installed Rx extensions for Silverlight from the page above.  I created new Silverlight project and added references to three DLLs that are included with Rx:

System.CoreEx, System.Observable, System.Reactive.

In attempt to save time I created RIA Services project.  Rx is not as good of a fit for the Rx pattern, so my example is a bit contrived.

First, I am creating new instance of domain context

RXContext context;

Now, I am creating new query and starting the load for it:

            var talks = context.GetTalksQuery();


            var op = context.Load<Talk>(talks, LoadBehavior.RefreshCurrent, false);

Now, the fun part:  I am creating two event handlers by querying completed event with two different where clauses – one for error, the other for success:


    var events = Observable.FromEvent((EventHandler<EventArgs> eventInstance) =>
        new EventHandler(eventInstance),
            eventInstance => op.Completed += eventInstance,
            eventInstance => op.Completed -= eventInstance);
    var subsc = events.Where(ev => op.Error == null).Subscribe((args) =>
        { gridTalks.ItemsSource = op.AllEntities; });
    var errorSubs = events.Where(ev => op.Error != null).Subscribe((args) =>
        { MessageBox.Show(op.Error.ToString()); });

In the first statement I am converting regular event to observable event.  In the other two statement I am creating two event subscriptions with different where clauses.

Rx supports other clauses, such as group by as well.  I can see that Rx in general can result in cleaner, more readable code.  You can find more details at this Rx 101 page.

Post to Twitter

Windows 7 and IIS Errors

I just re-installed Windows 7 on my machine.  Once I opened and tried to run an old web project configured for VS 2010 and .NET 4.0, my IIS server threw an exception.  I went into Windows features and enabled all IIS features related to ASP.NET and WCF.  Even after all this I still got the following error:

HTTP Error 500.21 – Internal Server Error
Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list

I checked web.config, and it looked correct, plus it has not changed in a while.  After some research I found out that  even though ASP.NET 4.0 was showing up in properties of my virtual directory, ASP.NET still did not function properly.  The solution was to run aspnet_regiis –i after all.  One thing to remember is to run this utility from Microsoft.NET v4 folder, not 2.0 folder.  Once I ran the utility, I was back in business.

 

I hope this helps someone with the same issue.

Post to Twitter

Extending Interfaces with Implementation

Today I was faced with an issue.  I had an interface based implementation of a specific functionality.  All classes that implemented this interface had different implementation of course.  What I had to add is ability to run certain checks on each implementation that would need to analyze the data defined in the interface and return a Boolean result of this check.

The problem was that the checks were all the same and I hated to add this check to the interface and write identical code in all implementations.  As everyone knows interfaces cannot contain implementation code though.  So, what should I do?

So, a particular .NET 3.5 feature came to my rescue.  I am referring to extension methods.  As you may or may not know extension methods are tied to a type.  Well, interface is a type too.  Here is some code to look at.

Here is the interface definition:

    public interface ISupportCustomAction

    {

        Action CustomAction { get; set; }

        void Execute();

    }

Here is my class definition that implements this interface

    public class CustomActionOne : ISupportCustomAction

    {

        #region ISupportCustomAction Members

        private Action action;

        public Action CustomAction

        {

            get

            {

                return action;

            }

            set

            {

                action = value;

            }

        }

 

        public void Execute()

        {

            // fill in the method

        }

 

 

        #endregion

    }

Finally, here is my extension method

    public static class ISupportCustomActionExtensions

    {

        public static bool Check(this ISupportCustomAction action)

        {

            if (action.CustomAction == null)

            {

                return false;

            }

            else

            {

                return true;

            }

        }

    }

Here is my test code to confirm that everything works

    class Program

    {

        static void Main(string[] args)

        {

            CustomActionOne action = new CustomActionOne();

            action.CustomAction = () => { Debug.WriteLine("Exectuted Action."); };

            Analize(action);

 

            action = new CustomActionOne();

            Analize(action);

            Console.ReadKey();

        }

 

        private static void Analize(ISupportCustomAction action)

        {

            if (action.Check())

            {

                Console.WriteLine("Can execute action");

            }

            else

            {

                Console.WriteLine("Cannot execute action");

            }

        }

    }

How useful this is?  Pretty useful in my case.  Saved me some typing and resulted in consistent coding.  My point is that is good to know what features .NET has and use them as a need arises.  As you can see I have a hybrid here of a base (abstract) class and an interface.  As a result, I am able to use features that belong to both concepts.

What does this code remind you of?  Can you say “Multiple Inheritance in C#?”  Well, not exactly, but pretty close.

 

Thanks.

Post to Twitter

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.

Post to Twitter

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.

Post to Twitter

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

Post to Twitter

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.

Post to Twitter

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.

Post to Twitter