Reading Notes #271

vs2017

 

 

Suggestion of the week

  • Azure Functions vs Web Jobs: How to choose? (Chris Pietschmann) - Wow! This is the best post I've read about Azure Function. It really describes clearly the differences between the two. A must for every cloud developer.

Cloud


Programming


Databases


Miscellaneous




Reading Notes #270

canada-mapSuggestion of the week


Cloud


Databases


Miscellaneous



Reading Notes #269

AzureFunctionSuggestion of the week


Cloud


Programming


Miscellaneous



Reading Notes #268

microsoft-integration-stencils-pack-v2-4_thumbCloud


Programming


Miscellaneous



Reading Notes #267

IMG_20170208_201247Cloud


Programming


Miscellaneous




Reading Notes #266

Retropie_SplashSuggestion of the week


Cloud


Programming


Databases

  • SQL Database Query Editor available in Azure Portal (Ninar Nuemah) - I was looking for this since the old query tool was removed. I will probably continue to use SQL studio management or VsCode, put what a time saving, and you are investigating a problem... Open a blade right from the Azure portal and voila!

Miscellaneous

  • MVP API Intro (Daron Yöndem) - I love it! I already have few ideas in mind, and I'm curious to see what you will do guys.


Reading Notes #265

msdevMtljan31Suggestion of the week


Cloud


Programming


Databases


Miscellaneous



Reading Notes #264

2017-01-22_21-13-48Cloud


Programming

  • Introducing Docker 1.13 (Docker Core Engineering) - This post summarizes all the great features added in the new release and shows again why Docker is such a fantastic tool in the containers' world.

Databases


Miscellaneous


Reading Notes #263

IMG_20170113_162910Cloud


Programming


Databases



Connect VSCode to Azure SQL Database from everywhere

Visual Studio Code looks like a simple text editor. However, the fact that it running from anywhere (Windows, Linux, MacOs) and that you can highly customize it, make it very special. The way you customize your VSCode is by using extensions. The last extension I installed was MSSQL. In this post, I will explain how to leverage this extension to connect from everywhere to your database.

Installation


Adding the extension is very simple you can go to the Extension menu and type mssqm in the search area; then click Install.

install_mssql

Configuration


To create your connection profile, you could just open Command Palette and type connect, the extension will then ask you to enter the server name, username, password…

connect_longway
To avoid any typo I tend to copy/paste the information, but every time the dialog was losing the focus it was closing. The workarounds to this unfortunate problem was to open the User Settings and specify my connection information. Here is the configuration:

"mssql.connections": [
    {
        "server": "{{put-server-name-here}}",
        "database": "{{put-database-name-here}}",
        "user": "{{put-username-here}}",
        "password": "{{put-password-here}}"
    },
    {
        "profileName": "Azure SQL FBoucher",
        "server": "sqlservername.database.windows.net",
        "database": "demodb",
        "user": "admin",
        "password": "",
        "authenticationType": "SqlLogin",
        "savePassword": true
    }
]

I kept password empty and savePassword equal to true. This way the first time you connect to the database you will need to enter it and it will be saved outside of the user Setting using the Password Management.
Now to connect you only need to open the Command Palette and type connect or mssql, to see the MS SQL: Connect option and select the connection profile you just created.

connect_profile


Using the mssql extension


Of course, you can type any query you like, but the extension is offering not only snippets, but a contextual auto-completion. That mean the VSCode once connected will know all the column’s names of all tables and boost as must your productivity.

snippets
To execute the query a simple Ctrl + E, and voila!

query_and_result


Wrapping up


This fantastic extension is providing a light-weight setup to execute or write any SQL scripts whatever you are on Windows, Linux or MacOS. It doesn’t have all the features of the bigger tool like SQL Server Management, when databases are not your primary focus or even to have a light setup on the go, the Visual Studio Code SQL Server extension is definitely a must.


References:




Reading Notes #262

2017Cloud


Programming


Databases


Miscellaneous

  • Identity vs Permissions (Dominick Baier) - Good post that demystifies some point between two distinct but very often mixed concept.


Reading Notes #261

