Portable Class Library

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:

Visual Studio 2013 Update 5 (2013.5) RC–Released

May 5, 2015 .NET, .NET Framework, .NET Framework 4.5, .NET Framework 4.5.2, ASP.NET, ASP.NET 4.5, ASP.NET MVC, BCL(Base Class Library), KnowledgeBase, Microsoft, Microsoft SDKs, Portable Class Library, Visual Studio 2013, VisualStudio, VS2013, Windows, Windows 7, Windows 8, Windows 8.1, Windows Phone, Windows Phone 8 No comments

Microsoft has released an release candidate version for VS2013 Update 5 (short: 2013.5).

This update is the latest in a cumulative series of technology improvements and bug fixes for Visual Studio 2013.

What’s new in Visual Studio 2013 Update 5
  • Current iteration query token
  • Team Project Rename support for Local Workspaces : –  [ability to update local workspaces after a team project is renamed. Performing a get or check-in will automatically correct the workspace mapping so that it uses the new team project name.]

WARNING: All prior releases of the Tools for Apache Cordova are incompatible with Update 5. If you have previously installed a Tools for Apache Cordova CTP extension, you must uninstall that extension before installing Visual Studio 2013 Update 5.

Download: Visual Studio 2013 Update 5 (2013.5) RC

KB – https://support.microsoft.com/en-us/kb/3021976?wa=wsignin1.0 

https://www.visualstudio.com/news/vs2013-update5-vs

Visual Studio 2015 RC–Download

April 30, 2015 .NET, .NET Framework, .NET Framework 4.6, ASP.NET, ASP.NET 5.0, ASP.NET AJAX, ASP.NET MVC, BCL(Base Class Library), Microsoft, Microsoft SDKs, MSDN, Portable Class Library, SignalR, Trial Downloads, Updates, Visual Studio 2015, VisualStudio, VS2015, Web API, Web API v2.0, Windows, Windows 10, Windows 7, Windows 8, Windows 8.1, Windows Phone 8.0 SDK, Windows Phone SDK 2 comments

During #Build2015 event Microsoft has unveiled Visual Studio 2015 RC (Release Candidate) with lots of improvements and fixes to CTP version of Visual Studio. RC would be a near release quality and your see it is stable than ever.

Release Date: 29/APR/2015
Release Notes: View Release notes

Download

Other Associated Products

Visual Studio 2015 – ctp6

February 23, 2015 .NET, .NET Framework, ASP.NET, ASP.NET 4.5, Azure, Azure SDK, BCL(Base Class Library), C#.NET, IE, IIS, Microsoft SDKs, Portable Class Library, SQL Azure, SQL Server, Updates, Visual Studio SDK, VisualStudio, VS2015, WCF, Web API, Windows Phone SDK, Windowz Azure No comments

Microsoft today has released Visual Studio 2015 Community Technology PreviewĀ 6 (CTP 6), which includes some new featuresĀ and improvements, such as new UI debugging tools for XAML, new Control Flow Guard security tool, and feature updates to ASP.NET framework.

For more information about what’s new in this release, please see the release notes.

Download Visual Studio 2015 Ultimate (web | iso)

 

WP8 Developer Series–Getting to know Common API’s for Windows Phone 8 and Windows 8

November 4, 2012 .NET, .NET Framework, .NET Framework 4.5, All, C#.NET, Community, KnowledgeBase, Microsoft, Microsoft SDKs, Mobile-Development, MSDN, Portable Class Library, VisualStudio, VS2012, Windows, Windows 8, Windows 8 apps development, Windows Phone, Windows Phone 7.1 SDK, Windows Phone 8, Windows Phone 8.0 SDK, Windows Phone Development, Windows Phone SDK, Windows Store Development 2 comments

WindowsPhone8.svg Windows 8 logo and wordmark.svg

 

[ Windows 8 and Windows Phone 8 logos are trademarks of Microsoft ]

Windows Phone 8 is the second generation of the Windows Phone mobile operating system by Microsoft, officially announced the release to manufacture on 29th OCT 2012. Previous Windows Phone versions were all based on old CE kernel and with Windows Phone 8 – Microsoft made sure to shift the focus to a better kernel which can handle multi-core processing capabilities. That why Microsoft has choose Windows NT based kernel as the base kernel for Windows Phone 8.

