Codes

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:

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.

WP8Dev– How to identify the sensors supported on your Windows Phone

August 12, 2013 C#.NET, Codes, KnowledgeBase, Microsoft, Microsoft SDKs, Mobile-Development, VisualStudio, VS2012, Windows, Windows Phone, Windows Phone 8, Windows Phone 8.0 SDK, Windows Phone Development, Windows Phone SDK, Windows Phone Store, XAML No comments

This post will give you an  overview on how to identify the sensors supported on your Windows Phone. As a developer when you are developing for Windows Phone – and your application would need to interact with certain sensors in windows phone to achieve a certain functionality, you would need to verify whether the sensors are supported in  targeted devices.

Windows Phone 8 platform has support for the following sensors

  • Motion sensor  
  • Accelerometer
  • Compass
  • Gyroscope

You can access these API’s through the below namespace:

Microsoft.Devices.Sensors

You can check for any of the sensor support through “IsSupported” boolean property of the class

  • Motion sensor   [ Microsoft.Devices.Sensors.Motion ]
  • Accelerometer  [ Microsoft.Devices.Sensors.Accelerometer ]
  • Compass [ Microsoft.Devices.Sensors.Compass ]
  • Gyroscope  [ Microsoft.Devices.Sensors.Gyroscope ]

Here is the sample code block:

  public static string GetSensors()
        {
               StringBuilder sensorsList = new StringBuilder();

                if (Microsoft.Devices.Sensors.Gyroscope.IsSupported)
                {
                    sensorsList.Append("Gyroscope, ");
                }

                if (Microsoft.Devices.Sensors.Compass.IsSupported)
                {
                    sensorsList.Append("Compass, ");
                }

                if (Microsoft.Devices.Sensors.Accelerometer.IsSupported)
                {
                    sensorsList.Append("Accelerometer, ");
                }

                if (Microsoft.Devices.Sensors.Motion.IsSupported)
                {
                    sensorsList.Append("Motion,");
                }

            return sensorsList.ToString();
        }

Note: Only Accelerometer is supported in Windows Phone 8 emulator. To test remaining capabilities, you would need to deploy the application on a real Windows Phone device.

HTML5 – Introduction to HTML5Shiv for Internet Explorer 6/7/8

January 3, 2013 All, Back-2-Bascis, Codes, CodeSnippets, Community, CSS, CSS 3, HTML, HTML5, JavaScript, KnowledgeBase, MSDN, StyleSheets, Web 2 comments

HTML5Shiv is a JavaScript workaround, discovered by Sjoerd Visscher, to enable support styling of HTML5 elements in versions of Internet Explorer prior to version 9.0, which do not allow unknown elements to be styled without JavaScript. Means your CSS classes and attributes will not be applied to the particular HTML5 specific display element, until and unless the object is available in the DOM tree.

What HTML5Shiv does is that it creates the objects for all known HTML5 elements(of the Page) in the DOM tree?. This gives the browser an implication that the particular element is supported and available in the DOM tree and it applies the specific CSS classes to the element.

Follow these simple steps to integrate HTML5Shiv to your existing page:

Step 1: Get HTML5Shiv binary – You can get HTML5Shiv binary(html5shiv.js) from  http://code.google.com/p/html5shiv/

Step 2: Insert the necessary code block in the <head> element of your html page (after or before your CSS)

code block:

<blockquote><p>&lt;!--[if lt IE 9]&gt;<br />&lt;script src=&quot;scripts/html5shiv.js&quot;&gt;&lt;/script&gt;<br />&lt;![endif]—&gt;</p></blockquote>

NB: Assuming that html5shiv.js is kept under the scripts folder under the root folder of your web application.

Lets look for a simple example:

Look at the below html sample, with an article element:

Copy the below code block  in to notepad and save as ‘test.html’ – to a location wherever you like 🙂

<!DOCTYPE HTML>
<html>
<head>
     <style>
          article {
               font-size: 22px;
               color: orange;
          }
     </style>
</head>
<body>
     <article>Hello!</article>
</body>
</html>

Try to Browse the sample in Internet Explorer 7.0(by double clicking on ‘test.html’ file) and you can see that font color and font size are not applied and as a default fallback – it is displaying text in a normal font and color. It is because browser will not apply the CSS to an unknown element, HTML5 elements are aliens 🙂 for IE 8.0 and below.

[Before – HTML5 Shiv is applied]

HTML5Code_before

Now try to apply the HTML5Shiv code block on to the above sample and see the magic. Modified code block will look like below:

