What’s New in C# 6.0 using examples.

The null-conditional operator avoids having to explicitly check for null before calling a method or accessing a type member.

System.Text.StringBuilder sb = null;
string result = sb?.ToString(); // result is null

Expression-bodied functions allow methods, properties, operators, and indexers that comprise a single expression to be written more tersely, in the style of a lambda expression:

public int TimesTwo (int x) => x * 2;
public string SomeProperty => "Property value";

Property initializers let you assign an initial value to an automatic property:

public DateTime TimeCreated { get; set; } = DateTime.Now;

Read-only properties can also be set in the constructor, making it easier to create immutable (read-only) types.
Index initializers allow single-step initialization of any type that exposes an indexer:

var dict = new Dictionary()
{
[3] = "three",
[10] = "ten"
};

String interpolation offers a succinct alternative to string.Format:

string s = $"It is {DateTime.Now.DayOfWeek} today";

Exception filters let you apply a condition to a catch block:

string html;
try
{
html = new WebClient().DownloadString ("//asef");
}
catch (WebException ex) when (ex.Status == WebExceptionStatus.Timeout)
{
...
}

The using static directive lets you import all the static members of a type, so that you can use those members unqualified:

using static System.Console;
...
WriteLine ("Hello, world"); // WriteLine instead of Console.WriteLine

The nameof operator returns the name of a variable, type, or other symbol as a string. This avoids breaking code when you rename a symbol in Visual Studio:

int capacity = 123;
string x = nameof (capacity); // x is "capacity"
string y = nameof (Uri.Host); // y is "Host"

You’re now allowed to await inside catch and finally blocks.

Reference: C# 7.0 in a nutshell by Oreilly publications

Continue Reading

What’s New in C# 7.0 using examples.

Numeric literal improvements
Numeric literals in C# 7 can include underscores to improve readability. These are ignored by the compiler:

int million = 1_000_000;

Out variables and discards
You can now declare out variables on the fly:

bool successful = int.TryParse ("123", out int result);

And when calling a method with multiple out parameters, you can discard ones you’re uninterested in with the underscore character:

SomeBigMethod (out _, out _, out _, out int x, out _, out _, out _);

Patterns
You can also introduce variables on the fly with the is operator(pattern variables):

if (x is string s)

The switch statement also supports patterns, so you can switch on type as well as constants. You can also switch on the null value:

switch (x)
{
case bool b when b == true: // Matches only when b is true
..........
break;
case null:
...............
break;
}

Local methods
A local method is a method declared inside another function. Local methods are visible only to the containing function, and can capture local variables in the same way that lambda expressions do.

void WriteCubes()
{
Console.WriteLine (Cube (3));
int Cube (int value) => value * value * value;
}

More expression-bodied members
C# 6 introduced the expression-bodied “fat-arrow” syntax for methods, read-only properties, operators, and indexers. C# 7 extends this to constructors, read/write properties, and finalizers:

public class Person
{
string name;
public Person (string name) => Name = name;
public string Name
{
get => name;
set => name = value ?? "";
}
~Person () => Console.WriteLine ("finalize");
}

Deconstructors
C# 7 introduces the deconstructor pattern. Whereas a constructor typically takes a set of values (as parameters) and assigns them to fields, a deconstructor does the reverse and assigns fields back to a set of variables:

public void Deconstruct (out string firstName, out string lastName)
{
int spacePos = name.IndexOf (' ');
firstName = name.Substring (0, spacePos);
lastName = name.Substring (spacePos + 1);
}

Deconstructors are called with the following special syntax:

var joe = new Person ("Joe Bloggs");
var (first, last) = joe; // Deconstruction
Console.WriteLine (first); // Joe
Console.WriteLine (last); // Bloggs

Tuples
Tuples provide a simple way to store a set of related values:

var tuple = (Name:"Bob", Age:23);
Console.WriteLine (tuple.Name); // Bob

With tuples, functions can return multiple values without resorting to out parameters:

static (int row, int column) GetFilePosition() => (3, 10);
static void Main()
{
var pos = GetFilePosition();
Console.WriteLine (pos.row); // 3
Console.WriteLine (pos.column); // 10
}

Tuples implicitly support the deconstruction pattern, so they can easily be deconstructed into individual variables.

static void Main()
{
(int row, int column) = GetFilePosition(); // Creates 2 local variables
Console.WriteLine (row); // 3
}