gummibarchen-359950_960_720Suggestion of the week


Cloud


Programming


Miscellaneous




Need to Nuke an Azure Subscription?

(Ce billet en aussi disponible en français.)


I use very intensely my my.visualstudio (aka MSDN) Azure subscription, to create content for a demo or just to try new feature. So frequently I need to do some cleaning.

multi-resourceGroup-boom

Here a little script that will completely delete all resources of every resources group inside a specific subscription. To be able to execute this script you will need Azure PowerShell cmdlets.

The script asks you to login-in then list all the subscriptions that this account has access. Once you specify which one, it will list all the resource grouped by resource group. Then as a final warning, it will require one last validation before nuking everything.

Be careful.

#================================================================
#= Very dangerous interactive script that delete all rescources 
#= from all rescourcegroup in a specific subscription
#================================================================

# How to install and configure Azure PowerShell
# https://docs.microsoft.com/en-us/powershell/azureps-cmdlets-docs/

# Login
Login-AzureRmAccount 

# Get a list of all Azure subscript that the user can access
$allSubs = Get-AzureRmSubscription 

>$allSubs | Sort-Object Name | Format-Table -Property ame, SubscriptionId, State

$theSub = Read-Host "Enter the subscriptionId you want to clean"

Write-Host "You select the following subscription. (it will be display 15 sec.)" -ForegroundColor Cyan
Get-AzureRmSubscription -SubscriptionId $theSub | Select-AzureRmSubscription 

#Get all the resources groups
$allRG = Get-AzureRmResourceGroup

foreach ( $g in $allRG){
    Write-Host $g.ResourceGroupName -ForegroundColor Yellow 
    Write-Host "------------------------------------------------------`n" -ForegroundColor Yellow 
    $allResources = Find-AzureRmResource -ResourceGroupNameContains $g.ResourceGroupName
    if($allResources){
        $allResources | Format-Table -Property Name, ResourceName
    }else{
        Write-Host "-- empty--`n"
    } 
    Write-Host "`n`n------------------------------------------------------" -ForegroundColor Yellow 
}

$lastValidation = Read-Host "Do you wich to delete ALL the resouces previously listed? (YES/ NO)"
if($lastValidation.ToLower().Equals("yes")){
    foreach ( $g in $allRG){
        Write-Host "Deleting " $g.ResourceGroupName 
        Remove-AzureRmResourceGroup -Name $g.ResourceGroupName -Force -WhatIf
    }
}else{
    Write-Host "Aborded. Nothing was deleted." -ForegroundColor Cyan
}




The code is also available on Github: https://github.com/FBoucher/AzurePowerTools


How to use Azure Function App to crush an SQL Database on a schedule

In a project, I needed to run a task every day to process some data in an Azure SQL Database. I thought Azure Function App would be the perfect candidate for that because we can attach them on a schedule, and I will only get charges when they are running. In this post, I will create a function that will be executed every five minutes. It will read the information from an SQL table Person and write the stats in another SQL table Statistic.

Azure Setup


Let's start by creating the Azure Function App. From the Azure portal (portal.azure.com) click the "+" sign on the top left corner and in the Search textbox type Function App. Fill-up the creation form like usual. Note that it will be a good idea to put your Function Appin the same location to what they will be interacting with; in this case an SQL Database. Once the Function App is created, it will be possible to create a new function. For that you can start with an empty one or use one of the multiple templates available. For this post, the TimeTrigger-CSharp was perfectly indicated.

createAzureFunctionApp

On this page that you can configure the schedule. Here, I set it to 0 */5 * * * * because the task will be running every five minutes. It uses Cron expression, and to learn about it you can (should) refer to the documentation. You can edit that value later by going to the Integrate tab the function. Great, now that we have our function, we need to provide the SQL Database connection string. In this demo, I will use App Settings, but it could also be saved in the Azure Key Vault. Remember Function Apps are part of the Azure Apps ecosystem, thereby they have App Settings. To access it, it's really simple.

GoToAppSettings

In the left panel menu click on the Function app setting options, then in the many choices look for Configure app settings. That will open the usual app setting blade that we use with other Web Apps. Scroll down until you've reached the Connection String section. Add your connection string to your server... And don't forget to save!

