Minimizing Diameter in a tree while keeping a fixed sum of all edge weights

We are given a tree (an undirected connected graph without cycles) and an integer s which represents the sum of all edge weights in the tree/graph.

Consider a tree which has single path among leaf nodes. We can assign any weight; as long as they sum to s, diameter is also s. The diameter cannot be further minimized in this case.

Now, consider following case,

[put photos here]

C# Asynchronous Programming

Modern C# is a first class language to support asynchronous pattern. Its async/await, related keywords and Task Parallel Library enable us to comfortably utilize async features.

Basics

Task Parallel Library is a higher level abstraction of previous threading library. Instead of creating Thread to do some work we create Task instead. To create and run a new thread comfortably using a lambda expression, we can use Task.Run. Example,

var resultStr = Task.Run(() => MyFoo()).Result;

Task.Delay is an async sleep method that we use every now and then to simulate some async work.

Demonstrating Examples

All these example codes are available at github/atiq-cs/cs-async-demos.

First example demonstrates how to run create and run a thread synchronously.. The program does not even wait for the thread to complete. Hence, all output from the new thread might not be displayed.

// example 1
static void Main(string[] args) {
  ThreadingTest demo = new ThreadingTest();
  Console.WriteLine("Before running my foo()");
  demo.Run();
  Console.WriteLine("After running my foo()");
}

Second example, does not create any new thread.

// example 2
static void Main(string[] args) {
  ThreadingTest demo = new ThreadingTest();
  Console.WriteLine("Before running my foo()");
  demo.Run();
  Console.WriteLine("After running my foo()");
  Task.Delay(2000);
}

However, it marks its method as async. Additionally, it includes a potential beginner’s mistake: marking method as async void.
Task.Delay in main method has has no effect. It would return almost instantly since, await keyword is not used with the async method. Task.Delay does not create a new thread.
It is upto the reader to guess what the output is!

3rd example, mixes sync and async methods. New thread method is sync and it using Task.Delay does not make any sense.

static void Main(string[] args) {
  ThreadingTest demo = new ThreadingTest();
  Console.WriteLine("Before running my foo()");
  demo.Run();
  Console.WriteLine("After running my foo()");
}

By calling an async method from a sync method we are mixing up. Recommendation is to,

  • await an async method
  • since using await requires a method to be async as well, declare it as async

Best practices,

  • not to mix async methods with sync methods
  • not retrieving results using Task.Result, instead use await
  • do not use async void instead of async Task for methods that return nothing

Example 3 is better. However, it exemplifies Task.Delay without await.

Example 4 fixes all those flaws and additionally uses an async main method.
We use latest C# language which allows us to make main method to be async. We add following line to include C# lang version support of 7 or later,

<LangVersion>7.3</LangVersion>

Or,

<LangVersion>Latest</LangVersion>

inside the .csproj file.

// example 4
class p4AsyncMain {
  static async Task Main(string[] args) {
    ThreadingTest demo = new ThreadingTest();
    await demo.Run();
    Console.WriteLine("Main terminates");
  }
}

Program 5 shows how the async method is blocking main thread. Since async method is running on the caller thread it is blocked and it cannot do anything till the method returns. If we want to do work concurrently in both the main method and the additional async method we have to call the addition method (represent work) creating a new thread i.e., using Task.Run.

Example 6, creates a new thread for the represented work (a timer). While new thread is performing timer work main thread performs calculation of fibonacci numbers.

  class p6TimerAsyncNonblocking {
    static async Task Main(string[] args) {
      Timer tDemo = new Timer();
      Task timerToFinish = Task.Run(() => tDemo.Run());
      // at this point, runs fibo and timer concurrently
      MathCompute mathWork = new MathCompute();
      mathWork.fibo();
      // now let's wait till timer finishes
      await timerToFinish;
      // assuming we might need some result from timerToFinish from here, otherwise we can do more
      // work and then 'await'
      Console.WriteLine("main terminates");
    }
  }

Example codes used above are available at github/atiq-cs/cs-async-demos.

When to use ConfigureAwait

Quoting Juan @ Bynder – C#: Why you should use ConfigureAwait(false) in your library code,

This changes the continuation behavior of GetJsonAsync so that it does not resume on the context. Instead, GetJsonAsync will resume on a thread pool thread. This enables GetJsonAsync to complete the Task it returned without having to re-enter the context.

As per Stephen Cleary – Don’t Block on Async Code best practices can be,

  • To use ConfigureAwait(false) in library codes

We can’t use ConfigureAwait if we need current thread’s context for example UI Thread for GUI applications.. Here is a nice example of a similar scenario Async/Await – Best Practices in Asynchronous Programming.

However, when we are calling async methods in .net core web applications any thread from the threadpool would suffice, we don’t need resume context of current thread. Hence, ConfigureAwait(false) is perfect application in such cases.

More related resources

.net basic concepts

As of now, we have 3 versions of .net implementations,

  • .net core
  • .net standard
  • .net framework

.net core is new open-source, cross-platform implementation of .net API where .net framework is the old one; it is the largest implementation which has UI, WPF. Xamarin also implements .Net. All of these implementations have Base Class Library. These Base Class Libraries require some sort of contract for better compatibility and inter-operability. That’s where .net standard come into play.

.net standard is the standard that all .net implementations should follow.

Higher the .net standard version, bigger the API is. For example, if we are targeting .net standard 2.0 we have access to System.Data namespace. If lower the target version it becomes 1.0. Consider a solution that have a number of projects, if a project is targeting .net standard 2.0 and another project is using that project. That project cannot target an equivalent .net framework that is less in target .net standard version. youtube video – Understanding .NET Standard, .NET Core and .NET Framework. Earlier .net standard supported some old devices which new versions don’t support them.

Quoting stackoverflow – What is the difference between .NET Core and .NET Standard Class Library project types?

Ignoring libraries for a moment, the reason that .NET Standard exists is for portability; it defines a set of APIs that .NET platforms agree to implement. Any platform that implements a .NET Standard is compatible with libraries that target that .NET Standard. One of those compatible platforms is .NET Core.

References

Windows 10 Update Enable Playing Videos with x265 Encoding

On my new notebook, Dell XPS 15 9560, I first saw this problem. When I try to play an x265 video file using Windows 10 Movies and TV Player, it will only play the audio in background and show an error dialog box instead of rendering the video,

codec missing 0xc00d5212

I dug a little bit and I found that this is a problem starting Windows 10 Fall Creators Update. Since I did a Fresh installation of Windows 10 I encountered this.

Which means this is not a problem with Hardware of notebooks such as Dell XPS 15 or 13, it’s rather an operating system – Windows 10.

Looks like solution is pretty simple. We need to install an extension from Microsoft: HEVC Video Extensions from Device Manufacturer. Afterwards, Windows can play all videos (mkv, mp4 etc with x265) again, no 3rd party player or codec is required.

Primary reference: winaero – Get HEVC Decoder for Windows 10 Fall Creators Update

Running Windows Server on Container Instance

For now, this article only covers Azure Cloud.

ACI is good for running single container up easily and running.