throw expressions
With C# 7, throw can also appear as an expression in expression-bodied functions:

public string Foo() => throw new NotImplementedException();

A throw expression can also appear in a ternary conditional expression:

string Capitalize (string value) => value == null ? throw new ArgumentException ("value") : value == "" ? "" : char.ToUpper (value[0]) + value.Substring (1);

Reference: C# 7.0 in a nutshell by Oreilly publications

Continue Reading

Configure error logging using Serilog.Sinks.Postgres and appSettings.json

Install nuget packages
Serilog.Sinks.PostgreSQL
Microsoft.Extensions.Configuration.Json

Program.cs:

public class Program
   {
     public static void Main(string[] args)
     {
       var path = Directory.GetCurrentDirectory();
       var environmentName =Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production";
      var configuration = new ConfigurationBuilder()
         .SetBasePath(path)
         .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
         .AddJsonFile($"appsettings.{environmentName}.json", optional: true, reloadOnChange: true)
         .AddEnvironmentVariables()
         .Build();
       Log.Logger = new LoggerConfiguration().
         Enrich.FromLogContext().
         ReadFrom.Configuration(configuration).
         CreateLogger();
      try
       {
         var iWebHost = CreateWebHostBuilder(args).Build();
         Log.Information("Application starting");
         iWebHost.Run();
       }
       catch (Exception exception)
       {
         Log.Error(exception.ToString());
       }
       finally
       {
         Log.CloseAndFlush();
       }
     }
    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .UseStartup()
        .UseSerilog();
   }

appsettings.json:

"Serilog": {
     "Using": [ "Serilog.Sinks.PostgreSQL" ],
     "MinimumLevel": "Warning",
     "WriteTo": [
       {
         "Name": "PostgreSQL",
         "Args": {
           "connectionString": "",
           "tableName": "Logs",
           "needAutoCreateTable": true,
           "batchPostingLimit": 1
         }
       }
     ]
   }
Continue Reading

Fix for ‘’Npgsql.PostgresException: syntax error at or near ‘[‘”

We decided to change our database from SQL server to Postgres in our application. When I tried to apply the database migrations to the database it failed with a
Npgsql.PostgresException (0x80004005): 42601: syntax error at or near "[" error.
On further analyzing the issue I found that this issue occurs as the migrations were created on SQL Server and contain SQL Server-specific code.

To fix this issue, I
a. Removed the Migrations folder in your application.
b. Ran “Add-Migration Init” in the package manager console
c. Ran “Update-Database”, to flush the SQL Server predefined context.

Continue Reading

“Error starting userland proxy: Bind for unexpected error Permission denied” error when debugging ASP.Net Core application

If you get an “Error starting userland proxy: Bind for unexpected error Permission denied” error, when debugging your ASP.Net Core application in Docker, then run the following command to find the excluded ports range, being used by different applications:

netsh int ip show excludedportrange protocol=tcp

image

I then change my launchSettings.json file to use a port that is not reserved

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "//localhost:50504",
      "sslPort": 44392
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "Scrubber": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "//localhost:5001;//localhost:5000"
    },
    "Docker": {
      "commandName": "Docker",
      "launchBrowser": true,
      "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
      "environmentVariables": {
        "ASPNETCORE_URLS": "//+:443;//+:80",
        "ASPNETCORE_HTTPS_PORT": "44393"
      },
       "httpPort": 54558,
      "useSSL": true,
      "sslPort": 44393
    }
  }
}
Continue Reading

Deploy a ASP.Net Core application to Digital Ocean

  • Make sure that your source code is checked into Github. Check in the DockerFile in the root of the repository.
  • Create a account in DockerHub at //hub.docker.com/.
    Create a new repository and connect your github repository. 
    Click Create & Build. With this, when new changes are checked into your Github repository it will be automatically build in DockerHub and a new image created.

    image

Create a new account\Login in Digital Ocean.
Create a new Droplet.

image

Select Docker and select the 5$\month plan.  Select One time password for Authentication.
Click create Droplet.

image

After the droplet is created, click the droplet.
image

Then click the console link on the right hand side.
image

In the console window, login into the your droplet using the login id and one time password, provided in email. You will be asked to change the password.
To install the application, in the console window, login into docker hub using the following command:

login docker

pull the image for your application using the following command:

docker pull ajitgoel/socialmediascrubber

To run the docker image, use the following command:

docker run –p 80:80 ajitgoel/socialmediascrubber

your website should now be visible at

//<PublicIpAddress>
Continue Reading

Fix for “Unable to bind to the underlying transport for [::]:<PortNumber>. The IP Listen-Only list may contain a reference to an interface which may not exist on this machine.

I have been developing on Visual studio and IISExpress for sometime when I started getting the following error:
Unable to bind to the underlying transport for [::]:50160. The IP Listen-Only list may contain a reference to an interface which may not exist on this machine.

Deleting the .vs folder in the application or the C:\Users\<UserName>\Documents\IISExpress\config folder, restarting the IISExpress or machine,  did not help nor did adding the “::”  value to the registry key Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP\Parameters\ListenOnlyList
image

What finally worked for me when I ran the following command, I see that the ports from 49697 to 50503 were reserved by Docker.  So I changed the application port to 50504 and the application was able to run correctly on IISExpress.

netsh interface ipv4 show excludedportrange protocol=tcp

image

Continue Reading

Azure App service for containers error: repository does not exist or may require ‘docker login’

I have configured my ASP.Net Core 2.2 application for continuous build and deploy through Visual Studio 2019. I also see that the image has been build and the deploy successful in Azure DevOps. However in my App service’s application logs, I see the following errors:

2019-07-03 05:44:22.174 ERROR - Pulling docker image productssimplerregistry/simpler.products:5 failed:
2019-07-03 05:44:22.179 INFO  - Pulling image from Docker hub: productssimplerregistry/simpler.products:5
2019-07-03 05:44:23.663 ERROR - DockerApiException: Docker API responded with status code=NotFound, response={"message":"pull access denied for productssimplerregistry/simpler.products, repository does not exist or may require 'docker login'"}
2019-07-03 05:44:26.233 ERROR - Image pull failed: Verify docker image configuration and credentials (if using private repository)

To fix the issue, you should ensure that your application’s pipeline’s Azure Container Registry is the fully qualified name like  productssimplerregistry.containers.azurecr.io instead of just productssimplerregistry.

2019-07-03 19_23_27-Window

Continue Reading

Configuring Serilog SQL server sink logging for ASP.Net Core application

Here are the changes that you need to make in your ASP.Net Core web application to configure Serilog logging with SQL server sink.

a. Install the following libraries from Nuget, using the Nuget Package Manager
Serilog.AspNetCore
Serilog.Extensions.Logging
Serilog.Settings.AppSettings
Serilog.Settings.Configuration
Serilog.Sinks.MSSqlServer

b. Program.cs:


using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Serilog;
using System;
using System.IO;

namespace Scrubber
{
  public class Program
  {
    public static void Main(string[] args)
    {
      var path = Directory.GetCurrentDirectory();
      var environmentName =Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production";

      var configuration = new ConfigurationBuilder()
      .SetBasePath(path)
      .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
      .AddJsonFile($"appsettings.{environmentName}.json", optional: false, reloadOnChange: true)
      .Build();

      Log.Logger = new LoggerConfiguration()
        .Enrich.FromLogContext()
        .ReadFrom.Configuration(configuration)
        .CreateLogger();

      try
      {
        WebHost.CreateDefaultBuilder(args)
          .UseStartup()
          .UseSerilog()
          .Build()
          .Run();
      }
      finally
      {
        Log.CloseAndFlush();
      }
    }
  }
}

AppSettings.json:


{
  "Serilog": {
    "Using": [ "Serilog.Sinks.MSSqlServer" ],
    "MinimumLevel": "Information",
    "WriteTo": [
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "YourSQLServerConnectionString",
          "tableName": "Logs",
          "autoCreateSqlTable": true
        }
      }
    ]
  }
}
Continue Reading

System.BadImageFormatException: Index not found. (Exception from HRESULT: 0x80131124)

If you get a

An unhandled exception has occurred while executing the request. 
System.BadImageFormatException: Index not found. (Exception from HRESULT: 0x80131124)

error when publishing your website through Visual Studio, a couple of things to check are:

  • When publishing the application to Azure make sure that the “Remove Additional Files at destination” option is checked.

    image
  • Made sure that all the projects(only one) were being build as “Any CPU” in both “debug” and “release” configuration.
    image
Continue Reading
1 2 3 6