VS2010

Back to Basics : Singleton Design Pattern using System.Lazy type

June 25, 2015 .NET, .NET Framework, .NET Framework 4.5, .NET Framework 4.5.2, .NET Framework 4.6, Back-2-Bascis, BCL(Base Class Library), C#.NET, Codes, Design Patterns, KnowledgeBase, Microsoft, Portable Class Library, Visual Studio 2013, Visual Studio 2015, VisualStudio, VS2010, VS2012, VS2013, VS2015, Windows No comments

This article takes you to a simpler/alternative approach in making a Singleton Design Pattern implementation using System.Lazy class rather that using our traditional approach.

Singleton Design Pattern implementation without lazy initialization:

  • This code is thread safe enabled
 /// <summary>
    /// Singleton class 
    /// </summary>
    public class AppConfig
    {

        private AppConfig()
        {

        }

        /// <summary>
        /// Gets the current date time.
        /// </summary>
        /// <value>
        /// The current date time.
        /// </value>
        public DateTime CurrentDateTime
        {
            get
            {
                return DateTime.Now;
            }
        }
        /// <summary>
        /// The _config
        /// </summary>
        private static AppConfig _config;

        /// <summary>
        /// The pad lock for maintaining a thread lock.
        /// </summary>
        private static readonly Object padLock = new object();

        /// <summary>
        /// Gets the instance.
        /// </summary>
        /// <value>
        /// The instance.
        /// </value>
        public static AppConfig Instance
        {
            get
            {

                if (_config == null)
                {
                    lock (padLock) // making thread-safe
                    {
                        //{
                        if (_config == null) //second level check to make sure, within the short span, another concurent thread didnt initialize the object. 
                        {
                            _config = new AppConfig();
                        }
                    }
                }
                //}

                return _config;
            }
        }
    }

This approach ensures that only one instance is created and only when the instance is needed. Also, the variable is declared to be volatile to ensure that assignment to the instance variable completes before the instance variable can be accessed. Lastly, this approach uses a padLock instance to lock on, rather than locking on the type itself, to avoid deadlocks.

Another variant using Lazy initialization using static constructor and thread safe since initialization is handled during runtime within readonly variable declaration.  This will be thread-safe any ways.

 /// <summary>
    /// a Simpler version of Singleton class with lazy initialization.
    /// </summary>
    public class AppConfigLazy1
    {
        // static holder for instance, will not get initialized until first use, due to static contructor.
        private static readonly AppConfigLazy1 _instance = new AppConfigLazy1();

        /// <summary>
        /// Prevents a default instance of the <see cref=&quot;AppConfigLazy1&quot;/> class from being created.
        /// </summary>
        private AppConfigLazy1()
        {

        }

        /// <summary>
        /// for Lazy Initializes the <see cref=&quot;AppConfigLazy1&quot;/> class.
        /// </summary>
        static AppConfigLazy1()
        {

        }


        public static AppConfigLazy1 Instance
        {
            get
            {
                return _instance;
            }
        }
    }

Now with .NET 4.0 onwards there is a better way of doing this using .NET Runtime methods using System.Lazy type. System.Lazy type is mainly used in Entity Framework context, but we can use the same in implementing lazy loading where ever we have to deal with memory intensive object or collection of objects.

System.Lazy type  guarantees thread-safe lazy-construction. (By default, all public and protected members of the Lazy class are thread safe and may be used concurrently from multiple threads.)

.NET Framework Support in: 4.6, 4.5, 4
/// <summary>
    /// a Simpler version of Singleton class with lazy initialization.
    /// </summary>
    public class AppConfigLazy2
    {
        // static holder for instance, need to use lambda to construct since constructor private
        private static readonly Lazy<AppConfigLazy2> _instance = new Lazy<AppConfigLazy2>(() => new AppConfigLazy2());

        /// <summary>
        /// Prevents a default instance of the <see cref=&quot;AppConfigLazy2&quot;/> class from being created.
        /// </summary>
        private AppConfigLazy2()
        {

        }
        
        public static AppConfigLazy2 Instance
        {
            get
            {
                return _instance.Value;
            }
        }


        /// <summary>
        /// Gets the current date time.
        /// </summary>
        /// <value>
        /// The current date time.
        /// </value>
        public DateTime CurrentDateTime
        {
            get
            {
                return DateTime.Now;
            }
        }
    }
    

That’s more than one way doing Singleton Pattern Implementation right?, hope that was helpful to you  Some reference links are given below:

NuGet Package – Unity.WebAPI

January 5, 2015 .NET, .NET Framework, .NET Framework 4.5, .NET Framework 4.5.2, ASP.NET, ASP.NET 4.5, ASP.NET MVC, Microsoft, NuGet, Package Manager, VisualStudio, VS2010, VS2012, VS2013, Web API No comments

Today I came across this interesting Nuget Package for creating ASP.NET Web API project with Microsoft Unity Dependency Injection container.

  • It is pretty simple to configure and install on your existing Web API project or new ones.

Inorder to use it, use the respective NUGET package from below links:

To install Unity.WebAPI, run the following command in the Package Manager Console

PM> Install-Package Unity.WebAPI -Version 0.10.0

To install Unity.WebAPI, run the following command in the Package Manager Console

PM> Install-Package Unity.WebAPI

You can find out more about Unity.WebAPI by visiting – http://devtrends.co.uk/blog/introducing-the-unity.webapi-nuget-package

WCF RIA Services V1.0 SP2–available

November 7, 2013 .NET, .NET Framework, ASP.NET, Microsoft, RIA Services, Silverlight, Visual Studio 2013, VisualStudio, VS2010, VS2012, WCF, Windows, Windows 7, Windows 8, Windows 8.1 No comments

Latest update for WCF RIA Services v 1.0 includes support for Windows 8.1 and VS2010, 2012, 2013.

Version: 4.1.61829.0            |        Date Published:  11/5/2013

Little about WCF RIA Services

    “ WCF RIA Services simplifies the traditional n-tier application pattern by bringing together the ASP.NET and Silverlight platforms. RIA Services provides a pattern to write application logic that runs on the mid-tier and controls access to data for queries, changes and custom operations. It also provides end-to-end support for common tasks such as data validation, authentication and roles by integrating with Silverlight components on the client and ASP.NET on the mid-tier. “
    [Quote – Microsoft]

Download WCF RIA Services v1.0 SP2

Kinect SDK for Windows v 1.8 Released

September 20, 2013 .NET, .NET Framework, Kinect Development, Kinect SDK, KnowledgeBase, Microsoft, Microsoft SDKs, Visual Studio 2013, VisualStudio, VS2010, VS2012, Windows, Windows 7, Windows 8, Windows 8.1, Windows Embedded 7, Windows Store No comments

k4w-logo

Microsoft has released latest version of Kinect SDK for Windows and Kinect Developer Toolkit for Windows. The Kinect for Windows Software Development Kit (SDK) enables developers to create applications that support gesture and voice recognition, using Kinect sensor technology on computers running Windows 7, Windows 8, Windows 8.1, and Windows Embedded Standard 7.

News features available in this SDK are:

  • Color Capture and Camera Pose Finder for Kinect Fusion
  • Webserver for Kinect Data Streams
  • Kinect Background Removal
  • Windows 8.1 Support
  • New Samples!
  • HTML interaction sample
  • Multiple-sensor Kinect Fusion sample.
  • Adaptive UI sample
  • Realistic color capture with Kinect Fusion.
  • Improved tracking robustness with Kinect Fusion.

    The Kinect for Windows SDK, driver, and runtime v1.8 are 100% compatible with Kinect for Windows v1.0, 1.5, 1.6, and 1.7 applications.

    The Kinect for Windows SDK includes the following:
  • Drivers for using Kinect for Windows sensors on a computer running Windows 7, Windows 8, Windows 8.1, and Windows Embedded Standard 7
  • Application programming interfaces (APIs) and device interfaces
  • Note: Samples, tools, and other valuable development resources are available in the Kinect for Windows Developer Toolkit.
    To learn more about the SDK visit:

DOWNLOAD:

Kinect for Windows SDK v1.8

Kinect for Windows Developer Toolkit v1.8

Kinect for Windows Runtime 1.8

Kinect for Windows Human Interface Guidelines

Disable Client Side validation on a button click – ASP.NET MVC

September 16, 2013 .NET, .NET Framework, ASP.NET, ASP.NET 4.5, ASP.NET MVC, Back-2-Bascis, Codes, JavaScript, jQuery, Microsoft, Snippets, VisualStudio, VS2010, VS2012 No comments

ASP.NET MVC we use client side validation using jQuery.validate plugin, which will be based on Model – Data Annotation validation attributes.

In some cases we might want to disable such validation on a button click wherever it is not needed.

For example:

The below code block will register validation block for Title property in the Model, will result in client side validations fired when user click on button.