Running a Windows Server Container on Azure
https://ronaldwildenberg.com/azure/2018/01/25/running-windows-server-container-in-azure.html

az container
https://docs.microsoft.com/en-us/cli/azure/container?view=azure-cli-latest#az-container-deletexrr

Execute a command in a running Azure container instance

https://docs.microsoft.com/en-us/azure/container-instances/container-instances-exec

Azure CLI Basics

Introduction

A strong CLI is useful to manage cloud resources easily. It helps automation, scripting and logging. It is handy in managing basic docker (Azure Container Services) stuff as well.

If you are new to Azure CLI it helps a lot took at the MS Docs – Getting Started documentation page. Documentation root is at MS Docs – Azure CLI 2.0

Here are few ways to access Azure Resources,

  • Azure Portal
  • Azure Powershell
  • SDKs – fluent .net api, supports other languages,
  • service principal (can be used to created using CLI)
  • REST API {JSON}

Here is the work flow for azure-cli.

  • First, we login to azure using CLI.
  • Second, we create/delete/modify resources.
  • Third, We perform actions on resource.

Additionally, I usually set the path manually in a command prompt,

C:> set PATH=%PATH%;C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin

On a powershell, if you ever need to add this manually to path var,

$ $Env:Path += 'C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin;'

Azure CLI is a cross-platform tool built using python, Wix. az commands in this article should work across all operating systems.

To check what version is installed,

$ az --version
azure-cli (2.0.43)
... .... ....

Python location 'C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\python.exe'
Extensions directory 'C:\Users\Neo\.azure\cliextensions'
Python (Windows) 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)]
Legal docs and information: aka.ms/AzureCliLegal

To access interactive version of Azure CLI, we enter an interactive session,

az interactive

Finally, here’s a brief overview of Azure CLI.

Azure CLI Intro

We can use Azure Cloud Shell as well to access Azure-CLI. It however requires a storage account. More info at MS Docs – Overview of Azure Cloud Shell

1. Azure login

login command looks like following,

$ az login
Note, we have launched a browser for you to login. For old experience with device code, use "az login --use-device-code"
You have logged in. Now let us find all the subscriptions to which you have access...

[
  {
    "cloudName": "AzureCloud",
    "id": "c2eax898-6232-4834-8e65-5e2cbeac0919",
    "isDefault": true,
    "name": "My Pay As You Go",
    "state": "Enabled",
    "tenantId": "cde5d866-bf04-4fa4-8da1-b3282cdb843b",
    "user": {
      "name": "matrix@morphis-system.com",
      "type": "user"
    }
  }
]

It automatically opens up a new browser Windows where we login to the account. Once we are logged into the azure portal, authentication token is automatically picked up the command prompt CLI instance.
In future az commands same authentication is continued to be used.

As we can see above, in command output, after logging in, it lists available subscriptions with the with Azure Cloud account. Following command also lists subscriptions,

$ az account list

This lists all subscriptions under the account. Commands we apply work on current subscription context. To show currently set subscription context,

$ az account show

If you have more than one subscription you might want to set the active subscription globally which can be done in following way ref,

$ az account set -s "My Pay As You Go"

which is equivalent to,

$ az account set --subscription "My Pay As You Go"

More info can be found at MS Docs – Manage multiple Azure subscriptions

For login we can use service principals as well, here’s an example of logging in with service principal,

az login --service-principal -u $servicePrincipalAppId --password $spPassword --tenat $tenantId

2. Managing Resource

We can do following managing of Azure Resources,

  • Create
  • Query
  • Update
  • Delete

Here are few examples below,

list examples

To list VMs we do,

$ az vm list
[]

Currently, I do not have any VM. Hence, the empty array shows up in output.

To list resource groups we do,

$ az group list
[
  {
    "id": "/subscriptions/c2eax898-6232-4834-8e65-5e2cbeac0919/resourceGroups/asynctest",
    "location": "westus",
    "managedBy": null,
    "name": "asynctest",
    "properties": {
      "provisioningState": "Succeeded"
    },
    "tags": null
  },
  {
    "id": "/subscriptions/c2eax898-6232-4834-8e65-5e2cbeac0919/resourceGroups/blog",
    "location": "centralus",
    "managedBy": null,
    "name": "blog",
    "properties": {
      "provisioningState": "Succeeded"
    },
    "tags": null
  },
  {
    "id": "/subscriptions/c2eax898-6232-4834-8e65-5e2cbeac0919/resourceGroups/ML",
    "location": "westus2",
    "managedBy": null,
    "name": "ML",
    "properties": {
      "provisioningState": "Succeeded"
    },
    "tags": null
  },
  {
    "id": "/subscriptions/c2eax898-6232-4834-8e65-5e2cbeac0919/resourceGroups/Speech",
    "location": "westus",
    "managedBy": null,
    "name": "Speech",
    "properties": {
      "provisioningState": "Succeeded"
    },
    "tags": null
  }
]

To show available azure function apps,

az functionapp list

Following screenshot from Azure CLI course by Mark Heath shows some more examples,
Azure CLI Show Resource Example

Using Query Language JMES

To select only field: state, to check whether the app is Running or not,

az functionapp show -n func -g myfuncs --query state

We can query multiple fields such as state and ftpPublishingUrl using array like syntax,

--query "[state, ftpPublishingUrl]"

Query language used in Azure CLI is called JMESPath.

We can rename properties in output,

az funcapp list --query "[].{Name:name, Group:resourceGroup, State: state}"

It feels like similar to the C# Feature where we can dictionary like, name fields in output,

Create Examples

To create a new resource group we do,

$ az group create --name MyContainers --location westus
{
  "id": "/subscriptions/c2eax898-6232-4834-8e65-5e2cbeac0919/resourceGroups/MyContainers",
  "location": "westus",
  "managedBy": null,
  "name": "MyContainers",
  "properties": {
    "provisioningState": "Succeeded"
  },
  "tags": null
}

Navigating help

To view top level help,

az -h

To view help on sub-topic webapp,

az webapp -h

To view help sub-topic of webapp: create,

az webapp create -h

To view help sub-topic of webapp: config,

az webapp config -h

-h applies to all available sub-commands.

Managing Web App and Other Resources

Here’s a brief overview of things we can do,

Azure CLI Managing Web Apps and Resources

Listing webapps,

az webapp list

To create new resource group,

az group create -n ResourceGroupName -l westus

To view help on App service plan create command,

az appservice plan create -h

Here’s an example, how we create an webapp under specified app service plan,

az webapp create -n AppName -g ResourceGroupName --plan AppServicePlanName

To show newly created app and query its host name,

az webapp show -n AppName -g ResourceGroupName --query "defaultHostName"

We can perform webapp deployment from source control,

az webapp deployment source config -n AppName -g ResourceGroupName --repo-url GIT_REPO_URL --branch master --manual-integration

For automatic integration with github we need to pass a git token.

In summary,

Azure CLI Managing Web Apps and Resources

To trigger redeployment we do,

az webapp deployment source sync -n AppName -g ResourceGroupName

SQL Server Resources

To create new SQL Server,

az sql server create -n SqlServerName -g ResourceGroupName -l Location -u sqlServerUserName -p sqlServerPass