&lt;!DOCTYPE HTML&gt;
&lt;html&gt;
&lt;head&gt;
&lt;!--[if lt IE 9]&gt;<br />&lt;script src=&quot;scripts/html5shiv.js&quot;&gt;&lt;/script&gt;<br />&lt;![endif]--&gt;
     &lt;style&gt;
          article {
               font-size: 22px;
               color: orange;
          }
     &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
     &lt;article&gt;Hello!&lt;/article&gt;
&lt;/body&gt;
&lt;/html&gt;

[After – HTML5 Shiv is applied]

HTML5Code_after

Very nice! right?. Yes, it is indeed helpful for enabling backward support of your HTML5 elements styling on IE 6,7,8 versions.

DOWNLOAD and USE

You can get HTML5Shiv binary from here: http://code.google.com/p/html5shiv/

and Full original, uncompressed source available here: https://github.com/aFarkas/html5shiv

Hope you enjoy this nice tip.

Courtesy: Wikipedia and Google Code

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!

Zip(Archive) API’s in .NET Framework 4.5 – ZipArchive Class

October 22, 2012 .NET, .NET Framework, .NET Framework 4.5, All, Back-2-Bascis, C#.NET, Codes, CodeSnippets, General, Help Links, KnowledgeBase, Microsoft, Samples, VB.NET, VisualStudio, VS2012 1 comment

With release of .NET Framework 4.5, Microsoft has introduced new classes in to System.IO.Compression namespace. These classes will add the necessary programming support for Zipping(Achiving), and Extracting support for Zip Files in your .NET Source Code.

Below are the newly introduced classes as part of .NET Framework 4.5:

ZipArchive – Represents a package of compressed files in the zip archive format.

ZipArchiveEntry – Represents a compressed file within a zip archive.

ZipFile – Provides static methods for creating, extracting, and opening zip archives.

ZipFileExtensions – Provides extension methods for the ZipArchive and ZipArchiveEntry classes.

In this blog post I am going to discuss about ZipArchive class which will help you with most of the important tasks in Archiving a file or folder using .NET.

The ZipArchive class enables you to work with a package of compressed files. The package contains an entry for each compressed file. You can:

  • Retrieve an entry by using the GetEntry method.
  • Retrieve the entire collection of entries by using the Entries property.
  • Create a new entry in the package by calling the overloaded CreateEntry method.

If you add reference for the System.IO.Compression.FileSystem assembly in your project, you can access three extension methods (from the ZipFileExtensions class) for the ZipArchive class: CreateEntryFromFile, CreateEntryFromFile, and ExtractToDirectory. These extension methods enable you to compress and decompress the contents of the entry to a file.

The System.IO.Compression.FileSystem assembly is not available for Windows Store apps.

In Windows Store apps, you can compress and decompress files by using the DeflateStream or GZipStream class, or you can use the Windows Runtime types Compressor and Decompressor.

Here is the quick sample that would help you to understand how to use ZipArchive class. Code is self explanatory – hope that helps. There are three methods ZipFiles – zip all files in a folder, ExtractFile – to extract files with specificname, ExtractFiles – extract multiple files.

Please go through the below code snippet. If you need additional information: visit MSDN Ref on System.IO.Compression, and in later posts we might discuss about the ZipFile class in more detail.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO.Compression;
using System.IO;

namespace ConsoleApp01
{
    class Program
    {
        static void Main(string[] args)
        {
            string targetZip = AppDomain.CurrentDomain.BaseDirectory + "\" + System.Guid.NewGuid().ToString() + ".zip";

            string sourceFolder = AppDomain.CurrentDomain.BaseDirectory + "\Sample01" ; //We are going to zip the whole contents of the folder. 

            Console.WriteLine(String.Format("Now Archiving the folder/file {0}, to target zip:{1} ", sourceFolder, targetZip));

            //Zipping the folder 
            ZipFiles(sourceFolder, targetZip);



            string extractFolder = AppDomain.CurrentDomain.BaseDirectory + "\" + Path.GetFileNameWithoutExtension(targetZip);

            Console.WriteLine(String.Format("Now Extracting the file {0}, to location:{1} ", targetZip, extractFolder));

            //Extract the entire Zip file 
            ExtractFiles(targetZip, extractFolder);



            //Extract files based on search pattern such as *.txt
            string extractFolder2 = AppDomain.CurrentDomain.BaseDirectory + "\" + Path.GetFileNameWithoutExtension(targetZip) + "12";

            Console.WriteLine(String.Format("Now Extracting the selected file(s) {0}, to location:{1} ", targetZip, extractFolder2));
            
            //Extract the entire Zip file 
            ExtractFiles(targetZip, extractFolder2, "*.txt");

            Console.WriteLine("Press any key to exit");

            Console.ReadKey();
        }

