HelloWorld in .Net Core really takes less than 10 minutes!

Intro

I have been paying attention to the development of the .NET Core framework and the great features coming out of it. Things like cross-platform compatibility are very appealing and open a whole new window of opportunities to the developer community. I never decided to start experimenting with this until now, and since I saw how easy it was to setup, I decided to share my experience here. In this post I will list the required steps to write a HelloWorld console application using .NET Core framework. It literally took me less than 10 minutes to see “Hello World” in the output window!

Steps to create HelloWorld console application in .NET Core

1. Go to dot.net and download the .NET Core SDK

– Download and install .NET Core SDK for Windows
I am using Windows, but the same steps can be applied to Mac and Linux.

2. Open a command line

c:\Users\luis.carrazana\Documents>
I like Windows PowerShell, but you could use the windows command line, or Terminal if using a Mac.

3. Check if .NET Code SDK was successfully installed

Execute the following command:

c:\Users\luis.carrazana\Documents> dotnet
You should see something like this:
dotnetcore

4. Create a folder for the project and navigate to it

c:\Users\luis.carrazana\Documents> cd "MyProjects"
c:\Users\luis.carrazana\Documents\MyProjects> md "DotNetCore101"
c:\Users\luis.carrazana\Documents\MyProjects> cd "DotNetCore101"
c:\Users\luis.carrazana\Documents\MyProjects\DotNetCore101>

5. Create a new project

Execute the following command:

c:\Users\luis.carrazana\Documents\MyProjects\DotNetCore101> dotnet new
Two files should be created:
Program.cs  (contains the program logic).
project.json  (contains project configuration, including dependencies).
DotNetCore-dir.PNG
This is the simplest boilerplate for a console application, and it contains the required logic to print “Hello World” to the console.

6. Restore dependencies and prepare the project for execution

Execute the following command:

c:\Users\luis.carrazana\Documents\MyProjects\DotNetCore101> dotnet restore
DotNetCore_restore.PNG
This step generates a new file: project.lock.json
This file should not be touched or checked into source control. Its purpose is to cache the result of analyzing project dependencies, so it is faster the next time. More details abut this file here.

7. Run the program

Execute the following command:

c:\Users\luis.carrazana\Documents\MyProjects\DotNetCore101> dotnet run
The logic should get executed and the “Hellow World” message should be displayed.
dotnetcore-helloworld

That’s it! You have a full .NET Core program running.

Editing the program

The steps above are useful for setting up the minimal required infrastructure to execute .NET Core logic. From this point, you will certainly want to start choosing developer tools that will allow you to write code in a very efficient way.
You can choose any text editor (including Notepad), or you may wanna choose a more robust IDE to make the development workflow more efficient. Coming from a pure .NET background, my immediate choice is the lightweight Visual Studio Code, which offers some nice integrations and can be executed in Windows, Mac and Linux.
So to edit and extend this program, I would manually open Visual Studio Code and load the project folder. However, I learned a very useful tip from Scott Hanselman in one of his training videos: from the command line, type “code .” and it will open Visual Studio Code with the current folder already loaded, ready to go. Pretty neat.
c:\Users\luis.carrazana\Documents\MyProjects\DotNetCore101> code .

Summary

This post described the required steps to provision and execute a quick console application using .NET Core. This framework is currently in Preview mode, and any developer can start using it to write code and run it on any platform. Being a Consultant working for big enterprises, I don’t see myself leveraging this framework for production in the near future. However, it is a good idea to pay attention to the great amount of innovation coming out of it. This is opening up a whole new world for writing great applications.

Reference

How to rename an Azure subscription

Intro

This post will provide the steps to rename an Azure subscription.

Why is this needed?

When managing several Azure subscriptions, keeping the default name may not be very desirable because you would like to quickly identify the customer, website, or any other association you have when managing resources and billing.

I recently ran into this issue myself, where I had to create a new subscription for managing the resources and billing for a production website separately from my own development and testing. When creating the subscription, I chose the Pay-As-You-Go type, and I wanted to rename it with the website name. So my naming convention is:”<websitename> Pay-As-You-Go”. This way, I’ll be able to get the exact billing for each production website in my account, and I could even decide to use different credit cards for each one.

The option for renaming a subscription is not available from the Azure portal. This is available from the windows azure account page. I’d be interested to know why Microsoft hasn’t decided to unify this and allow the action from the portal itself, at least for service administrators.

Renaming an Azure Subscription

  1. Navigate to the Windows Azure account page at: https://account.windowsazure.com and click on SUBSCRIPTIONS on top
    capture
  2. Select the subscription you want to rename, and click “Edit Subscription Details” from the right menu
    capture1
    Capture2.PNG
  3. Enter the new name and save it
    Capture3.PNG
  4. Navigate back to the  Azure portal and you should see the new name reflected under your subscriptions
    Capture4.PNG

How To: Compare two text files with PowerShell

Intro

This post shows the code to compare two text files and determine whether the content is identical or not, as well as listing a line by line comparison. This utility could be useful to verify some scenarios, such as migrations, upgrades.

Comparing two files with PowerShell

The script below takes two files stored in the Desktop, compares their content, and prints a message to determine whether they are identical or not.

$desktopFolder = [Environment]::GetFolderPath("Desktop")
$fileA = "$desktopFolder\FileA.txt"
$fileB = "$desktopFolder\FileB.txt"

If (Compare-Object -ReferenceObject $(Get-Content $fileA) -DifferenceObject $(Get-Content $fileB))
{
  Write-Host "Different" -foregroundcolor red
}
Else
{
  Write-Host "Identical" -foregroundcolor green
}

