Browsing:

Categorie: c#

Setting up Ubuntu 17.10 for .NET Core Development (including SQL Server, Visual Studio Code, PowerShell and SQL Operations Studio)

In this post I will show you how to set up an Ubuntu desktop that you can use for .NET Core Development.

Why?

Maybe because you want to do Microsoft development on older hardware or because you think Windows is too bloated.

Install the OS

In this example I use the latest Ubuntu version. Mind you, in April another LTS version will be out but I can’t wait and will probably update this article.

Update and essentials

Once installed, open up your terminal and enter:

sudo apt-get update -y
sudo apt-get upgrade -y

sudo apt-get install -y wget curl git gitk \ 
vim build-essential linux-headers-$(uname -r) zsh 

This the essentials you will want, build tools and zsh.

Oh My Zsh

I prefer the zsh and Oh My Zsh over Bash because of its auto complete features and eye candy.


wget https://github.com/robbyrussell/oh-my-zsh/raw/master/tools/install.sh -O - | zsh

And the Powerline fonts for a lovely prompt:

cd ~/Downloads
git clone https://github.com/powerline/fonts.git
cd fonts
./install.sh

Set the default shell to zsh:

chsh -s `which zsh`

Now log out and log back in.
You can then set your favorite theme by editing ~/.zshrc.

Node.js

Next we will install Node.js and fix npm so we can run it without sudo:

curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs
mkdir ~/npm-global -p
sudo chown -R $USER:$USER ~/npm-global
npm config set prefix '~/npm-global'

#add to path:
echo "export PATH=~/npm-global/bin:$PATH" >> ~/.zshrc

Trust the Microsoft sources

curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg
sudo mv microsoft.gpg /etc/apt/trusted.gpg.d/microsoft.gpg

Add the repo’s for the .Net Core SDK, Powershell, Visual Studio Code, SQL Server at once


sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-ubuntu-artful-prod artful main" > /etc/apt/sources.list.d/dotnetdev.list'

curl https://packages.microsoft.com/config/ubuntu/17.04/prod.list | sudo tee /etc/apt/sources.list.d/microsoft.list

sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main" > /etc/apt/sources.list.d/vscode.list'

sudo add-apt-repository "$(wget -qO- https://packages.microsoft.com/config/ubuntu/16.04/mssql-server-2017.list)"

sudo add-apt-repository "$(wget -qO- https://packages.microsoft.com/config/ubuntu/16.04/prod.list)"

Now install the software:

sudo apt-get update 
sudo apt-get install dotnet-sdk-2.1.3 powershell code mssql-server mssql-tools unixodbc-dev

Configure Sql Server

You will need to run setup to choose the correct Sql Server version and to set the SA password.

sudo /opt/mssql/bin/mssql-conf setup
# Verify
systemctl status mssql-server

Install Sql Server Tools

Next we need to instal sqlcmd:

wget http://download.microsoft.com/download/B/2/0/B20D3C84-C82A-4638-8E8C-164E09B96F71/sqlops-linux-0.25.4.deb
sudo dpkg -i sqlops-linux-0.25.4.deb

# Now login:
sqlcmd -S localhost -U SA -P ''

And we’re done

We now have an Ubuntu desktop for .NET Core development, including Sql Server. Now go ahead and do

dotnet new webapi

Next, install the Entity Framework Core package, create a full fledged backend and enjoy the fact that Microsoft has gone out of its way to make this all possible!

Script

For your convenience: here is a Gist that contains this script.

Links

https://github.com/PowerShell/PowerShell/blob/master/docs/installation/linux.md
https://code.visualstudio.com/docs/setup/linux
https://docs.microsoft.com/en-us/sql/sql-operations-studio/download
https://docs.microsoft.com/en-us/sql/linux/quickstart-install-connect-ubuntu


Build a C# REST API and consume it with Powershell (and write Pester tests!) (part 2)

This is the sequel to part 1.
Now we are going to query the AdventureWorks Database.

Install the AdventureWorks database

The script below downloads the AdventureWorks database for SQL Server 2014, extracts it in c:\temp and restores it. As you can see I had to change the data and the log locations because the original AdventureWorksDb is created in another version of SQL Server.

With the SQL Powershell commandlets you have to create 2 ‘Microsoft.SqlServer.Management.Smo.RelocateFile’ objects to do so. Now, if you have both SQL Server 2014 Express and Visual Studio 2015 Community Edition installed, the SQL Server Management dlls get messed up, because both version 12 and 13 are loaded in the app domain. You can check that with

