Tag Archives: C#

Simple generic C# caching class (I use this all the time)

I wanted to add this simple class that I find myself using all the time in every project that I create. It is a generic caching class:

CacheProvider`1.cs

    public abstract class CacheProvider<TCache> : ICacheProvider
    {

        public int CacheDuration
        {
            get;
            set;
        }

        private readonly int defaultCacheDurationInMinutes = 30;

        protected TCache _cache;

        public CacheProvider()
        {
            CacheDuration = defaultCacheDurationInMinutes;
            _cache = InitCache();
        }
        public CacheProvider(int durationInMinutes) 
        {
            CacheDuration = durationInMinutes;
            _cache = InitCache();
        }

        protected abstract TCache InitCache();

        public abstract bool Get<T>(string key, out T value);

        public abstract void Set<T>(string key, T value);

        public abstract void Set<T>(string key, T value, int duration);

        public abstract void Clear(string key);

        public abstract IEnumerable<KeyValuePair<string, object>> GetAll();

    }

ICacheProvider.cs

    public interface ICacheProvider
    {
        /// <summary>
        /// Retrieve cached item
        /// </summary>
        /// <typeparam name="T">Type of cached item</typeparam>
        /// <param name="key">Name of cached item</param>
        /// <param name="value">Cached value. Default(T) if
        /// item doesn't exist.</param>
        /// <returns>Cached item as type</returns>
        bool Get<T>(string key, out T value);

        /// <summary>
        /// Insert value into the cache using
        /// appropriate name/value pairs
        /// </summary>
        /// <typeparam name="T">Type of cached item</typeparam>
        /// <param name="value">Item to be cached</param>
        /// <param name="key">Name of item</param>
        void Set<T>(string key, T value);

        /// <summary>
        /// Insert value into the cache using
        /// appropriate name/value pairs WITH a cache duration set in minutes
        /// </summary>
        /// <typeparam name="T">Type of cached item</typeparam>
        /// <param name="key">Item to be cached</param>
        /// <param name="value">Name of item</param>
        /// <param name="duration">Cache duration in minutes</param>
        void Set<T>(string key, T value, int duration);

        /// <summary>
        /// Remove item from cache
        /// </summary>
        /// <param name="key">Name of cached item</param>        
        void Clear(string key);

        IEnumerable<KeyValuePair<string, object>> GetAll();

    }

I tend to use dependency injection to implement this cache. Here is a concrete implementation of my cache provider:

    public class HttpCache : CacheProvider<Cache>
    {
        protected override Cache InitCache()
        {
            return HttpRuntime.Cache;
        }

        public override bool Get<T>(string key, out T value)
        {
            try
            {
                if (_cache[key] == null)
                {
                    value = default(T);
                    return false;
                }

                value = (T)_cache[key];
            }
            catch
            {
                value = default(T);
                return false;
            }

            return true;
        }

        public override void Set<T>(string key, T value)
        {
            Set<T>(key, value, CacheDuration);
        }

        public override void Set<T>(string key, T value, int duration)
        {
            _cache.Insert(
                key,
                value,
                null,
                DateTime.Now.AddMinutes(duration),
                TimeSpan.Zero);
        }

        public override void Clear(string key)
        {
            _cache.Remove(key);
        }

        public override IEnumerable<KeyValuePair<string, object>> GetAll()
        {

            foreach (DictionaryEntry item in _cache)
            {
                yield return new KeyValuePair<string, object>(item.Key as string, item.Value);
            }

        }
    }

View the source on GitHub: Omegaluz.Caching

Update, here is a new article with an example: Using the C# generic cache: the Tester Doer pattern

Twin Cities Code Camp – Day 2

Expressing Yourself with C# Expression Trees – Chad Kulesa

Code == Data

  • Dynamically modify code at run time.
  • Create new code at run time.
  • Translate code to another Langauge (SQL, XPath, etc.)
  • Strongly typed.

Expression<Func<string, bool>> expression = x => x == "Value";

var x = Expresion.Parameter(typeof(string), "x");
Expression<Func<string, bool>> expression =
     Expression.Lambda<Func<string, bool>>(
          body: Expression.Equal(
               left: x,
               right: Expression.Constant("Value")),
          parameters: x);

Lambda

  • Easier to read
  • Don’t need to learn the API
  • Compiler will simplify constant expressions

API

  • Additional commands available
  • Dynamically create expression trees

Expression Trees are Immutable – you cannot change them at runtime.

Most C# programmers use expression trees all of the time without even knowing it. For example, LINQ syntax uses expression trees. Func<T, bool>

Expression trees are not useful for just querying. It also has it’s uses for what is called Fluent Configuration. The logic is that is is much better to get configuration errors at compile time rather than runtime. (Don’t know if I’m in agreement with this – I prefer web.config files for configuration changes. They recycle and restart your app when you change them. You also don’t need to recompile your code to change a configuration.)

Source code for presentation at: http://chadkulesa.com

Extending .NET Applications with MEF Plugins – J Wynia

How to extend .NET Applications with MEF plugins. Not how to create METH-amphetamines.

Why should we bother using an extensible architecture? The dominant reason is that the decision of what code to run is not known at compile time. The classic sign that you should be using a plugin based architecture is that you are using a switch statement with a ton of cases. Another, is if you have an app that needs to act differently depending on what kind of record it is in the context of. If the context matters as to what code you want to run. Another great reason is if you want other developers to build upon your product.

The reason the Microsoft focus is on MEF is because Visual Studio’s plug architecture is all MEF based as of 2010.

"I need a" = "Import"

&quotI need some" = "Import Many"

"I have a" or "I am a" = "Export"

"Match up the needs with the providers" = "Compose"

Source code dealt with a loan processing company that did just that – processed loans – console app.

Loan processors became Interfaces injected into the LoanApplication so that many types of Loan Processors can be defined.

Morphed app to use DI/IoC to import the needed LoanProcessor.

Usually, he creates a default implementation of an Export in the assembly so his app does not throw exceptions if there are no imports/exports found. Because of this, he always includes an AssemblyCatalog in the final composition catalog that contains the executing assembly. J calls this Plugin selection with fallback.

Showed an awesome way to load modules. He usually uses the ImportMany attribute to import everything and let the application choose how to load the modules. His example had a method called ChoosePlugins.

caveat. Metro apps IoC containers only work with MEF.

Source available here.

check out if this then that

Unobtrusive Validation with MVC 3 and Html.BeginForm

Yesterday a colleague of mine and I were trying to find out why client side unobtrusive validation attributes were being generated everywhere EXCEPT one specific page on our upcoming release of WebCenter 6.  Client side validation attributes in MVC 3 are html 5 data-val-*attributes.   They enable you to tie your validation to Data Annotation attributes on your models without having to write a line of javascript code.  This is sweet in my book because the JavaScript is completely decoupled from the actual C# code.

Here is what they look like:

<input type="text"
    name="UserName"
    data-val-required="The Username field is required."
    data-val="true"
    class="text-box single-line" />
  • data-val turns unobtrusive validation on for the input
  • data-val-required enables the required validation rule to kick in with the specified error message you see above

If you want to go into more detail, check out Brad Wilson’s in depth post about Unobtrusive Client Validation in ASP.NET MVC3.

The specific problem we were both encountering was that these attributes were simply not being output on our view when rendered in the browser.

I peeked into the source of System.Web.Mvc.dll and here is what I discovered.

  1. When you render an input using an HtmlHelper like @Html.EditorFor, @Html.TextBox etc., they are rendered with the InputExtensions.InputHelper method.
  2. InputHelper calls HtmlHelper.GetUnobtrusiveValidationAttributes to render the data-val attributes.
  3. GetUnobtrusiveValidationAttributes calls ViewContext.GetFormContextForClientValidation which checks to see if ClientValidation is enabled in the either your web.config or the scope of the view that you are rendering.
  4. GetFormContextForClientValidation will return the FormContext that was instantiated with @Html.BeginForm OR return null.
  5. If it returns null, no attributes are rendered, thus the need for Html.BeginForm.

So to re-cap.  I discovered the problem was that my colleague had NOT created his form using Html.BeginForm.  Instead, he had manually added a <form> tag, which in turn never created the ViewContext.FormContext object.

If you want to see for yourself, go download the latest MVC 3 sources from the ASP.Net site on CodePlex.

In my opinion, this is totally ridiculous.  And I guess the devs over at Microsoft agree because they are removing this requirement in MVC 4.

Here are Brad’s own words:

Important note: jQuery Validate requires your input elements to be inside of a <form> element in order to be validated. In addition, MVC 3 requires that you have called Html.BeginForm() to render this form, so that it can find its book-keeping object to help render the HTML attributes. Starting with MVC 4, we’ve eliminated the need for Html.BeginForm(), but the requirement for the HTML <form> element is still there.