Windows 8 and Windows Phone 8 are sharing same core level technology(from kernel to networking and driver support, all of that will be common on Windows 8 and Windows Phone 8), Microsoft calls it ā€˜Shared Core’. Windows Phone 8 will include more features aimed at the enterprise market, such as device management, BitLocker encryption (which is already included part of Windows 8), to facilitate all these common features – that is where ā€˜Shared Core’ comes in to picture.

If you would like to know further about Shared Core – suggest going through Joe Belfiore’s video

Having a Shared Core will save lots of development time – if we are targeting for both the platforms (Windows 8 and Windows Phone 8), that is where Microsoft has done the magic. Microsoft has made sure that development will be lot easier if you can leverage the same code base for both Windows and Windows Phone 8, with minor changes. This is really a good move as a Unified platform.

Developing Applications for Windows Phone 8 and Windows 8

Windows Phone 8 and Windows 8 share the same .NET Framework engine.You can leverage the same .NET engine in your XAML apps for Windows Phone 8 and Windows 8, and use sharing techniques to maximize code reuse for these apps on both platforms.

Now we will try to familiarize with common API’s on both platform which can save our time while developing applications targeting both.

Following part’s of this article is prepared based on the Original MSDN Source – Windows Phone 8 and Windows 8 platform comparison

1. Common Native API’s

As a Windows Phone developer now you can develop Games in C++  using new Windows 8 aligned Direct3D application model.

The set of native APIs that are common to Windows Phone 8 and Windows 8 are listed below:

  • DirectX 11.1
  • XAudio2
  • MediaEngine
  • STL
  • CRT
  • WinSock

Additional references:

2. Common Windows Runtime API’s

Windows Runtime is a technology first introduced in Windows 8 and which offers a core infrastructure, a common type system, and a standard programming model.

It is firat implemented in C++ and ported into C#, VB, C++, and JavaScript, so it is easy to consume with the language of your choice.

  • A subset of Windows Runtime is built natively into Windows Phone 8, with the functionality exposed to all supported languages.
  • This gives you the ability to use the same API for common tasks such as networking, working with sensors, processing location data, and implementing in-app purchase.
  • By using common Windows Runtime API in your app, you increase the potential to share code between your Windows Phone 8 and Windows Store apps to save time and improve the maintainability of your apps over time.

[Source – msdn]

The following list is the Windows Runtime APIs that are common to both platforms:

  • Networking
  • Sensors
  • Proximity
  • Storage
  • DataSaver/Connection Manager
  • Location
  • Touch
  • Online Identity
  • Keyboard
  • Launchers & Choosers
  • In-App Purchase
  • Sensors
  • Threading
  • Base Types/ Windows.Foundation

3. Similar UI Controls

Between Windows Phone 8 and Windows 8 XAML controls you will see lots of similarities. Same control name, class name etc – this makes the use of same code and controls on both the platforms. Developers will be familiar with both the platforms, and do not have to spend much time in porting from one to another.

  • The set of controls available on Windows Phone 8 is available in the System.Windows.Controls namespace.
  • The set of controls used on Windows 8 is in the Windows.UI.Xaml.Controls namespace.

You may read further about it on: XAML controls comparison between Windows Phone 8 and Windows 8.

4. Shared Engine

Windows 8 and Windows Phone 8 shares the same .NET Framework engine. You can leverage the same .NET engine in your XAML apps for Windows Phone 8 and Windows 8, and use sharing techniques to maximize code reuse for these apps on both platforms.

For more info, see .NET API for Windows Phone.

[ Content Source – msdn on Windows Phone 8 and Windows 8 platform comparison ]

 

Recommended Reads:

Concepts and architecture for Windows Phone

Maximize code reuse between Windows Phone 8 and Windows 8

XAML for Windows Phone

Learn about Windows Store app development

Learn about Developing apps for Windows Phone

XAML controls comparison between Windows Phone 8 and Windows 8.

What’s new in Windows Phone SDK 8.0

Develop Windows Store apps using Visual Studio 2012.