Codes

Azure Cosmos DB–Setting Up New Database using Azure CLI–Sample

October 1, 2018 Azure, Azure Cosmos DB, Codes, CosmosDB, KnowledgeBase, Microsoft, PowerShell, Windows Azure Development No comments

Purpose of this article is to help you with few steps of commands to provision a new Azure Cosmos DB database instance through Azure CLI or Azure Cloud Shell.

Here is the snippet:

 <# 
   This Bash script should help you create a Azure Cosmos DB instance using Azure CLI with bare minimal configuration 
#>

export ACCOUNT_NAME="thingx-retail-store-db"
export DB_RESOURCE_GROUP="thingx-dev"
export DB_LOCATION="southcentralus"
export DB_NAME="Products" 
export DB_THROUGHPUT=1000  ## bare minimal for 500 read and 100 write configuration for a 1KB document.
export DB_COLLECTION_NAME="Groceries"

##Optional: If resource group does not exist create a new one 
az group create --name $DB_RESOURCE_GROUP --location $DB_LOCATION

##1.0 Create the Azure Cosmos DB Account 
az cosmosdb create --name $ACCOUNT_NAME --kind GlobalDocumentDB --resource-group $DB_RESOURCE_GROUP

##2.0 Create Products database in the account  
az cosmosdb database create --name $ACCOUNT_NAME --db-name $DB_NAME --resource-group $DB_RESOURCE_GROUP

##3.0 Create Groceries collection in Products database
az cosmosdb collection create --collection-name $DB_COLLECTION_NAME --partition-key-path "/productId" --throughput $DB_THROUGHPUT --name $ACCOUNT_NAME --db-name $DB_NAME --resource-group $DB_RESOURCE_GROUP


 

For the ease of this article I used Azure Cloud Shell, that you can launch from your azure portal by clicking on the Shell icon on the top portal menu.

image

image

Now you are ready to execute all the commands listed above in the sample bash script

image

Create New Azure Cosmos DB Account

 <span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"></span>
az cosmosdb create --name $ACCOUNT_NAME --kind GlobalDocumentDB --resource-group $DB_RESOURCE_GROUP

image

Create Products Database in the account

az cosmosdb database create --name $ACCOUNT_NAME --db-name $DB_NAME --resource-group $DB_RESOURCE_GROUP

image

Create Groceries collection in Products database

az cosmosdb collection create --collection-name $DB_COLLECTION_NAME --partition-key-path "/productId" --throughput $DB_THROUGHPUT --name $ACCOUNT_NAME --db-name $DB_NAME --resource-group $DB_RESOURCE_GROUP

image

Now if you browse Azure Portal you can see resources created in “thingx-dev” resource group.

image

Upon browsing with Data Explorer you can see the Groceries collection inside Products DB.

image

So that’s the few silly easy steps to create Cosmos DB database from Azure CLI or Azure Cloud Shell. Hope that makes it easy for you.

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:

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!