saveConnStr

Database Setup


For this demo, I will use two simple tables.
CREATE TABLE [dbo].[Person] (
    PersonID     INT NOT NULL IDENTITY(1,1) PRIMARY key,
    Firstname    VARCHAR(50)  NOT NULL, 
    Lastname     VARCHAR(50)  NOT NULL,
    Age          INT  NOT NULL
)
I will insert manually records, adding people with a random age. The Function App on its side, will read the information from the table Person and calculate the average age and the number of people in the population. For finally inserted it into the table Statistic.
CREATE TABLE [dbo].[Statistic] (
    StatisticID    INT NOT NULL IDENTITY(1,1) PRIMARY key,
    Population     INT NOT NULL, 
    AverageAge     INT  NOT NULL,
    DateTaken      VARCHAR(50)  NOT NULL
)

Coding the Function App


The code of this function is not styled or optimized. It was kept very simple so it was obvious was it was doing. Here is the code.
#r "System.Data"
using System;
using System.Configuration;
using System.Data.SqlClient;
public static async Task Run(TimerInfo myTimer, TraceWriter log)
{
    log.Info($"C# Timer trigger function executed at: {DateTime.Now}");  
    var str = ConfigurationManager.ConnectionStrings["sqlConn"].ConnectionString;
    using (SqlConnection conn = new SqlConnection(str))
    {
        var sum = 0;
        var cnt = 0;
        var avr = 0;
        conn.Open();
        var sqlStr = "SELECT Age FROM [dbo].[Person]";
        using (SqlCommand cmd = new SqlCommand(sqlStr, conn))
        {
            var dataReader = await cmd.ExecuteReaderAsync();
            while(dataReader.Read()){
                sum += dataReader.GetInt32(0);
                cnt++;
            }
            avr = (sum / cnt);
            log.Info($"The average actual population is {avr} .");
        }
        var sqlInsert = $"INSERT INTO [dbo].[Statistic](Population, AverageAge, DateTaken) VALUES ( {cnt} , {avr} , '{DateTime.Now}' )";
        using(SqlCommand cmd  = new SqlCommand(sqlInsert, conn)){
            var rows = cmd.ExecuteNonQuery();
            log.Info($"{rows} rows were inserted");
        }
    }  
}
The first line is to add reference to System.Data. Many libraries are already available to any Function App, and just require a reference. When you need an external library, you will need to create a file project.json and add it to the dependencies. Those will be loaded via Nuget. From there, the code talk by itself. Beginning by getting the connection string from the config, getting all the people and doing his magic, then finally inserting his result into the Statistic table.

Let's Run It


Everything is now in place. It's t to use your favorite SQL tool to insert some record into the Person table. Personally, I've created a little console application in .Net Core to do that. I share all about it at the end of this post. Once it's done, you will see the table Statistic growing every five minutes. Voila! Azure Function App a very useful and effective in this scenario. The code, of course, can be part of your repository, and now that Azure Function Tools have just been released you can even code them from Visual Studio!


Little Bonus


For a will now, every time I need to generate data, I tend to use a nice framework that my MVPs buddy the ASP.Net Monsters has done called: GenFu. Available on github, GenFu is a library that generates realistic test data. Here the code I used to generate the population in this demo.
using System;
using System.Data.SqlClient;
using GenFu;
namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            int counter = (args.Length > 0) ? Convert.ToInt32(args[0]) : 5;
            var Users = A.ListOf<Person>(counter);
            var connStr = "Server=YOURSERVERNAME.database.windows.net,1433;Initial Catalog=YOURDATABASENAME;Persist Security Info=False;User ID=YOURUSER;Password=YOURPASSWORD;MultipleActiveResultSets=True;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();
                foreach (var u in Users)
                {
                    var sqlStr = $"INSERT INTO [dbo].[Person] (Firstname,Lastname,Age) VALUES ( '{u.Firstname}' , '{u.Lastname}' , {u.Age} )";
                    using (SqlCommand cmd = new SqlCommand(sqlStr, conn))
                    {
                        var rows = cmd.ExecuteNonQuery();
                        Console.WriteLine($"{rows} rows were inserted");
                    }
                }
                conn.Close();
            }
        }
    }
    public class Person
    {
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public int Age { get; set; }
    }
}
You will need to add Genfu reference to the project.json file.
{
"version": "1.0.0-*",
"buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
},
"dependencies": {
        "Genfu": "1.2.1",
        "System.Data.SqlClient": "4.3.0"
},
"frameworks": {
    "netcoreapp1.0": {
    "dependencies": {
        "Microsoft.NETCore.App": {
        "type": "platform", 
        "version": "1.0.1"
        }
    },
    "imports": "dnxcore50"
    }
},
"runtimes": {
"win-x64":{}
}
}





