BCL(Base 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

<br />
 /// &lt;summary&gt;<br />
    /// Singleton class<br />
    /// &lt;/summary&gt;<br />
    public class AppConfig<br />
    {</p>
<p>        private AppConfig()<br />
        {</p>
<p>        }</p>
<p>        /// &lt;summary&gt;<br />
        /// Gets the current date time.<br />
        /// &lt;/summary&gt;<br />
        /// &lt;value&gt;<br />
        /// The current date time.<br />
        /// &lt;/value&gt;<br />
        public DateTime CurrentDateTime<br />
        {<br />
            get<br />
            {<br />
                return DateTime.Now;<br />
            }<br />
        }<br />
        /// &lt;summary&gt;<br />
        /// The _config<br />
        /// &lt;/summary&gt;<br />
        private static AppConfig _config;</p>
<p>        /// &lt;summary&gt;<br />
        /// The pad lock for maintaining a thread lock.<br />
        /// &lt;/summary&gt;<br />
        private static readonly Object padLock = new object();</p>
<p>        /// &lt;summary&gt;<br />
        /// Gets the instance.<br />
        /// &lt;/summary&gt;<br />
        /// &lt;value&gt;<br />
        /// The instance.<br />
        /// &lt;/value&gt;<br />
        public static AppConfig Instance<br />
        {<br />
            get<br />
            {</p>
<p>                if (_config == null)<br />
                {<br />
                    lock (padLock) // making thread-safe<br />
                    {<br />
                        //{<br />
                        if (_config == null) //second level check to make sure, within the short span, another concurent thread didnt initialize the object.<br />
                        {<br />
                            _config = new AppConfig();<br />
                        }<br />
                    }<br />
                }<br />
                //}</p>
<p>                return _config;<br />
            }<br />
        }<br />
    }<br />

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.

<br />
 /// &lt;summary&gt;<br />
    /// a Simpler version of Singleton class with lazy initialization.<br />
    /// &lt;/summary&gt;<br />
    public class AppConfigLazy1<br />
    {<br />
        // static holder for instance, will not get initialized until first use, due to static contructor.<br />
        private static readonly AppConfigLazy1 _instance = new AppConfigLazy1();</p>
<p>        /// &lt;summary&gt;<br />
        /// Prevents a default instance of the &lt;see cref=&amp;quot;AppConfigLazy1&amp;quot;/&gt; class from being created.<br />
        /// &lt;/summary&gt;<br />
        private AppConfigLazy1()<br />
        {</p>
<p>        }</p>
<p>        /// &lt;summary&gt;<br />
        /// for Lazy Initializes the &lt;see cref=&amp;quot;AppConfigLazy1&amp;quot;/&gt; class.<br />
        /// &lt;/summary&gt;<br />
        static AppConfigLazy1()<br />
        {</p>
<p>        }</p>
<p>        public static AppConfigLazy1 Instance<br />
        {<br />
            get<br />
            {<br />
                return _instance;<br />
            }<br />
        }<br />
    }<br />

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

<br />
/// &lt;summary&gt;<br />
    /// a Simpler version of Singleton class with lazy initialization.<br />
    /// &lt;/summary&gt;<br />
    public class AppConfigLazy2<br />
    {<br />
        // static holder for instance, need to use lambda to construct since constructor private<br />
        private static readonly Lazy&lt;AppConfigLazy2&gt; _instance = new Lazy&lt;AppConfigLazy2&gt;(() =&gt; new AppConfigLazy2());</p>
<p>        /// &lt;summary&gt;<br />
        /// Prevents a default instance of the &lt;see cref=&amp;quot;AppConfigLazy2&amp;quot;/&gt; class from being created.<br />
        /// &lt;/summary&gt;<br />
        private AppConfigLazy2()<br />
        {</p>
<p>        }</p>
<p>        public static AppConfigLazy2 Instance<br />
        {<br />
            get<br />
            {<br />
                return _instance.Value;<br />
            }<br />
        }</p>
<p>        /// &lt;summary&gt;<br />
        /// Gets the current date time.<br />
        /// &lt;/summary&gt;<br />
        /// &lt;value&gt;<br />
        /// The current date time.<br />
        /// &lt;/value&gt;<br />
        public DateTime CurrentDateTime<br />
        {<br />
            get<br />
            {<br />
                return DateTime.Now;<br />
            }<br />
        }<br />
    }</p>
<p>

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)

 