[appdomain]::CurrentDomain.GetAssemblies() | ? { $_.Location -like "*smo*" } 

This knowledge results in this script. See also this question from StackOverflow.


New-Item 'c:\temp' -ItemType Directory -Force 
Set-Location C:\temp
choco install 7zip.commandline --yes --force
wget https://msftdbprodsamples.codeplex.com/downloads/get/880661# -OutFile adventureworksdb.zip
7z e .\adventureworksdb.zip

Import-Module SQLPS

$RelocateData = New-Object 'Microsoft.SqlServer.Management.Smo.RelocateFile, Microsoft.SqlServer.SmoExtended, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' -ArgumentList "AdventureWorks2014_Data", "C:\Program Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\DATA\AdventureWorks2014.mdf"

$RelocateLog = New-Object 'Microsoft.SqlServer.Management.Smo.RelocateFile, Microsoft.SqlServer.SmoExtended, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' -ArgumentList "AdventureWorks2014_Log", "C:\Program Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\Log\AdventureWorks2014.ldf"

#Invoke-Sqlcmd -ServerInstance '.\sqlexpress' -Query "DROP DATABASE AdventureWorks2014"
Restore-SqlDatabase -ServerInstance localhost\sqlexpress -BackupFile C:\temp\AdventureWorks2014.bak -Database AdventureWorks2014 -RelocateFile @($RelocateData,$RelocateLog)

Add Linq to SQL classes

Now it’s time to add an Object Relation Mapper. If the app is using Microsoft SQL and is relatively easy (only a few tables, not too much relationships) then why not go ahead and use good old Linq2SQL. It’s incredibly easy.

So type CTRL+Shift+A
Add Linq to SQL Classes and call it AdventureWorks.dbml.

20160515linq

Next, open Server Explorer and drag the Person table to the canvas like this:

20160515serverexpl

Now build the Project. And we are done. This simple drag and drop action created a Person class and added the ConnectionString to the Web.Config file.

Create a Person Controller

In the Controllers folder, add a new Class named PersonController.

Change the first Get method as follows:

// GET: api/Person
public IQueryable<Person> Get()
   {
       var db = new AdventureWorksDataContext();
       var people = db.Persons.Take(10);
       return people;
   }

So here we changed the return type in ‘Queryable’, because that is the return type of a AdventureWorksDataContext collection. You see that we only pick 10 records because the Person table has almost 20.000 records and it takes a long time to load them all.

Now, hit build and start debugging. Fire up Powershell and type:

curl http://localhost:49491/api/person

You may need to change the url to match yours. The result should be:

ice_screenshot_20160515-134347

Consume the api with Powershell and test with Pester

A tip: read http://mikefrobbins.com/2014/10/09/using-pester-for-test-driven-development-in-powershell/ because it explains in a very concise way how to use Pester. It’s great to be able to write unit tests for Powershell. If you are not sure why you should be writing tests, read this.

Shouldn’t I test the api as well? Yes, I definitely should and I will, but it’s not in scope of this article. So let’s get started with Powershell.

First, add a new Test:

New-Fixture -Name Get-AWPeople -Path .\AWcmdlets -Verbose

This creates 2 files in the AWcmdlets folder:

ice_screenshot_20160515-135708

This is the contents of the Get-AWPeople.Tests.ps1 file:

So let’s invoke a test:

20160515pester-fail

Of course, it fails. Now, let’s write code in the Get-AWPeople.ps1 file:

function Get-AWPeople 
    [CmdletBinding()]
    param (
        [Parameter(Mandatory, 
                   ValueFromPipeline)]
        [string]$Uri
    )
 
    PROCESS {
       $data = ((Invoke-WebRequest $Uri).content) | ` 
                  ConvertFrom-Json
       Write-Output $data.count
    }

}

We would expect the output to be 10 of course, because our api returns only 10 entries.

Next, write the test:

$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".")
. "$here\$sut"

Describe "Get-AWPeople" {
    It "returns 10 entries from the Person table" {
        $result = Get-AWPeople -Uri "http://localhost:49491/api/person"
        $result | Should Be 0
    }
}

Let’s run the test again:

20160515pester2-fail

Now change the 0 in the file to 10 and run Invoke-Pester:

20160515pester2-OK

And we have a success. Now on to write some more functionality!

agile


Query a database through a C# REST API with Powershell (part 1)

It is probably known that you can query an SQL database in Powershell relatively easy, but wouldn’t it be great to quickly write a REST API in front of the database? So that you can add business logic if you wish? And use Powershell as a REST client? And then be able to code a decent frontend for the API for whatever device?

Let’s get started!
In this series I will first create a WebApi from scratch. Of course, you can also use the templates in Visual Studio, but I prefer to have a bit of knowledge of the code that’s in my project. It’s not that hard and you will end up with a clean code base.

Step 1. Get your dev environment ready

You can use a Vagrant box. If you use this Vagrantfile a install.ps1 script will be copied to your desktop. Run it, grab a coffee or go shopping because we are on Windows and Windows apps can be huge.

Step 2. Getting the VS Project in place

Start Visual Studio
Create a new empty solution:

ice_screenshot_20160508-093224

I named the empty solution BusinessApp (I’m lacking inspiration for a better name).

Then right click the newly made solution in the Solution Explorer (the pane on the right) and click Add and the New Project:

20150508-context

 

 

 

 

 

I named the new Project BusinessApp.Api. If you set your solution up like this you can add more projects as you continue extending the app, for example for an Angular (or whatever framework) frontend, or if you want to separate your datalayer. You can also put your Powershell client modules in a separate project if you wish.

Then open up the Nuget Package Manager Console and install the WebApi dll’s:

Install-Package Microsoft.AspNet.WebApi

Make sure to choose the correct Package source (Microsoft and .NET).

Step 3. Add routing

Add a new folder and name it App_Start.
Create a new class in the folder and name it WebApiConfig.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;


namespace BusinessApp.Api
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

In this class we configure that we want our api to return and consume json. Also, we configure our routes to match the controller name, followed by id, wich is optional. E.g http://example.com/api/employees/1 would match a controllername Employees, and it would return employee with id 1.

Step 4. Enable CORS

We need to enable CORS else we won’t be able to consume the api from from another domain outside the domain from which the resource originated. In a production web environment you should configure this very carefully. I will CORS very permissive because I want my code to work.

Install CORS with in Nuget console:

Install-Package Microsoft.AspNet.WebApi.Cors

Then modify the WebApiConfig.cs class as follows:

using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;

namespace BusinessApp.Api
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);
            config.MapHttpAttributeRoutes();
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

Step 5. Add a Controller

  • Create a folder named ‘Controllers’
  • Right click the Controllers folder and click Add and then Controller
  • Click Web API 2 Controller with read/write actions.

ice_screenshot_20160508-092302

I named the Controller Test Controller.

Step 5. Add a Global.asax file

We need to add a Global.asax file to call the WebApiConfig.cs methods at startup.

Right click the solution, click Add, click New Item and search for Global.asax, then Add it.

ice_screenshot_20160508-095951

Modify Global.asax (see the highlighted lines):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Security;
using System.Web.SessionState;

namespace BusinessApp.Api
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }

 

Step 6. Test the API

Hit F5 and browse to http://localhost:/api/test

ice_screenshot_20160508-100831

And it works. You can also consume the API with Powershell at this point:

((Invoke-WebRequest http://localhost:53601/api/test).content) | ConvertFrom-Json

It should return value1 and value2.

Done! Now let’s query a database. This will be explained in Part 2.


ASP.NET 5 getting started from scratch

Let’s see how ASP.NET 5 works and discover how we can build a basic website with an API and an Angularjs frontend. Just like we’re used to doing with Node.js. Let’s see how the Microsoft way compares. Maybe I’m a little late because the current release seems to be 1.0.0.-rc2 on Github. So there’s tons of info on the Internet already. And here is my bit as well. 🙂

I will use the Visual Studio Community Edition and I’ve got a VirtualBox VM running. And let’s also host the app in Azure and see how we can collaborate using the Visual Studio Online tools.

First, select File, New, Project and select the Empty ASP.NET 5 template:

aspnet5_1

 

 

 

 

 

 

 

Let’s debug and run it immediately!

aspnet5_2

 

 

 

 

Cool! Now where did that came from?

Startup.cs

Startup.cs is the entrypoint for an ASP.NET 5 application. I feel it compares to the app.js or index.js in an Express application which requires all the dependencies needed for the application. It is what the Global.asax was before. There are 2 sections: ConfigureServices and Configure. I think the comments describes their purposes really well:

public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app)
        {

           
            app.UseIISPlatformHandler();
              
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });             
        }

        // Entry point for the application.
        public static void Main(string[] args) => WebApplication.Run(args);
    }

Adding a static page

If we follow along the Express.js workflow, I would now need to add the possibility to add a static file (index.html). And I would need to plug that in to the Startup.cs. And I would need to install the dependencies in a package.json sort of file:

And that is correct. There is a project.json file in the solution and I need to add a dependency to Microsoft.AspNet.StaticFiles. Add it like I did at line 10. (It has intellisense, cool!)

{
  "version": "1.0.0-*",
  "compilationOptions": {
    "emitEntryPoint": true
  },

  "dependencies": {
    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
    "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final"
  },

  "commands": {
    "web": "Microsoft.AspNet.Server.Kestrel"
  },

  "frameworks": {
    "dnx451": { },
    "dnxcore50": { }
  },

  "exclude": [
    "wwwroot",
    "node_modules"
  ],
  "publishExclude": [
    "**.user",
    "**.vspscc"
  ]
}

Now I can add an index.html file in wwwroot and edit Startup.cs. Delete everything in the Configure method and add ‘app.UseStaticFiles();’.

 public void Configure(IApplicationBuilder app)
        {
            app.UseStaticFiles();
        }

Run the app and now this page is served:
aspnet5_3

 

 

 

 

But of course I don’t want to type in the URI. I want the web app to server default files.
Then it seems I still need to add middleware to serve the index.html. Add ‘app.UseDefaultFiles(); to the Configure method in Startup.cs:

public void Configure(IApplicationBuilder app)
        {
            app.UseDefaultFiles();
            app.UseStaticFiles();
        }

You can find a great explanation here.

So great! That means I can go ahead and add Bootstrap and Angular and that I can write some serious api in C#.

BTW, if you want to know how Microsoft (and the community I must add) has envisioned an ASP.NET 5 web project, please try the MVC web app template.


I use Ubuntu as a development workstation (but it doesn’t matter!)

I use Ubuntu as my development machine and I like to evangelize about it. But actually it doesn’t matter at all. It’s the functionality I run that is the most important. And since that is the case, the underlying OS becomes irrelevant. That’s why I tend to choose the OS with the smallest footprint. Which would be a Linux based OS.

So here is why, and how, I use Ubuntu.

2014-05-24_10-42-50

This picture is Ubuntu running in Parallels, which looks great in high res on the MacBook Pro Retina screen.

Some Linux advantages over another OS

There are some advantages of running Ubuntu (or another Linux distro):

  • system requirements are low, you can happily use older hardware
  • the software is open source and free (as in ‘costs nothing’, although I donate to my favourite open source projects like LibreOffice and Ubuntu itself).
  • installation is easy, however installing Windows is easy too.
  • installation is fast because Ubuntu has a smaller footprint than Windows (8 GB vs 20 GB, and then Ubuntu is considered large in comparison with e.g. Puppy Linux)
  • installation of software is a delight, because of the packaging method (apt, yum, rpm, pacman and so forth). With a package manager you do not need to browse to websites to grab a copy
  • Updating is just as simple apt-get update && apt-get upgrade
  • If you prefer to work with the keyboard and in the terminal, Linux is your best fried. Just choose your terminal, your favourite shell, your favourite editor and your good to do any kind of task

So how do I use Ubuntu?

  • I am a keyboard user. Ubuntu is very friendly for keyboard users! Especially the Dash is very handy:
  • As IDE I use Subtext and Vim. In Vim I us the NERDTree. Vim deserves a dedicated post. It’s an extremely versatile editor that lives in the terminal and it is very small (6 MB). It has a steep learning curve. But when you get the hang of it you’ll notice how powerful it is. And Vim is ubiquitous. It’s everywhere (as Vi on every Linux machine). Once you know vi, you can deal with every Linux machine out there.
    vim
  • I use Robomongo to browse Mongo databases.
  • The Gimp is a great Photoshop replacement, especially now that you can enable single Windows!
    gimp
  • Chrome is my mainbrowser. I use the apps a lot so I have access to them on every machine.
    chrome
  • Last but not least: I use XMind for mindmapping. It is multiplatform. And I love it. It too deserves a dedicated post.

    xmind

So I use Ubuntu

And yes, I can do all above mentioned things on my Mac and Windows machine as well, but going the Ubuntu way the footprint is the smallest.