List what pricing tiers are availabe for SQL Database,

az sql db list-editions -l Location -o table

To show outboundIpAddresses,

az webapp show -n AppName -g ResourceGroupName --query "outboundIpAddresses" -o tsv

Brief overview of SQL Server command examples below,

SQL Server Command Examples

To create sql server firewall,

az sql server firewall-rule create -g ResourceGroupName -s SqlServerName -n AllowWebApp1 --start-ip-address 0.0.0.0 --end-ip-address 0.0.0.0

We can get the connection string using the CLI as well. Afterwards, we can set the connection string to the webapp,

az webapp config connection-string set -n AppName -g ResourceGroupName --settings \
"SnippetsContext=$connectionString" --connection-string-type SQL-Azure

Import/Export SQL Database
An export example,

 az sql db export -s $sqlServerName -n $databaseName -g $ResourceGroupName \
 -u $sqlServerUserName -p $sqlServerPass --storage-key-type StorageAccessKey \
 --storage-key $storageKey --storage-uri "StorageBlobURL"

To restore database from backup, we use a new database. As we know, we cannot restore into current database.We can only restore into blank database.
So we create new database, get the connection-string, and use this new connection-string on the webapp.

Export procedure overview,

SQL Server Export Examples

Deployment procedure overview,

Deployment using CLI

Output Formatting

By default, output is displayed in JSON format. Using -o table we can have tabular format output.

To display the output as a table we add --out table. Here’s an example,

$ az container list --out table

Azure Container Instance Related Commands

Listing containers,

$ az container list
[
  {
    "containers": [
      {
        "command": null,
        "environmentVariables": [],
        "image": "microsoft/iis:nanoserver",
        "instanceView": null,
        "livenessProbe": null,
        "name": "MyServerCoreCI",
        "ports": [
          {
            "port": 80,
            "protocol": "TCP"
          }
        ],
        "readinessProbe": null,
        "resources": {
          "limits": null,
          "requests": {
            "cpu": 1.0,
            "memoryInGb": 1.5
          }
        },
        "volumeMounts": null
      }
    ],
    "diagnostics": null,
    "id": "/subscriptions/c2eax898-6232-4834-8e65-5e2cbeac0919/resourceGroups/dockers/providers/Microsoft.ContainerInstance/containerGroups/MyServerCoreCI",
    "imageRegistryCredentials": null,
    "instanceView": null,
    "ipAddress": {
      "dnsNameLabel": null,
      "fqdn": null,
      "ip": "40.78.17.202",
      "ports": [
        {
          "port": 80,
          "protocol": "TCP"
        }
      ]
    },
    "location": "westus",
    "name": "MyServerCoreCI",
    "osType": "Windows",
    "provisioningState": "Succeeded",
    "resourceGroup": "dockers",
    "restartPolicy": "Always",
    "tags": {},
    "type": "Microsoft.ContainerInstance/containerGroups",
    "volumes": null
  }
]

Azure Resource Manager (ARM)

Azure Resource Manager, in brief ARM helps deployment procedure automated and sophisticated.
We can perform group deployment using ARM.

Then check what the newly created resourceGroup contains,

az resource list -g ResourceGroupName -o table

Create deployment overview,
SQL Server Command Examples

To get domain name property of first public ip,

az network public-ip list -g ResourceGroupName --query "[0].dnsSettings.fqdn" -o tsv

To generate template from existing from resource group we can utilize command similar to,

az group export

Sometimes, there are things in the resource group that cannot be represented in an ARM template.

Bug of current CLI turns this warning into an error.. Compared to github deployment json this is much more verbose and specific..

Another way to create ARM Template is using Visual Studio, ARM Tooling.

Recommended Courses

Misc.

Azure CLI Windows build script can be found at references section. Additionally, we can configure with Active directory,
Active Directory Examples

Reference

Windows 10 Installation – Forcing to a different edition of Windows

Here’s an example of the problem.

Say you purchased a Dell XPS Notebook which comes with pre-installed Windows 10 Core (Home Edition). Now, you might have,

  • an Enterprise Edition of Windows or License
  • a Pro Edition of Windows or License

There might be a number of reasons why you might go with a superior license which you have or you can afford,

  • Pro edition or enterprise edition has features that are not available with Home edition
  • Simple things like remote desktop connection would not work with a home edition, so may be it’s better keep the option open if you need those features in future.

The simplest way to upgrade would be to go to Windows Product Key from control panel and change the Key. Windows should install everything as required for the Pro version.

Now, you might be wondering, like the old days, we can reinstall Windows using Installation Media and during installation it would ask nicely which version (Pro or Home or Enterprise etc) we want to install. Unfortunately, that does not work for many of the new systems where Windows Setup automatically detects previously installed Windows’s version like a rude robot! It chooses that version of Windows such as Windows Home edition every time we do reinstall.

Here’s a way to force it to Pro Edition. This is easier with USB Installation Media tool. All we need to do, is put two configuration files specified the edition and the product key.

  • ei.cfg
  • pid.txt

Sample ei.cfg for Pro edition looks like,

[EditionID]
Professional
[Channel]
Retail

For home edition, second line should be changed as showed below,

[EditionID]
Home

As per MS Docs {Channel Type} must be either “OEM” or “Retail”.

Sample pid.txt looks like below,

[PID]
Value=YOURP-RODUC-TKEY-IF6V9-RUW32

Reference

How to Reset Windows 10 password

One way to reset password is to reset Windows. Here’s instruction from microsoft support.
Forgot your Windows 10 user password. Here’s a way to fix it if your BIOS is not password protected or if you know the BIOS Password.

Here are the steps to reset password,
First thing to do is to boot using Windows Installation Media (USB boot works),
Then we select “Repair your computer” that gives us access to Troubleshooting. Then we choose command prompt.

After getting access to the command prompt I found that C drive is the Win System Drive. In some cases this can be different. Setup might mark D as system drive. Once you know the system drive it’s pretty easy and we can go to next step.

We rename Utilman binary,

move C:\Windows\System32\Utilman.exe C:\Windows\System32\Utilman.exe.bak

Then we rename cmd.exe,

move C:\Windows\System32\cmd.exe C:\Windows\System32\Utilman.exe

I can verify it,

X:\Sources> dir C:\Windows\System32\Utilman.*
 Volume in drive C is OS
 Volume Serial Number is 3A78-E6F7

 Directory of C:\Windows\System32

03/18/2017  12:57 PM           271,872 Utilman.exe
03/18/2017  12:57 PM            90,112 Utilman.exe.bak
               2 File(s)        361,984 bytes
               0 Dir(s)  462,441,738,240 bytes free

Then we exit command prompt and select “Turn off pc” from the menu. Then we unplug the installation media from the system.

When Windows boots up normally without the installation media, on the logging screen, we click “Ease of access” which brings us “Command Prompt”. That’s golden gate bridge to resetting password.

We add a user using following command syntax,

net user user_name password

Please user_name and password in command above with intended credentials.

Once you are done click Shutdown computer. Now plug in USB boot or DVD installation media again and boot to Windows 10 Setup. Get access to command prompt as mentioned before. Afterwards, restore utilman and cmd.exe as it was before,