        /// <summary>
        /// Zips the files from the source folder - for now single level - assuming that we will be zipping all the files in a folder. 
        /// not the child folders and files in it, we will ignore it.
        /// </summary>
        /// <param name="sourceFilesFolderPath">The source files folder path.</param>
        /// <param name="targetZipFilePath">The target zip file path.</param>
        /// <param name="searchPattern">The search pattern.</param>
        public static void ZipFiles(string sourceFilesFolderPath, string targetZipFilePath, string searchPattern = "")
        {
            //if Source Directory exists. 
            if (Directory.Exists(sourceFilesFolderPath))
            {
                using (FileStream zipToOpen = new FileStream(targetZipFilePath, FileMode.OpenOrCreate))
                {
                    //Open Archieve for update
                    using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
                    {
                        //Getting directory info
                        DirectoryInfo dInfo = new DirectoryInfo(sourceFilesFolderPath);


                        //Getting all files list in the folder 
                        FileInfo[] filesList = dInfo.GetFiles(searchPattern);

                        if (String.IsNullOrEmpty(searchPattern)) //fail safe to retrieve all
                            filesList = dInfo.GetFiles();

                        if (filesList != null && filesList.Length > 0)
                        {
                            //Creating archieve entry for each file in the folder 
                            foreach (FileInfo file in filesList)
                            {
                                archive.CreateEntryFromFile(file.FullName, file.Name);
                            }
                        }


                    }

                }
            }
            else
            {
                throw new DirectoryNotFoundException(String.Format("Source folder: {0} not found",sourceFilesFolderPath);
            }

        }




        /// <summary>
        /// Extracts the files.
        /// </summary>
        /// <param name="sourceZipPath">The source zip path.</param>
        /// <param name="targetExtractPath">The target extract path.</param>
        /// <param name="conditionalExtractPattern">The conditional extract pattern.(OPTIONAL)</param>
        public static void ExtractFiles(string sourceZipPath, string targetExtractPath, string conditionalExtractPattern = "")
        {
            string zipPath      = sourceZipPath;  //Source Zip File 
            string extractPath  = targetExtractPath; //Path to Extract

            if (!Directory.Exists(targetExtractPath))
            {
                Directory.CreateDirectory(targetExtractPath);
            }

            using (ZipArchive archive = ZipFile.OpenRead(zipPath))
            {

                //STEP 1
                foreach (ZipArchiveEntry entry in archive.Entries)
                {
                    //Conditional extract
                    if (!String.IsNullOrEmpty(conditionalExtractPattern))
                    {
                        if (entry.FullName.EndsWith(".txt", StringComparison.OrdinalIgnoreCase))
                        {
                            entry.ExtractToFile(Path.Combine(extractPath, entry.FullName),true);
                        }
                    }
                    else // extract all..
                    {
                        entry.ExtractToFile(Path.Combine(extractPath, entry.FullName),true);
                    }

                    
                }

                //Or EXTRACT ALL USING 

                //STEP 2
                //archive.ExtractToDirectory(targetExtractPath);

            } 

        }




        /// <summary>
        /// Extracts the file.
        /// </summary>
        /// <param name="sourceZipPath">The source zip path.</param>
        /// <param name="targetExtractPath">The target extract path.</param>
        /// <param name="extractFileName">Name of the extract file.</param>
        public static void ExtractFile(string sourceZipPath, string targetExtractPath, string extractFileName)
        {
            string zipPath = sourceZipPath;  //Source Zip File 
            string extractPath = targetExtractPath; //Path to Extract

            using (ZipArchive archive = ZipFile.OpenRead(zipPath))
            {
                //STEP 1
                foreach (ZipArchiveEntry entry in archive.Entries)
                {
                    //Conditional extract
                    if (!String.IsNullOrEmpty(extractFileName))
                    {
                        //Extract the file.
                        if (entry.FullName.EndsWith(extractFileName, StringComparison.OrdinalIgnoreCase))
                        {
                            entry.ExtractToFile(Path.Combine(extractPath, entry.FullName), true);
                        }
                    }

                }

            }

        }

    
    }
}