CodeSnippets

WordPress Blog in Azure App Service In Minutes–Part 01

March 24, 2018 App Service, Azure, Azure Database for MySQL, Back-2-Bascis, CodeSnippets, JumpStarts, KnowledgeBase, Microsoft, OpenSource, Tips & Tricks, Windows, Windows Azure Development No comments

All my life I have been a tech saavy person would make my hands dirty trying out all odds available.

Here I am going to help you with setting up your own WordPress Blog in Azure App Service.

SPOILER ALERT: We will be using a B1 – Basic instance to save the cost.

image

Step 1: Login to Azure Portal

Step 2: Click on New

Step 3: Search for “Wordpress” among resources  and Select WordPress

image

Step 4: Click on ‘CREATE’

image

Step 5: Enter App Service Instance Name

image

Step 6: Now Select Database Provider. We need MySQL as the database and we have two options provided by Azure

1. Azure Database for MySQL ( a managed MySQL instance)  which has become publically available few days back.

2. MySQL In App (an instance hosted within App Service instance, basically your web app and mysql will be sharing the computing capabilities of the instance).

For the interest of the article, I will go with Option 2: MySQL InApp

image

Step 7: Specify App Service Plan /Location

As metioned in the spoiler we will go with a B1 Basic tier in West Europe location.

image

Step 8: Turn Application Insights ON and Specify location (This is optional, you do not want Application Insights performance logging for your blog, you can simply ignore)

Step 9: You are ready to go, click on [CREATE] to start the deployment.

image

Step 10: Now you see the deployment in progress message in Azure Portal.

image

image

Wait until this deployment is finished to setup WordPress initial configuration for use along with your custom domain.  We will continue with our setup in next part of this series.

Getting Started local development with Azure Cosmos DB services – Part 2

May 29, 2017 .NET, .NET Core 1.0, .NET Core 1.0.1, .NET Framework, ASP.NET, Azure, Azure SDK Tools, Azure Tools, Cloud Computing, CodeSnippets, CosmosDB, Document DB, Microsoft, PaaS, SaaS, Visual Studio 2015, Visual Studio 2015 Update 3, Visual Studio 2017, VisualStudio, VS2015, VS2017, Windows, Windows 10, Windows Azure Development, Windowz Azure No comments

In my previous article we discussed about setting local development environment using Cosmos DB Emulator for Windows. With this part 2 of the article, we will cover developing, debugging and integration related aspects of using Cosmos DB Emulator.

Developing with Cosmos DB Emulator

Once you have Cosmos DB emulator installed and running on your machine, you can use any supported Cosmos DB SDK or Cosmos DB REST API to interact with emulator. This process is same as you are using a Cosmos DB cloud service.

Cosmos DB Emulator also provides a build-in visual explorer through which you can view,create and edit collections and documents.

image

Before you integrate Cosmos DB SDK or Cosmos DB REST API you would need to generate master key for authentication. Unlike cloud service, Cosmos DB emulator only support single fixed account and master key.  You would not be able to communicate with Emulator without this master key.

Default Master Key:

Account name: localhost:<port>

Account key: C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==

PS: This key is only to be used in Emulator. You cannot use the same key for Production(Cosmos DB Cloud Service).

Furthermore, if you want to set your own key. You can go to command line references and run DocumentDB.Emulator.exe with sufficient command switch to set your own key. Remember it should meet the key security requirements. See command-line tool reference for more information.

The Azure Cosmos DB Emulator is installed by default to the C:\Program Files\Azure Cosmos DB Emulator  or C:\Program Files\DocumentDB Emulator  directory.

Once you have account name and key, you are good to go with development and debugging using Azure Cosmos DB emulator.

Let us start looking at how to use CosmosDB SDK. Once you add Cosmos DB SDK for .NET from NUGET sources. You would need to import the following namespaces to reference necessary classes.

 using Microsoft.Azure.Documents;
   
 using Microsoft.Azure.Documents.Client;
   
 using Microsoft.Azure.Documents.Linq;

Simple code to establish connection:

// Connect to the Azure Cosmos DB Emulator running locally use DocumentClient class in : 
DocumentClient client = new DocumentClient(
    new Uri("https://localhost:8081"), 
    "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==");

In the above code block we are directly embedding endpoint, key in the source code.But as a suggested approch keeping in mind to easily point to production service would be maintain the key in Web.config appSettings.

   <add value="https://localhost:8081/" key="endpoint"/>
    <add value="C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==" key="authKey"/>
 

Add NuGet reference to Microsoft.Azure.DocumentDB  (always use the latest version of the library)

image

For the ease of this article, I am going to use the existing ToDoList sample from DocumentDB Samples provided by Microsoft. You can originally find the same source from C:\Program Files\DocumentDB Emulator\Packages\DataExplorer\quickstart.

image

Copy and Unzip DocumentDB-Quickstart-DotNet.zip and open todo.sln in Visual Studio 2017 and your solution structure will look like below:

image

Now run the application in your Visual Studio.

1. You will see an initial screen:

image

2. Click on Create New:

image

3. New record will be added to your Azure Cosmos DB Emulator:

image

4. To verify in Cosmos DB emulator now open Cosmos DB explorer, click on Collections and Select ToDoList

image

5.Expand Documents and select item with id:da305da3-c1dc-4e34-94d9-fd7f82d26c58

image

Hope this article was helpful for you with initial development.  Share your feedback through comments and share this to your friends and colleagues.

Useful Links:

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

Free eBooks from Microsoft Press on Windows 8 and Windows Server 2012

December 1, 2012 .NET, All, CodeSnippets, Community, DevLabs, Help Links, Microsoft, Microsoft Press, MSDN, Must-Have, Recommends, VisualStudio, VS2012, Windows, Windows 8, Windows Server 2012, Windows Store No comments

Introducing Windows 8: An Overview for IT Professionals (Final Edition)

image

You can download the eBook in:
Introducing Windows 8- An Overview for IT Professionals – PDF ebook

Introducing Windows 8-An Overview for IT Professionals – Mobi format for Kindle
Introducing Windows 8-An Overview for IT Professionals – ePub format

If you prefer a hard copy of the final book, you can order it here for $14.99 from official distributor, O’Reilly Media.

Introducing Windows Server 2012 (RTM Edition)

675353.indd

PDF – Introducing Windows Server 2012 RTM Edition – PDF ebook

EPUB – Introducing Windows Server 2012 RTM Edition – ePub format

MOBI – Introducing Windows Server 2012 RTM Edition – MOBI format (for Kindle)

If you prefer a hard copy of the book, you can order it here for $14.99 from official distributor, O’Reilly Media.

 

 

Programming Windows 8 Apps with HTML, CSS, and JavaScript (Final Edition)

672611.indd 

You can download the eBook in:

PDF – http://go.microsoft.com/FWLink/?Linkid=270056 (17.9 MB)

EPUB – http://go.microsoft.com/FWLink/?Linkid=272592 (37.3 MB)

MOBIhttp://go.microsoft.com/FWLink/?Linkid=272591 (69.5 MB)

 

Provided to by Microsoft Press Team Blog

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);
                        }
                    }

                }

            }

        }

    
    }
}