Happy coding!




Reading Notes #260

shopping-cart-1275482_640Suggestion of the week


Cloud


Programming


Miscellaneous


Reading Notes #259

three-amigos-mainCloud


Programming




Reading Notes #258

AzureAdvisorSuggestion of the week

  • Announcing the public preview of Azure Advisor (Shankar Sivadasan) - This is definitely the most asked question from clients: how can I optimize my solutions. I was very positively surprised by the quality and precision of the suggestions of the advisor service. It's a must.

Cloud


Programming



Lessons learn while trying to deploy a Docker container in Azure

(Ce billet en aussi disponible en français.)


Since I saw Donovan Brown do his demo during the Connect(); // 2016 Keynote, I really want to have a taste of that left click to turn a project to Docker containers. So last Sunday I wake up early and armed with a big bowl of cafe latte start prepping my VM to try it. But as you could imagine, it didn't work on the first attempt, and that what I want to share to you.

DonovanBrown

Let's get started


I build a new VirtualBox virtual machine (VM) using an ISO of Windows 10, then install all the updates to get the anniversary edition. I afterward went to visualstudio.com to get the Visual Studio 2017 RC and install it with a few components: web, azure, etc. And next when looking for Docker for windows. Same here super easy just need to download and install the MSO from docker.com and voila... or not. Like specified in the Docker documentation the installer noticed that Hyper-V was not present in my environment and suggested installing it and reboot the machine. Until then, everything was going fine, but when Docker try to start, after the reboot, I got an error message:

Error creating machine: Error in driver during machine creation: This computer doesn't have VT-X/AMD-v enabled. Enabling it in the BIOS is mandatory

However, the setting was set, as you can see in the screenshot.

VT-xSetting

After a short investigation, I found that VirtualBox was not supporting nested virtualization, yet. Well, let's try another virtualization platform then.

First Success


I created a new VM under VMware Player this time and repeated all the steps as before. After the reboot, the little white whale in the system didn't prompt any error... Was it working? Let's try to create a Nginx Hello-world container to check. And the answer was YES!

2016-11-22_19-00-45

Docker and Azure


Now let's get serious. It's time to do the left click on the project and add Docker Project Support. Then press F5 to try it locally.

ERROR: for mystuff Cannot create container for service mystuff: C: drive is not shared. Please share it in Docker for Windows Settings Encountered errors while bringing up the project..

I got too excited, and I had skipped some reading... It's written black on white in the documentation that you need to share some drive to make it work.

ShareDrice

After that it when smoothly and in few minutes, I got my website to run in a Docker container accessible via localhost:32768. Great! Now to get it available on Azure, I need to create a registry where all the images will be saved. To do that simply left click again on the project, and select Publish. The guided dialog will popup and help you to create and deploy your things. An interesting point is before clicking the "Create" button you will have the option to export your template as a json file, very useful. But for now click Create, then Publish.

DockerPublishing

After a moment you should have a new browser window that will popup with your App now deployed in Azure.

DockerOnline

Wow! That was really a great experience. It's definitely a very simple process to get started. I really appreciate the Docker for Windows and Kitematic user interface. Of course, all the command-line are still available, but now I also have another option for the day where I feel more for clicking instead of typing.

DockerTools

Let's build it and ship it, from any platform to the cloud!



Reading Notes #257