move C:\Windows\System32\Utilman.exe C:\Windows\System32\cmd.exe
move C:\Windows\System32\Utilman.exe.bak C:\Windows\System32\Utilman.exe

If you don’t want to type in the commands above, you can copy commands in a script and put inside the USB disk to run them or open using notepad command and copy-paste.

Reference

Using Powershell Module for Windows Update

Here’s the Powershell module for Windows Update. As per instruction on package page we install,

PS > Install-Module -Name PSWindowsUpdate

Install update example is below. Please note that I had to confirm which actions I wanted to confirm.

PS > Install-WindowsUpdate 
Are you sure you want to perform this action? 
Performing the operation "2018-07 Cumulative Update for Windows 10 Version 1803 for x64-based Systems (KB4340917)[86GB]" on target "FFTSys". 
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y 

Are you sure you want to perform this action? 
Performing the operation "Microsoft Silverlight (KB4013867)[13MB]" on target "FFTSys". 
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): N 

X ComputerName Result     KB          Size Title 
- ------------ ------     --          ---- ----- 
1 FFTSys     Accepted   KB4340917   86GB 2018-07 Cumulative Update for Windows 10 Version 1803 for x64-based Systems (KB4340917) 
1 FFTSys     Rejected   KB4013867   13MB Microsoft Silverlight (KB4013867) 
2 FFTSys     Downloaded KB4340917   86GB 2018-07 Cumulative Update for Windows 10 Version 1803 for x64-based Systems (KB4340917) 
3 FFTSys     Installed  KB4340917   86GB 2018-07 Cumulative Update for Windows 10 Version 1803 for x64-based Systems (KB4340917) 
Reboot is required.Do it now? [Y / N] (default is 'N') 
Y

If you want to script it then you have to set to use a default action instead of interactively confirming.

Hide Windows Update example,

PS > Hide-WindowsUpdate -Title "Microsoft Silverlight*" -Hide
Are you sure you want to perform this action? 
Performing the operation "Hide Microsoft Silverlight (KB4023307)[13MB]" on target "FFTSys". 
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A 

ComputerName Status     KB          Size Title 
------------ ------     --          ---- ----- 
FFTSys     ---H--     KB4023307   13MB Microsoft Silverlight (KB4023307) 

Export import mysql database with Unicode Encoding using Windows Client

This article largely applies to MySQL clients on Windows Systems. This is related to Enterprise Azure database for MySQL as well.

Logical steps for database migrations are,

  1. Setup new database server
  2. Export all data using mysqldump from old server to a sql, verify if export was done
  3. Import data using that sql script.

Step 1 – Verifying server logins

Right after creating Database server it does not have the database, hence, we connect without specifying a DB,

mysql -p -h company-name-mysql-server.mysql.database.azure.com -u admin@company-name-mysql-server

If we specify a database on above command,

ERROR 2013 (HY000): Lost connection to MySQL server at 'reading final connect information', system error: 2

If we can get a MySQL shell, this verifies that we met authentication requirements for the
connection. Please note that this command works with SSL enforced database as well. However, for
Azure Databases, client IP addresses should be added to connection security setting before
attempting connection.

After logging in we create the DB,

mysql> Create Database wpdb;
Query OK, 1 row affected (0.37 sec)

We set UTF-8 encoding on the new database,

mysql> ALTER DATABASE wpdb CHARACTER SET utf8;
Query OK, 1 row affected (0.03 sec)
mysql> ALTER DATABASE wpdb CHARACTER SET utf8 COLLATE utf8_unicode_ci;
mysql> SET NAMES utf8;

Step 2 MySqlDump

While trying to export a database containing contents UTF-8 encoding with Powershell I have encountered issues.

Looking back, in Linux, this has been fairly simple.

mysqldump wpdb -p > wpdb-2018-07-21.sql

This exports the database named wpdb into a sql file named wpdb-2018-07-21.sql.

In Windows Powershell, this is how my first attempt looks like,

$Env:Path += 'D:\PFiles_x64\PT\mysql\bin;'
mysqldump -p -h company-name-mysql-server.mysql.database.azure.com -u
admin@company-name-mysql-server wpdb > wpdb-2018-07-21.sql
mysqldump: Couldn't execute 'SELECT COLUMN_NAME, JSON_EXTRACT(HISTOGRAM,
'$."number-of-buckets-specified"') FROM information_schema.COLUMN_STATISTICS
WHERE SCHEMA_NAME = 'wpdb' AND TABLE_NAME = 'wp_allowphp_functions';': Unknown
table 'column_statistics' in information_schema (1109)

Then, I added --column-statistics=0 with above command following ref. It completed successfully. However, utf-8 encoding was not preserved properly. This can be problem with output redirection operator’s not setting proper encoding or the output that is coming from the command.

Though I would follow this SO – MySqlDump from Powershell and Windows encoding. Similarly, SO – Changing PowerShell’s default output encoding to UTF-8
has instruction. This did not work for me though.

$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'

I also check Console encoding,

$ [Console]::OutputEncoding
IsSingleByte      : True
BodyName          : IBM437
EncodingName      : OEM United States
HeaderName        : IBM437
WebName           : IBM437
WindowsCodePage   : 1252
IsBrowserDisplay  : False
IsBrowserSave     : False
IsMailNewsDisplay : False
IsMailNewsSave    : False
EncoderFallback   : System.Text.InternalEncoderBestFitFallback
DecoderFallback   : System.Text.InternalDecoderBestFitFallback
IsReadOnly        : True
CodePage          : 437

Keith Hill’s Blog – Handling Native EXE Output Encoding in UTF8 with No BOM shows some interesting stuff on console encoding.

Next I tried Out-File instead of redirection operator. I also added --verbose so I can track progress of the command. It is useful for large databases.

mysqldump -p -h company-name-mysql-server.mysql.database.azure.com -u
admin@company-name-mysql-server wpdb --verbose | Out-File
wpdb-2018-07-21.sql -Encoding UTF8

This did not properly preserver my utf-8 encoding. So I tried again adding --default-character-set=utf8.

This is pretty frustrating. Right?

To solve this import/export on Powershell/Windows Encoding problem I looked up a number of references,

Finally, at mysql.com documentation I found option --result-file also named -r which saved my ass. I tried following command to dump the database using -r,

mysqldump -p -h company-name-mysql-server.mysql.database.azure.com -u
admin@company-name-mysql-server wpdb --verbose --default-character-set=utf8 -r
wpdb-2018-07-21.sql

This successfully completed and preserved utf-8 encoding. However, look out for losing connection due to network problems which can give something like this on the console,

ERROR 2013 (HY000): Lost connection to MySQL server at 'reading final connect information', system error: 2

The Import using the exported script

Old Unix way of import is,

use wpdb;
source wpdb-2018-07-21.sql;

Or,

mysql -p wpdb > wpdb-2018-07-21.sql;

My first attempt to use input redirection operator gave me this,

$ mysql -p -h company-name-mysql-server.mysql.database.azure.com -u
    admin@company-name-mysql-server wpdb < wpdb-2018-07-21.sql
