Showing posts with label database. Show all posts
Showing posts with label database. Show all posts

Reading Notes #322

IMG_20180328_194043_2Cloud


Databases


Miscellaneous


Books



Unfu*k Yourself: Get Out of Your Head and Into Your Life (Gary John Bishop)

I really enjoyed this book. Strong ideas. No repetition. It goes straight to the point. The narration is awesome.

ASIN: B0731QJ482














Reading Notes #321

ester-eggs-2345859_640

Suggestion of the week



Cloud



Programming



Databases



Miscellaneous


Books



When: The Scientific Secrets of Perfect Timing (Daniel H. Pink)

A really amazing book packed of very interesting advice. Things that you kind of already knew, or at least had a feeling you maybe knew are clearly explained to you.

After reading (or listening) this book, you will know why, and you can decide to fight it or change the when... improve your performance and use your time and energy on something else.

ISBN: 0525589333






Reading Notes #319

kUz2asfCloud


Programming


Databases


Miscellaneous



Reading Notes #313

roy_sky_ansi2Suggestion of the week


Cloud


Programming


Databases


Miscellaneous


Reading Notes #309

419HCloud


Programming


Databases


Miscellaneous



Reading Notes #306

MVIMG_20171126_090346Suggestion of the week


Cloud


Programming


Databases



Reading Notes #304

IMG_20171108_160315

Cloud


Programming


Databases


Podcast


Miscellaneous



Reading Notes #301

300love

Programming


Data

Miscellaneous


  • My First Year as an MVP, part 1 (Jen Kuntz) - Interesting post. It feels soooooo familiar, and yet so far now. I look forward to meeting you in March fellow Canadian MVP.


Reading Notes #299

azure-1Cloud


Programming


Databases


Miscellaneous



Lessons learned when deploying multiple databases to Azure with VSTS

It's had been a while since I worked into Visual Studio Team Services (VSTS), and it was a real pleasure to get back in that area. For the solution I was working on, we need to keep the current database up and running while deploying a new version. For this purpose, we decided to append the release number to database name (ex: MyDatabase363). In our Build and Release processes, we needed to identify which databases are from the last release. In this post, I will show what I did using an inline PowerShell script to get that number and set it as an environment variable so it can be accessible by other tasks.

To get started let's add a Azure PowerShell task to our build definition. In this post, I use a build process but of course this is also valid for release process. To find the task quickly, use the search text box. I will add two of those, one to get the number, the second to validate that this value is now set as an environment variable and readable from other tasks.
AddPowerShellTask

Now it's time to set the first task. Fill-out all the properties and select Inline Script as the Script Type. It should look like this.

InlineScript

Let's examine the code.
Get last Release Number
$matchingResources = Find-AzureRmResource -ResourceNameContains "mydatabase" -ResourceType "Microsoft.Sql/servers/databases"

$lastRelease = 0

ForEach($resource in $matchingResources)
{
    if ($resource.ResourceName -match '(\d)+$') {
        if($lastRelease -lt $matches[0]){
            $lastRelease = $matches[0]
        }
    }
}
Write-Output "The last release number is:  $lastRelease"
Write-Output ("##vso[task.setvariable variable=lastReleaseNumber;]$lastRelease")
On the first line, I use the Azure PowerShell commandlet Find-AzureRmResource1 to get an array of all the databases currently online in my resource group that contains a specific string. In this case, it's the name of the database without the release number. Then I will loop through all returned resources and using a very simple Regex to extract the release number and keep the biggest one (the last release).

To close that script we have two outputs. The first one is to give feedback in the logs, because it's always good to have some information there. The second one look more complicated, but if you split it, it's easier to see what's happening. In fact, we are producing a VSTS (previously called Visual Studio Online this is why it's VSO) command to initialize a variable ##vso[task.setvariable variable=lastReleaseNumber;] And of course, assign to it our last release number $lastRelease

To validate that we really successfully found our last release number and assigned it to a variable, let's try to read it back but from another step. That will be easily done this code in the other step created:
Validate the last Release Number
$number = $env:lastReleaseNumber

Write-Output "Confirmation, the last Release Number is:  $number "
The only thing missing before we can run our test is to create that environment variable. To to it simply go in the Variables tab and add it there.

env-variable

It's all set, run the build and you should see something similar in your logs.

trace



References




Reading Notes #296

IMG_20170910_134750

Cloud


Databases


Miscellaneous




Reading Notes #295

Sketch002

Cloud


Programming


Databases




Reading Notes #292

cloudheight


Suggestion of the week


Cloud


Programming


Databases


Miscellaneous



From a Docker container to MySQL as a Service in Azure in 5 minutes

Hello MySQL! It's been a while eh? You were at version 3 something, I was just getting stated with my professional career. We had fun for years... Then you know things changed, and I did something else. I was really happy when Microsoft announced, at the MSBuild,  the availability of MySQL as a Servive in Azure.
 
SearchMySQL

Creating a MySQL database with the portal is extremely simple. As usual, you enter the server name, database name and the Admin's password. At the time I'm writing this post, it was not possible to use any CLI, but I'm sure it will be available shortly. For the ones who are not used at Database as Service in Azure, one thing you will need to do to get access to your database from your computer is white listed your IP. It's very easy to do from the Azure Portal, just select the Connection Security tab on the left menu and add your address. Oh! And don't forger to click the save button. ;)

Firewall

During my tests, I've tried different applications (WordPress, Azure WebApp, custom on-premise app.) that use MySQL as backend database, I didn't notice any problem, and performance were great. It was just... simpler; no server to configure, no VM to configure, no update. The only "issue" I got was trying to connect Power BI Desktop to a MySQL, but I think it more related to the drivers since the service was still in early preview. I notified Microsoft, and I'm sure it will be available shortly.

Since it's been a while since I did some reel work with MySQL I didn't have any client install on my laptop. In fact, I had no idea which one I should take.

I knew we can run some CLI inside a Docker container with an interactive interface. So I decided to give it a try. A quick docker search mysql shows me that an image existed. Here are the steps to get setup.

First, let's download the image, and create an instance named mySQLTools of MySQL 8.0:

docker run --name mySQLTools --env "MYSQL_ROOT_PASSWORD=Passw0rd" -d mysql:8

Then using the -it let's bring the bash prompt to our terminal.

docker exec -it mySQLTools bash -l 

Finally we connect to our client using the usual settings (note that you must have no space between -p and your password):

mysql -h _ServerName.database.windows.net_  -u _UserName@ServerName_ -p_MyPassword_ _DatabaseName_

result

Voila! That's all what it takes to get started. And by the way, it will also work great with a Azure SQL Database.


docker pull shellmaster/sql-cli 

docker run -it --rm --name=sqlTools shellmaster/sql-cli mssql -s ServerName.database.windows.net  -u UserName@ServerName  -p YourPassword -d DatabaseName -e





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.


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 #254

IMG_20161019_192029Cloud


Programming


Databases


Miscellaneous



Reading Notes #253

2016-10-17_09-17-05Suggestion of the week


Cloud


Programming


Databases