The second script compares two files and provides a line by line comparison.

$desktopFolder = [Environment]::GetFolderPath("Desktop")
$fileA = "$desktopFolder\FileA.txt"
$fileB = "$desktopFolder\FileB.txt"

Compare-Object $(Get-Content $fileA) $(Get-Content $fileB) -includeequal

Reference

Using the Compare-Object Cmdlet – TechNet

How To: Decode user name from claims format in SharePoint 2013

Intro

After converting a SharePoint web application to Claims Authentication mode, it is often required to write some code to decode and extract the regular user name in the way of domain\username. This is due to the fact that calling  SPContext.Web.CurrentUser.LoginName will now return an encoded string.

E.g: “i:0#.w|mydomain\luis.carrazana”.

A great explanation about how claims are formatted and how to identify the different claim types is provided by my colleague Wictor Wilén here.

In this post I’ll share a method for getting the regular user name without having to manually parse the encoded claim identity, and leveraging SharePoint built-in API. Here, I’m extending an original solution provided by Tobias Zimmergren, in order to address an issue when using HttppContext instead of SPContext.

Context about my scenario

In my case, I was maintaining a custom ASP.NET solution, which was originally built on top of SharePoint 2010. The platform was being upgraded to SharePoint 2013, and the web application was migrated to use claims authentication. The custom ASP.NET components made heavy used of the current logged in user name, which in some cases was retrieved using SPContext.Web.CurrentUser.LoginName and in other cases using HttpContext.Current.Identity.User.Name.

Tobias Zimmergren posted a great solution for getting the user name by leveraging the SharePoint built-in functions. I leveraged this solution in my project, but I faced the following issue:

When HttpContext.Current.Identity.User.Name is used to get the current user name, the encoded formatted string doesn’t contain the claim’s identity identifier. In this case, the encoded claim format for the user name will be something like “0#.w|mydomain\luis.carrazana” instead of “i:0#.w|mydomain\luis.carrazana” (notice how the “i:” is missing from the string). For this reason, the SharePoint built-in function SPClaimProviderManager.IsEncodedClaim will not work as intended.

Please share your comments if you know the reason behind this behavior and a better solution to address it.

Solution

To completely address this scenario and support both SPContex and HttpContext, I updated Tobias’ solution and added  another condition in case IsEncodedClaim method doesn’t work as expected. I check if the user name contains the ‘|’ character, in which case the string is converted back to the proper claims format and then decoded.

See the code below with my updated version.

public string GetUserLoginNameFromClaim(string userLoginName)
{
 using (new SPMonitoredScope("GetUserLoginNameFromClaim method called for " + userLoginName))
 {
 try
 {
 SPClaimProviderManager spClaimProviderMgr = SPClaimProviderManager.Local;
 if (spClaimProviderMgr != null)
 {
 if (SPClaimProviderManager.IsEncodedClaim(userLoginName))
 {
 // return the normal domain/username without any claims identification data
 userLoginName = spClaimProviderMgr.ConvertClaimToIdentifier(userLoginName);
 }
 else if (userLoginName.IndexOf('|') > -1)
 {
 //This case will occur if the user name was obtained from calling HttpContext.Current.User.Identity.Name
 //In this case, the encoded claim format for the user name will be something like "0#.w|mydomain\luis.carrazana" instead of "i:0#.w|mydomain\luis.carrazana"

 //This line will convert to the proper claim format, so we can later decode it.
 userLoginName = spClaimProviderMgr.GetUserIdentifierEncodedClaim(userLoginName);

 // return the normal domain/username without any claims identification data
 userLoginName = spClaimProviderMgr.ConvertClaimToIdentifier(userLoginName);
 }
 }
 }
 catch (Exception ex)
 {
 //Log exception here
 }

 return userLoginName;
 }
}

Summary

When a SharePoint web application is converted to use claims authentication, the current user name is encoded. This articles showed some code to properly use the SharePoint built-in methods for decoding the user name. It also addressed the issue when HttpContext is used, and the encoded string doesn’t contain the identity identifier.

Reference

How Claims encoding works in SharePoint 2010 – Wictor Wiléen

Tip: Getting the normal domain username from the claims username in SharePoint 2013 – Tobias Zimmergren

SPClaimProviderManager.GetUserIdentifierEncodedClaim method – MSDN Reference

Programmatically converting login name to claim and vice versa – Waldek Mastykarz

 

How to get the bytes from a file and convert them to Base64String in PowerShell

Introduction

In this post I’ll share a PowerShell script, that simply reads the bytes from a given file, converts those bytes to a Base64String, and then saves it to a text file.

A little background about why I needed this

I needed to troubleshoot a web service method and I wanted to use SOAP UI as the testing framework. The service method took a byte[] as a parameter and uploaded the corresponding file to a Yammer network.

I’ve been using SOAP UI for testing web services, but most of the times the requests were taking simple types, such as integers and strings. I learned that the way to pass a byte[] to an ASP.NET web service method is to use the Base64String representation, so my next task was to get the Base64String representation of any given file, so I could grab it as simple text and pass it to the XML test request. Rather than creating a console application, I thought that a PowerShell script would get it done faster.

Here is the script

#Get the bytes of a given file
$fileBytes = Get-Content <fileNameAndPath> -Encoding byte

#Convert byte array to base64 string
$fileBytesBase64 = [Convert]::ToBase64String($filebytes)

#Save Base64String to a text file
Add-Content outputFileBytesBase64.txt $fileBytesBase64

Reference

I was able to gather useful tips from these posts:

PowerShell Encoding and Decoding (Base64) – by Sean Metcalf

Efficient Base64 conversion in PowerShell – by mnaoumov