At line:1 char:83
+ ... server.mysql.database.azure.com -u admin@com.. wpdb < wpd ...
+                                                                 ~
The '<' operator is reserved for future use.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : RedirectionNotSupported

SO – Why is “<” input redirect not implemented in PowerShell? explains why this happens.

Then, I found the backward way of doing it using Powershell. Please note, in Step 1, how I set encoding for the Powershell.

$ Get-Content wpdb-2018-07-21.sql | mysql -p -h
company-name-mysql-server.mysql.database.azure.com -u
admin@company-name-mysql-server wpdb --default-character-set=utf8

Please note that adding --verbose to any of the above import commands can produce error and terminate earlier before completion.

Then, I thought I would try the old friend command prompt a try instead of the Powershell.

< set PATH=%PATH%D:\PFiles_x64\PT\mysql\bin
< mysql --version
mysql  Ver 8.0.11 for Win64 on x86_64 (MySQL Community Server - GPL)
< mysql -p -h company-name-mysql-server.mysql.database.azure.com -u
 admin@company-name-mysql-server wpdb --default-character-set=utf8 < 
 wpdb-2018-07-21.sql

This worked like a charm; import successfully recognized the utf-8 encoding and preserved it.

Enabling SSL with Azure Web App for mysql database connection

Enabling SSL with Azure App for mysql database is pretty straightforward.

  1. We need to enforce SSL on the database server.
  2. We need to download the certificate that validates the SSL for the database server. Web app needs it. And upload into the bin folder of the website.
  3. Add variable in Web app application settings.
  4. Add two lines in wp-config.php

Elaboration of above steps is below.

Step 1

This is enabled using Azure portal or az (Azure CLI) command. Screenshot of the portal is below,

Azure Portal Enabling SSL

A reference MS docs which also illustrates this will be added later.

Step 2

We acquire/download cert from here following reference: MS Docs – Configure SSL connectivity in your application to securely connect to Azure Database for MySQL. Currently, the URL of the certificate: digicert pem URL. The reference provides instruction on also how to connect to database server using different programming languages and from MySql Clients.

Step 3 Adding Application settings Variable

Then, we add variables on Application settings of the Azure App,

MYSQL_SSL_CA    |   wwwroot\bin\BaltimoreCyberTrustRoot.crt.pem

Following reference MS Docs – Connect Azure App Service to Azure database for MySQL and PostgreSQL via SSL provides instruction on this.

Step 4 updating wp-config.php

We add following two lines,

define( 'MYSQL_SSL_CA', getenv('MYSQL_SSL_CA'));
define( 'MYSQL_CLIENT_FLAGS', MYSQLI_CLIENT_SSL | MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT );

However, if your php version is earlier than 7 second line should read instead,

define( 'MYSQL_CLIENT_FLAGS', MYSQLI_CLIENT_SSL);

In my case, php version is 7.2.5 Hence I definitely go with former instead of later. Otherwise, I get following error,

Warning: mysqli_real_connect() expects parameter 8 to be integer, string given in wwwroot\wp-includes\wp-db.php on line 1531r
Warning: mysqli_get_server_info(): invalid object or resource mysqli in wwwroot\wp-includes\wp-db.php on line 3424r
Warning: mysqli_get_server_info(): invalid object or resource mysqli in wwwroot\wp-includes\wp-db.php on line 3424r
Warning: mysqli_get_server_info(): invalid object or resource mysqli in wwwroot\wp-includes\wp-db.php on line 3424r
Warning: mysqli_query(): invalid object or resource mysqli in wwwroot\wp-includes\wp-db.php on line 792r
Warning: mysqli_select_db(): invalid object or resource mysqli in wwwroot\wp-includes\wp-db.php on line 1024r

However, please be aware that defining MYSQL_CLIENT_FLAGS multiple times can produce error and not give you expected result.

Notes

One of the references: SO – Configure WordPress on Azure Cloud Service to connect to Azure MySQL over SSL below mentions adding DB_SSL,

define( 'DB_SSL', true);

And the reference also suggests adding following in wp-db.php,

mysqli_ssl_set($this->dbh, NULL, NULL, ABSPATH . 'BaltimoreCyberTrustRoot.crt.pem', NULL, NULL);

which are not really necessary. Adding these to wp-db.php led me to a different error,

Warning: mysqli_real_connect() expects parameter 8 to be integer, string given in wwwroot\wp-includes\wp-db.php on line 1533r
Warning: mysqli_get_server_info(): invalid object or resource mysqli in wwwroot\wp-includes\wp-db.php on line 3426r
Warning: mysqli_get_server_info(): invalid object or resource mysqli in wwwroot\wp-includes\wp-db.php on line 3426r
Warning: mysqli_get_server_info(): invalid object or resource mysqli in wwwroot\wp-includes\wp-db.php on line 3426r
Warning: mysqli_query(): invalid object or resource mysqli in wwwroot\wp-includes\wp-db.php on line 792r
Warning: mysqli_select_db(): invalid object or resource mysqli in wwwroot\wp-includes\wp-db.php on line 1024
Can’t select database
We were able to connect to the database server (which means your username and password is okay) but not able to select the wpdb database.
Are you sure it exists?
Does the user sqluser@sqlserver have permission to use the wpdb database?
On some systems the name of your database is prefixed with your username, so it would be like username_wpdb. Could that be the problem?

while actual fix I needed was to correct definition for MYSQL_CLIENT_FLAGS on php 7.

MS Docs – SSL connectivity in Azure Database for MySQL provides necessary SSL related references.

Self-hosted WordPress Trouble-shooting

When wordpress theme start acting up the entire blog homepage might disappear (blank homepage). However, still there is a chance to access the dashboard using the wp-admin link and change to a stock theme from the outdated/messy theme. If that does not work, what do you do?

Changing Site URL

Forcing change of site URL by adding this to wp-config.php,

define('WP_HOME','http://old-domain.com');
define('WP_SITEURL','http://new-domain.com');

Afterwards, making the change permanent by changing in database,

mysql> UPDATE wp_options SET option_value = replace(option_value, 'http://old-domain.com', 'https://new-domain.com') WHERE option_name = 'home' OR option_name = 'siteurl';
Query OK, 2 rows affected (0.21 sec)
Rows matched: 2  Changed: 2  Warnings: 0

mysql> UPDATE wp_posts SET guid = replace(guid, 'http://old-domain.com','https://new-domain.com');
Query OK, 2965 rows affected (0.48 sec)
Rows matched: 11923  Changed: 2965  Warnings: 0

mysql> UPDATE wp_posts SET post_content = replace(post_content, 'http://old-domain.com', 'https://new-domain.com');
Query OK, 66 rows affected (1.29 sec)
Rows matched: 11923  Changed: 66  Warnings: 0

mysql> UPDATE wp_postmeta SET meta_value = replace(meta_value,'http://old-domain.com','https://new-domain.com');
Query OK, 16 rows affected (1.94 sec)
Rows matched: 1533021  Changed: 16  Warnings: 0

Masterpiece reference on changing site URL is the one to visit. This one has a number of important sections including
plugin installation issues. coolestguidesontheplanet – Change and Update WordPress URLS in Database When Site is Moved to new Host and wordpress.stackexchange – Change homepage url also provides instruction on this.