Zip(Archive) API’s in .NET Framework 4.5 – Part 2 – ZipFile Class

October 22, 2012 .NET, .NET Framework, .NET Framework 4.5, All, Back-2-Bascis, BCL(Base Class Library), C#.NET, Codes, CodeSnippets, DevLabs, Foundations, Help Articles, KnowledgeBase, Microsoft, Updates, VB.NET, VisualStudio, VS2012, Windows No comments

In my previous post I shared some information on API’s/Classes included as part of System.IO.Compression namespace in .NET Framework 4.5, and given on overview of ZipArchive class. Once such class I would be sharing some insight with post today would be ‘ZipFile‘ class. The ZipFile class provides convenient static methods for working with zip archives:

  1. CreateFromDirectory (3 overloads) – Creates a zip archive that contains the files and directories from the specified directory, uses the specified compression level and character encoding for entry names, and optionally includes the base directory.
  2. ExtractToDirectory ( 3 overloads) – Extracts all the files in the specified zip archive to a directory on the file system and uses the specified character encoding for entry names.
  3. Open (2 overloads) – Opens a zip archive at the specified path, in the specified mode, and by using the specified character encoding for entry names.
  4. OpenRead  – Opens a zip archive for reading at the specified path.

 

To use these methods, you must reference the System.IO.Compression.FileSystem assembly in your project.

image

NB:

  • The System.IO.Compression.FileSystem assembly is not available for Windows Store apps. Therefore, the ZipFile class and ZipFileExtensions class (which is also in the System.IO.Compression.FileSystem assembly) are not available in Windows Store apps.
  • In Windows Store apps, you work with compressed files by using the methods in the ZipArchive, ZipArchiveEntry, DeflateStream, and GZipStream classes.

 

Now the time for creating some sample application.

For the purpose of explaining how to use the above methods – I followed the below steps :

  1. Created a console application in visual studio.
  2. Added Reference to System.IO.Compression and System.IO.Compression.FileSystem assemblies which is part of .NET Framework 4.5.
  3. Created a folder called “Files” and created some plain text files(.txt extension) , this would be out source folder to zip. And created two additional folder for storing zip files(Output) and ExtractLocation folder to extract the zip files.
  4.  image image
  5. and the below sample code snippet is the implementation/usage.
<code>&lt;p&gt;Sample code snippet:&lt;/p&gt; &lt;div&gt; &lt;pre class="brush: c#;"&gt;
</code>

namespace ConsoleApp02
{
class Program
{
static void Main(string[] args)
{
// AppDomain.CurrentDomain.BaseDirectory refers to the
//folder in which the executable or binaries are executing.
// E.g. ConsoleApp02ConsoleApp02binDebug
string startPath = AppDomain.CurrentDomain.BaseDirectory + "\Files";
string zipPath = AppDomain.CurrentDomain.BaseDirectory + "\Output";
string zipFilePath = zipPath + "\" + System.Guid.NewGuid().ToString() + ".zip";

<code>        string extractPath = AppDomain.CurrentDomain.BaseDirectory + &amp;quot;\ExtractLocation&amp;quot;;

        //just a fail-safe to create folders if not exists.
        if (!Directory.Exists(zipFilePath))
            Directory.CreateDirectory(zipFilePath);

        if (!Directory.Exists(extractPath))
            Directory.CreateDirectory(extractPath);

        //Creating a zipFile from folder
        ZipFile.CreateFromDirectory(startPath, zipFilePath);

        //Unzipping a zipFile to a folder
        ZipFile.ExtractToDirectory(zipFilePath, extractPath);

        //
        Console.WriteLine(&amp;quot;Press Any key to exit...&amp;quot;);

        Console.ReadKey();
    }
}
</code>

}

Hope this post is informative. Please keep share this post and give your comments/feedback. Happy coding!