2016-11-20_21-14-57Suggestion of the week

  • Microsoft Connect(); 2016 Recap (Joseph Hill) - Three full day of great content. However, if you are like me, you didn't that much free time. Fortunately, all the presentations are available in video on demand. You need a summary because even if the keynote was really good... it is still 2h30, this post is the place to start.

Cloud


Programming


Miscellaneous



Reading Notes #256

IMG_20161107_104028Cloud

Programming

Miscellaneous



What did you say you are, an MVP?


A few years ago, I decided to put myself in a situation where I’d be in contact with more people. Of course, I got a lot of technical questions, but also, and more often than you may think, people ask me about my MVP title. What’s an MVP? What do you need to do to become one? What do you do when you are an MVP? What do you get as an MVP? You can always come see me and ask me; it would be a pleasure to speak with you. However, for those who want to stay in the shadows, or are not sure how to ask, I decided to write a blog post about it.


What is MVP?

MVP_Logo_Preferred_Cyan300_RGB_300ppiIn short, MVPs are Microsoft Most Valuable Professionals (MVPs). For more than twenty years, Microsoft has given that award to technology experts who passionately share their knowledge with the community. There are close to 4,000 MVPs around the globe specializing in approximately seventeen different categories. MVPs share their passion by writing blog posts, articles, and books, answering questions in forums, and giving presentations in community groups and events.

How I Became an MVP

Firstly, I didn’t do anything to become an MVP. I became an MVP because of what I was doing. And that’s how I think it should be approached.

I’ve always read a lot about new technologies and enjoy working on home “pet projects”. I find that the optimal way to learn is by doing whenever possible. Having real struggles with “features” are the best brain push-up you can get. Because things are changing quickly, and because I was playing with a large variety of technologies, I was keeping notes on my work. First, my notes were on a disk; then I put them online. From time to time, when someone would ask me a question at work, I would search through my notes. Although my online notes were public, the URL was purposely not a friendly one. Before long, co-workers started to ask me if they could have the URL to my notes and I knew it was time to take the first real step into the light.

I still remember clearly that talk I had with Dom, an "Eagle" (tech prime) at the office. I was shy but he told me to give it a try; some people were already liking what I was sharing, and after all, I was doing the work for myself anyways so why not share it with others? Since getting out of your comfort zone is a good way to learn, I decided to start my blog. And just to add a level of difficulty, I decided to do it in English since at the time I only knew French.

I started my blog, FrankysNotes.com, and changed all my funny avatars to my photo. Since starting my blog, I publish my reading notes every Monday. And exactly like the saying goes, “build it, and they will come.” The weeks passed and the number of weekly views on my blog grew from dozens to hundreds. Encouraged, I decided to publish the notes from one of my home projects. Immediately the number of views jumped. I was trying to write more, but it was a very long process since I was definitely not fluent in English. However, every time I published a post, I was really proud. Not only had I successfully finished a project and learned something new, I had also written a post that would help others learn too. At the same time, I joined the Canadian Windows Azure Community Experts group and participated in events.

Sharing my passion through presentations, blog posts, and meetups was enough for me to be welcomed into the big MVP family.

CanadianMVPFamilly

What I’ve Been Up to Since Becoming an MVP

Having been recognized as an MVP didn’t change me. I’m still very nervous before a presentation or publishing a blog post. I continue to code late at night on personal projects. More than ever, I’m excited when after a long battle with a bug, I finally find the way to make everything work.
What is different is that I now have more opportunities. All those friends reaching out to me (and other times it’s me reaching out to them) to ask a quick question or invite me to join them at an event. It’s up to me to embrace those challenges, get out of my comfort zone and continue to share my passion and my journey through the technology I like so much. I’ve started a second blog, in French this time, called CloudenFrancais.com. I’ve also joined the MSDEVMTL (Cloud) community group in Montreal, Quebec, Canada as a co-admin and started a new community in Ottawa, Ontario, Canada called OttCloudTech.

Thank you for reading my blog posts and asking questions. Next time you have the chance, reach out to me, it would be terrific to finally meet you.
See you soon.


References

ReadingNotes #256


Cloud



Programming



Miscellaneous