Theme Settings

Using the wp database this can be changed.

This confirms my messed up theme,

mysql> select * from wp_options where option_name = 'template';
+-----------+-------------+--------------+----------+
| option_id | option_name | option_value | autoload |
+-----------+-------------+--------------+----------+
|        48 | template    | MessyTheme   | yes      |
+-----------+-------------+--------------+----------+
1 row in set (0.02 sec)

mysql> Select * from wp_options where option_name = 'stylesheet';
+-----------+-------------+---------------+----------+
| option_id | option_name | option_value  | autoload |
+-----------+-------------+---------------+----------+
|        49 | stylesheet  | MessyTheme | yes      |
+-----------+-------------+---------------+----------+
1 row in set (0.02 sec)

Please note that template and stylesheet are the exact static strings we use; they don’t refer to anything else.

Here’s example from another user,

mysql> select * from wp_options where option_name = 'template';
+-----------+-------------+--------------+----------+
| option_id | option_name | option_value | autoload |
+-----------+-------------+--------------+----------+
|        48 | template    | Avada        | yes      |
+-----------+-------------+--------------+----------+
1 row in set (0.02 sec)

mysql> select * from wp_options where option_name = 'stylesheet';
+-----------+-------------+--------------+----------+
| option_id | option_name | option_value | autoload |
+-----------+-------------+--------------+----------+
|        49 | stylesheet  | Avada        | yes      |
+-----------+-------------+--------------+----------+
1 row in set (0.02 sec)

This is how I force update it using database,