<div class="editor-field">
          @Html.EditorFor(model => model.Title)
          @Html.ValidationMessageFor(model => model.Title)
     </div>
<input type="submit" name="backButton" value="Back" title="Go back to Prev step." /> 

We can disable the client side validation check for a button using the “disableValidation=true” attribute for the button.

<script type="text/javascript">
  document.getElementById("backButton").disableValidation = true;
</script>

OR

<input type="submit" name="backButton" value="Back" 
 title="Go back to Prev Step" disableValidation="true" />

OR

You disable client-side validation on a button by adding the css style class “cancel” to it.

That will look like below example:

<input type="submit" name="backButton" value="Back"
 title="Go back to Prev Step" class="mybtn-style cancel" />

These are the different ways you can disable the client side validations. Hope it was helpful.

Sending Mobile Push notification using C#/.NET (iOS, Android, Windows Phone 8, Windows 8 and Blackberry)

August 9, 2013 .NET, ANDROID, Blackberry, Extensions, iOS, iPhone, KnowledgeBase, Microsoft, Microsoft SDKs, Mobile, Mobile Services, Mobile-Development, Nokia, Third-Party-Libraries and Frameworks, VisualStudio, VS2010, VS2012, Windows, Windows 8 apps development, Windows Phone, Windows Phone 8, Windows Phone 8.0 SDK, Windows Phone Development, Windows Phone SDK, Windows Phone Store, Windows SDK, Windows Store, Windows Store Development 2 comments

This is an update blog to my earlier blog about Sending Apple iOS Push notifications using C#.

With that blog – I  introduced you to  how to send push notification using Open Source library APNSharp, by the developer John Redth.  Redth announced that library is already deprecated.

Redth came up with  with another open source project called as PushSharp:,published under apache software foundation license.

PushSharp is a server-side library for sending Push Notifications to iOS (iPhone/iPad APNS), Android (C2DM and GCM – Google Cloud Message), Windows Phone, Windows 8, Amazon, Blackberry, and (soon) FirefoxOS devices!. Single library serves the purpose of sending push notifications to multiple platforms. Pretty decent isn’t it?

Here is the basic  architecture:

image

Features of PUsHSHARP

  • Supports sending push notifications for many platforms:
    • Apple (APNS – iPhone, iPad, Mountain Lion)
    • Android (GCM/C2DM – Phones/Tablets)
    • Chrome (GCM)
    • Amazon (ADM – Amazon Device Messaging)
    • Windows Phone 7 / 7.5 / 8 (including FlipTile, CycleTile, and IconicTile Templates!)
    • Windows 8
    • Blackberry (BIS and BES via PAP)
    • Firefox OS (Coming soon)
  • Fluent API for constructing Notifications for each platform
  • Auto Scaling of notification channels (more workers/connections are added as demand increases, and scaled down as it decreases)

Implementation using PushSharp is straight forward

Here’s some sample code: shared by Redth

//Create our push services broker
var push = new PushBroker();

//Registering the Apple Service and sending an iOS Notification
var appleCert = File.ReadAllBytes("ApnsSandboxCert.p12"));
push.RegisterAppleService(new ApplePushChannelSettings(appleCert, "pwd"));
push.QueueNotification(new AppleNotification()
                           .ForDeviceToken("DEVICE TOKEN HERE")
                           .WithAlert("Hello World!")
                           .WithBadge(7)
                           .WithSound("sound.caf"));


//Registering the GCM Service and sending an Android Notification
push.RegisterGcmService(new GcmPushChannelSettings("theauthorizationtokenhere"));
//Fluent construction of an Android GCM Notification
//IMPORTANT: For Android you MUST use your own RegistrationId here that gets generated within your Android app itself!
push.QueueNotification(new GcmNotification().ForDeviceRegistrationId("DEVICE REGISTRATION ID HERE")
                      .WithJson("{"alert":"Hello World!","badge":7,"sound":"sound.caf"}"));

You can get the Push Sharp for your .NET projects from below mentioned links:

Binaries from NuGet: https://www.nuget.org/packages/PushSharp 

To install PushSharp, run the following command in the Package Manager Console

PM> Install-Package PushSharp

Source Code from GitHub: https://github.com/Redth/PushSharp

Documentation and Implementation Guides available at wiki page: https://github.com/Redth/PushSharp/wiki 

Quick links to implementation guides

You can read my previous blogs here:

Sending Apple iOS Push notifications using C#

Apple Push Notifications Service API & C#