mysql> update wp_options set option_value = 'twentysixteen' where option_name = 'template';
Query OK, 1 row affected (0.22 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> update wp_options set option_value = 'twentysixteen' where option_name = 'stylesheet';
Query OK, 1 row affected (0.22 sec)
Rows matched: 1  Changed: 1  Warnings: 0

Before running above two commands I have ensured that the specified theme exists in wp-content/themes. Otherwise, theme situation does not get any better.

SSL Binding on Azure PaaS or Windows Server

Each web app (PaaS) in Azure Portal has SSL Settings option. Using that we can bind SSL for the domain.

First step is to, generate private key (.key file), Certificate Signing Request and then get SSL Certificate from an SSL provider.
Most ssl cert providers provide *.crt files. Now here’s the dilemma. The portal or server needs pfx and cer files. But provider has given *.crt files and we have an initial key file.

Here I show how to generate .pfx from .key file.

First, we fire up Powershell. And add openssl on Path if not added already. My openssl binary location is D:\PFiles_x64\choco\git\mingw64\bin,

$Env:Path += 'D:\PFiles_x64\choco\git\mingw64\bin'

Afterwards, following command generate the pfx file,

$ openssl pkcs12 -export -out my.domain.name.pfx -inkey my.domain.name.key -in my.domain.name.crt
Enter Export Password:
Verifying - Enter Export Password:

It asks for the password and confirming the password. Please remember/write down the password as you will need this when you upload the pfx file to Azure Portal SSL Settings. Once, I got pfx file, I need cer files. We follow an example comodo article – How do I convert .crt file into the Microsoft .cer format to convert our crt files cer.

Now, we got everything we need to bind ssl. Using the portal we click upload certificate, chose private and upload the pfx file. Next, we click upload certificate again, choose public this time and upload cer file. If I have multiple cer files I repeat the procedure.

Azure Portal SSL Settings
Please click to zoom image.

Finally, clicking SSL Bindings we choose the domain. For me SSL cert is SNI Based. So, I choose that.

In case, you have a number of key files and crt files and not sure which one is correct key file. Here’s a way to verify that. Assuming, you have openssl on Path command to verify if md5 hashes of crt and key matches will be,

$ openssl rsa -noout -modulus -in my.domain.key | openssl md5
(stdin)= xxxx456b5f5xxxxxxxxx8ccb9xxxx
$ openssl x509 -noout -modulus -in my.domain.crt | openssl md5
(stdin)= xxxx456b5f5xxxxxxxxx8ccb9xxxx

Commands are preceded with the prompt $ symbol. The symbol is not part of command.

Azure Relational Databases

Regarding connecting to the DB using a mysql client or management first thing to do in Azure db is to add the client IP in security settings

My SQL

As of today, there are three pricing tiers,

  • Basic
  • General Purpose
  • Memory Optimized

More to note,

  • Basic allows upto 2 VCores. Other tiers allow upto 32 VCores.
  • There are two compute generations available with Basic and General Purpose. Memory Optimized only has Gen 5 compute.

Regarding cost,

  • $33.43 Single Core West US is the minimum.
  • Cost can vary per region.
  • Cost is multiplied by number of cores. Therefore, a 32 VCore West US Database costs monthly $76.19*32 = $2438.63 per month.

Pricing tier for MySQL Azure DB

if you are running a site with small database (less than 1GB) you can see this pricing does not make sense. Cleardb on Azure in that case can be a good choice, will bring your cost down to about $15. However, if you are able to manage Virtual Machines. A linux VM can give you database of your choice as well.

If you are migrating your database to Azure Database for MYSQL it is good to be aware that Azure only implement InnoDB. They don’t have MyISAM yet.

Converting MyISAM Tables to InnoDB for a wordpress DB

Motivation

Error we get is kinda similar to,

Can’t restore database with error “Got error 1 from storage engine”

Article Azure Database for MySQL – Can’t restore database details on that.

  mysql> SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA =
  'fun_wp_db' AND engine = 'MyISAM';
  +-----------------------------+
  | TABLE_NAME                  |
  +-----------------------------+
  | wp_allowphp_functions       |
  | wp_bwps_lockouts            |
  | wp_bwps_log                 |
  | wp_collaboration            |
  | wp_collabrules              |
  | wp_collabwriters            |
  | wp_comment_notifier         |
  | wp_cr_post                  |
  | wp_cr_user                  |
  | wp_fbthumbnails             |
  | wp_filemeta                 |
  | wp_kf_most_read             |
  | wp_links                    |
  | wp_login_redirects          |
  | wp_mbdb_books               |
  | wp_monalisa                 |
  | wp_most_read_hits           |
  | wp_nc_coming_soon_free      |
  | wp_newsletter               |
  | wp_nxs_log                  |
  | wp_post_views               |
  | wp_private_messages         |
  | wp_recently_popular         |
  | wp_revslider_navigations    |
  | wp_shaf_adminmail           |
  | wp_subscribe2               |
  | wp_subscribe_reloaded       |
  | wp_term_relationships       |
  | wp_term_taxonomy            |
  | wp_terms                    |
  | wp_um_message               |
  | wp_um_notification          |
  | wp_useronline               |
  | wp_wc_avatars_cache         |
  | wp_wc_comments_subscription |
  | wp_wc_phrases               |
  | wp_wc_users_voted           |
  +-----------------------------+
  37 rows in set (0.01 sec)

Syntax for converting these tables,

ALTER TABLE table_name ENGINE=InnoDB;

I used following notepad++ regular expression to convert this to mysql statements to alter these tables,

Pattern: ^\| (wp_.+)\s+\|$
Replacement: ALTER TABLE \1 ENGINE=InnoDB;

Result query script looks like,

ALTER TABLE wp_allowphp_functions       ENGINE=InnoDB;
ALTER TABLE wp_bwps_lockouts            ENGINE=InnoDB;
ALTER TABLE wp_bwps_log                 ENGINE=InnoDB;
ALTER TABLE wp_collaboration            ENGINE=InnoDB;
ALTER TABLE wp_collabrules              ENGINE=InnoDB;
ALTER TABLE wp_collabwriters            ENGINE=InnoDB;
ALTER TABLE wp_comment_notifier         ENGINE=InnoDB;
ALTER TABLE wp_cr_post                  ENGINE=InnoDB;
ALTER TABLE wp_cr_user                  ENGINE=InnoDB;
ALTER TABLE wp_fbthumbnails             ENGINE=InnoDB;
ALTER TABLE wp_filemeta                 ENGINE=InnoDB;
ALTER TABLE wp_kf_most_read             ENGINE=InnoDB;
ALTER TABLE wp_links                    ENGINE=InnoDB;
ALTER TABLE wp_login_redirects          ENGINE=InnoDB;
ALTER TABLE wp_mbdb_books               ENGINE=InnoDB;
ALTER TABLE wp_monalisa                 ENGINE=InnoDB;
ALTER TABLE wp_most_read_hits           ENGINE=InnoDB;
ALTER TABLE wp_nc_coming_soon_free      ENGINE=InnoDB;
ALTER TABLE wp_newsletter               ENGINE=InnoDB;
ALTER TABLE wp_nxs_log                  ENGINE=InnoDB;
ALTER TABLE wp_post_views               ENGINE=InnoDB;
ALTER TABLE wp_private_messages         ENGINE=InnoDB;
ALTER TABLE wp_recently_popular         ENGINE=InnoDB;
ALTER TABLE wp_revslider_navigations    ENGINE=InnoDB;
ALTER TABLE wp_shaf_adminmail           ENGINE=InnoDB;
ALTER TABLE wp_subscribe2               ENGINE=InnoDB;
ALTER TABLE wp_subscribe_reloaded       ENGINE=InnoDB;
ALTER TABLE wp_term_relationships       ENGINE=InnoDB;
ALTER TABLE wp_term_taxonomy            ENGINE=InnoDB;
ALTER TABLE wp_terms                    ENGINE=InnoDB;
ALTER TABLE wp_um_message               ENGINE=InnoDB;
ALTER TABLE wp_um_notification          ENGINE=InnoDB;
ALTER TABLE wp_useronline               ENGINE=InnoDB;
ALTER TABLE wp_wc_avatars_cache         ENGINE=InnoDB;
ALTER TABLE wp_wc_comments_subscription ENGINE=InnoDB;
ALTER TABLE wp_wc_phrases               ENGINE=InnoDB;
ALTER TABLE wp_wc_users_voted           ENGINE=InnoDB;
$ mysql -p -h testaz-mysql-server.mysql.database.azure.com -u mysqluser@testaz-mysql-server fundb > db-export.sql

MS SQL

MS SQL has better pricing compare to MySQL. Tool to connect can be “SQL Management Studio”.

Typescript Introduction

[draft article]
Here are few things as per my understanding to learn about it,
typescript is a cleaner version of javascript.
.ts is the extension of the file instead of .js

Basic data types are,
– Boolean
– Number
– String
– Array
– Tuple
– Enum
– Any

If you are used to var for type assertions, let is preferred way to do instead of using var keyword. Please have a look at the mentioned reference above for more.

To define a property name in class named AppComponent we do, for example,

name: string

Later, across the class we refer it to as this.name. So, that was definition of the variable. Here’ an example of declaration,

markerTypes = [
{ text: “Parking”, value: 0 },
{ text: “Library”, value: 1 },
{ text: “Information”, value: 2 },
{ text: “Beach Flag”, value: 3 },
{ text: “Car”, value: 4 },
];

Resources

  1. What’s New in TypeScript : Microsoft Build 2018 Video
  2. Languages (TypeScript C#, C++, Node, Python) : Microsoft Build 2018 Video

Tips and Tricks

  • I know two ways to convert a string to number,

    s: string
    // way 1
    parseInt(s);
    // way 2
    Number(s);

  • How to concatenate strings?
    ‘+’ operator works,

    fullName = firstName + ‘ ‘ + lastName

Getting Started with Angular

This article is a developer reference instead of targeting general audience. This lists useful references I encountered while starting with angular. Please note that we are using Visual Studio Pro or Enterprise edition. For VS Code examples would be slightly different.

Primary guide provides documentation on initial overview, source tree structure. It’s good to be aware that angular is based on typescript, typescript documentation can be a good source of learning. reddit thread is a point of interest regarding the design decisions.

If you are into latest angular which is v6 right now. This angular6-example-app comes handy.

If we’re using angular cli to create projects, configure, build ng build is to be look up.

To initialize class properties ngOnInit is good place to start, [ref]

If we are using Forms in our html pages and we forget to include dependency FormsModule we hit error: can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’

Using Visual Studio with latest angular-cli

.net core web projects support typescript just like javascript if you are wondering. However, it is good idea to ensure you have .net core installed. If you don’t care about the latest version of angular and can afford to use bit of an older version then VS is perfectly fine. In that case, you can skip the instruction in this section.
To update the old template of VS we create a new project using angular-cli (ng). Then, we replace the contents inside ClientApp dir with the angular project files.

To understand how .net core middleware interacts with the framework please have a look at ASP.NET Core Middle-ware documentation

Updating Web Tools for Visual Studio

For developers, who don’t like the outdated toolchain with Visual Studio for nodejs and node_modules would probably prefer using customized node installation which is up to date.

node installation

Assuming you have chocolatey installed in the system, this would be the command to install it for 64 bit architecture. I am customizing to install it to D:\PFiles_x64\Node directory.

choco install nodejs.install -ia "'INSTALLDIR=D:\PFiles_x64\Node'"

Once, you installed node it should, by default, be added to system’s path environment. Then, we fix web tools path in visual studio. Here’s general instruction for node in Visual Studio for the updating software locations.

Afterwards, we need to restart the system for changes to take effect. Otherwise, there is a possibility that Visual Studio will throw exception while creating Web Host using .net core MiddleWare simply because it cannot execute npm command which happened a few times in my experience. The solution is to install node which should add the path in system. After restarting the system this is discover-able by Visual Studio.

Here’s the script runner source of .net middleware where npm is invoked,

As from the source, we realize that npm is invoked by following,

cmd /c npm --argument_as_provided

in Windows. This means that even if we properly included path for Third Party Web Projects and Solutions still npm would fail if it’s not found system’s path variable. Here’s an example, where this would fail even though Path inclusion correct in Visual Studio 3rd party project settings.

$ echo $Env:Path
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0;C:\Program Files\dotnet;C:\Program Files\Microsoft SQL Server\130\Tools\Binn;C:\WINDOWS\System32\OpenSSH;

In such case, what’s the fix? Add nodejs executable path, for example, D:\PFiles_x64\Node in system’s path variable, reboot and vola, it works!

References

  1. angular guide
  2. TypeScript 2.7 documentation

Using Google Maps API with Angular

Initially, while looking up online on how to use google maps api with angular I found a few references including [1]. Javascript reference for google map does not completely match; yet, it can be of help some time to match calls.

Balram Chavan shared his experience: Integrating Google Maps in Angular 5. His demo can be found at github. Additionally, there is an old example to demo gmap with angular 2 at ng2-ui/map.

First, I had to enable google maps with Google Cloud Platform which in the end gave me an API Key.

Current version of angular, at the time of this demo, is 6.0.5. We create a new angular project,

ng new p01-google-map-angular

The project name has certain restrictions. I remember ‘_’ is not allowed.

To use maps with angular maps we need to let angular know this type types/googlemaps,

npm install @types/googlemaps --save

In our app’s typescript template src/app/app.component.ts we import,

import { ViewChild } from '@angular/core';
import { } from '@types/googlemaps';

We add an ngOnInit method and instantiate a map object to use across the template file,

ngOnInit() {
  var mapProp = {
    center: new google.maps.LatLng(this.latitude, this.longitude),
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
}

In head section of index.html we add,

<a href="https://maps.googleapis.com/maps/api/js?key=API_KEY">https://maps.googleapis.com/maps/api/js?key=API_KEY</a>

In modules src/app/app.module.ts we import FormsModule to use forms.

Now that we got all the required stuffs to use google maps with angular we embed google map in the page src/app/app.component.html,

<div style="width:100%;height:600px;"></div>

We include buttons and call required methods from index.html.

While implementing marker removal Remove Markers came in handy. More on marker can be found in references section below.

My demo is published in the github repository.

Click Events

I found managing click events to be bit of tricky. When I add a click listener to the map I was not able to determine the type of argument. Simple event click provides some insight.

References

  1. How can I integrate Google Maps APIs inside an Angular 2 component
  2. maps js tutorial
  3. Lat, Lng reference
  4. Marker Overview
  5. Custom Marker Symbol

Codeforces Online Judge Peculiarities

Every online judge has some customization due to which they behave differently. Sometimes, it gets annoying. However, there are no other ways around to get problems accepted without knowing those peculiarities.

  1. Some newer C# functions/features are not available. For example, recent editions of C# has Array.Reverse(). However, online judge throws a runtime error if we call the function.
Unhandled Exception: System.MissingMethodException: Method not found: 'Void System.Array.Reverse(!!0[])'.
   at BracketUtil.GenerateCorrectSubstring(String exp)
   at BracketUtil.Run()
   at CF_Solution.Main()

Runtime error: exit code is -532462766
  1. CultureInfo: Default Culture is set to Russian in Codeforces I guess. Therefore, format specifier such as ‘F12’ produces ‘,’ instead of ‘.’ Setting culture to “en-US” enables us to achieve expected behavior. For example, for problem Dreamoon and WiFi we print the decimal result specifying “en-US” culture.
Console.WriteLine(PC.GetProbability().ToString("F12", CultureInfo.
  CreateSpecificCulture("en-US")));

Problems in codeforces site where we need to explicitly specify culture,
1. Dreamoon and WiFi
2. Depression
3. Vanya and Lanterns

Intro to C# 5.0 Fundamentals with Scott Allen

[draft article, yet to finalize]
Pluralsight has a Course by Scott Alen on C# 5.0

.Net Framework is part of Visual Studio installation. So that C# language can utilize the language and APIs provided by the framework..

CLR

CLR’s pivotal part is Framework class library (FCL)
CLR is an execution environment for C# executables
It has following responsibilities,

  • Memory management
  • Operating system and hardware independence
  • Language independence

In detail, it virtualizes the environment so we do not need to worry about OS: 32 bit or 64 bit and underlying architecture. We can use a number of languages such as F# or others to target the CLR.

It is available for every Windows OS Version available since XP.

FCL

FCL is A library of functionality to build applications. Here’s an illustration from the course,

FCL Intro

regular expression
read/write data from a disk

BCL (base class library) – subset

subset that works everywhere

FCL is so large and varied..

DateTime.Now to get current date time

notepad hello.cs

versions of .Net Framework installed in my system,

  • v1.0.3705
  • v1.1.4322
  • v2.0.50727
  • v4.0.30319

CSC – visual C# compiler

In powershell, I can observe content,

gci C:\Windows\Microsoft.NET\Framework\

Example code we are compiling,

using System;
using System.Collections.Generic;

/*class Sorting {
}*/

class CSDemo {
  public static void Main() {
    if (DateTime.Now.DayOfWeek == DayOfWeek.Monday)
      Console.WriteLine("Yay! Monday!");
    else if (DateTime.Now.DayOfWeek == DayOfWeek.Sunday)
      Console.WriteLine("Yay! Sunday!");
  }
}

Choosing a preferred version of compiler,

$ C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe D:\Code\PS\CS-ProblemSolving_Console\Program.cs
Microsoft (R) Visual C# Compiler version 4.7.2556.0
for C# 5
Copyright (C) Microsoft Corporation. All rights reserved.

This compiler is provided as part of the Microsoft (R) .NET Framework, but only supports language versions up to C# 5, which is no longer the latest version. For compilers that support newer versions of the C# programming language, see http://go.microsoft.com/fwlink/?LinkID=533240

$ D:\git_ws\fftsys_ws\PowerShell\Program.exe
Yay! Sunday!

After compiling, if we observe dump of the binary,

**********************************************************************
** Visual Studio 2017 Developer Command Prompt v15.5.5
** Copyright (c) 2017 Microsoft Corporation
**********************************************************************
[vcvarsall.bat] Environment initialized for: 'x86'

$ dumpbin /dependents D:\Program.exe
Microsoft (R) COFF/PE Dumper Version 14.12.25835.0
Copyright (C) Microsoft Corporation.  All rights reserved.


Dump of file D:\Program.exe

File Type: EXECUTABLE IMAGE

  Image has the following dependencies:

    mscoree.dll

  Summary

        2000 .reloc
        2000 .rsrc
        2000 .text

Developer command prompt however, give me following version,

$ csc
Microsoft (R) Visual C# Compiler version 2.6.0.62329 (5429b35d)
Copyright (C) Microsoft Corporation. All rights reserved.

warning CS2008: No source files specified.
error CS1562: Outputs without source must have the /out option specified

Part 2

csc
C# command line compiler

for multiple files.. Visual studio manages..

C# executable binary..
MSIL instructions for CLR

args[0]
first arg

Project -> Properties
Debug -> set command line arguments

Pillars of OOP
Encapsulation
Inheritance
Polymorhpism

return base.ComputeStatistic();

what’s the default access method for class members

inheriting from object is implicit

Abstract classes

See examples
cannot use virtual keyword
instead use override

Interfaces

like an API for the object..

difference between abstract classes and interfaces

class can inherit lot of interfaces

interfaces are favorable than abstract classes

interfaces don’t have access methods
no public, private..
also not required to have abstract keyword. by default, they are virtual

inherit from IEnumerable
to allow Foreach()

and implement GetNumerator()