ASP.NET

C# 8.0 New Feature–Interface Default Implementation for Methods

December 1, 2018 .NET, .NET 4.8, .NET Core, .NET Core 3.0, ASP.NET, Microsoft, Visual Studio 2017, VisualStudio, VS2017 No comments

With upcoming C# 8.0, there is an interesting feature called default implementation body for methods within an interface definition. That means if you have few methods signatures defined and you want make implementation classes to implement these methods optionally (remember, previously all interface methods needs to be implemented in implementation classes) , with C# 8.0, you can define methods to follow default implementation body, if it not explicitly implemented by implementation classes of the same interface.

When will we get C# 8.0?

C# 8.0 will be released along .NET Core 3.0, in upcoming months. Currently preview 1 version is available to try out.

Get Started:

1.) First of all, download and install Preview 1 of .NET Core 3.0 and Preview 1 of Visual Studio 2019.

imageimage

image

2.) Launch Visual Studio 2019 Preview, Create a new project, and select “Console App (.NET Core)” as the project type.

image

image

image

3.) Once the project is up and running, change its target framework to .NET Core 3.0 (right click the project in Solution Explorer, select Properties and use the drop down menu on the Application tab).

image

Here is how it can be implemented:

using System;

namespace CSharp8Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            IVehicle bmw = new Bmw();
            bmw.DefaultMessage();

            IVehicle audi = new Audi();
            audi.DefaultMessage(); 
        }
    }


    interface IVehicle
    {
        //default implementation 
        void DisplayMessage();

        void DefaultMessage() { Console.WriteLine("I am  inside default method in the interface!");} 
      
    }

    public class Bmw : IVehicle
    {
        public void DisplayMessage()
        {
            Console.WriteLine("I am BMW!!!");
        }
    }

    public class Audi : IVehicle
    {
        public void DisplayMessage()
        {
            Console.WriteLine("I am AUDI!!!");
        }
        public void DefaultMessage() => Console.WriteLine("I am  inside audi class!");
    }
}

Visual Studio 2017–Version 15.9.0 released

November 13, 2018 .NET, .NET 4.8, .NET Core, .NET Core 2.0, .NET Core 2.1, .NET Core 2.2, .NET Core 3.0, .NET Framework, ASP.NET, ASP.NET Core 2.1, C#.NET, JavaScript, Microsoft, Razor, SignalR, TypeScript No comments

Microsoft has today released Visual Studio 2017 – Update 15.9.0 with lots of bug fixed and improvements to the IDE for stability and performance.

image

Release Notes: Visual Studio 2017 version 15.9 Minor Release

Download the latest update from: visualstudio.com/downloads

Latest News: There is a new service update released on November 15, 2018 — Visual Studio 2017 version 15.9.1 Servicing Update

Useful Reads: 

Azure Cosmos DB–Multi Master

October 8, 2018 .NET, .NET Core, .NET Framework, ASP.NET, Azure, Azure CLI, Azure Cosmos DB, CosmosDB, Data Consistancy, Data Integrity, Microsoft, Multi-master, Performance, Reliability, Resilliancy, Scalability, Scale Up No comments

During the Ignite 2018, Microsoft has announced the general availability of Multi-Master feature being introduced to Azure Cosmos DB to provide more control into data redundancy and elastic scalability for your data from different regions with multiple writes and read instances.

What is Multi-Master essentially?

Multi-master is a capability that provided as part of Cosmos DB, that would provide you multiple write regions and provides an option to handle conflict resolution automatically through different options provided by the platform. Most of the major scenarios you would encounter the conflict can be resolved with these simple configurations.

A sample diagram depicting a use case of load balanced web app writing to respective regional master:-

image

With multi-master, Azure Cosmos DB delivers a single digit millisecond write latency at the 99th percentile anywhere in the world, and now offers 99.999 percent write availability (in addition to 99.999 percent read availability) backed by the industry-leading SLAs.

image

Wow! That’s an amazing performance Cosmos DB guarantees to provide so that your mission-critical systems will have zero downtime, if they start using Cosmos DB.

 

How to Enabled Multi-Master support in your Cosmos DB solutions?

Currently multi-master can only be enabled for new Cosmos DB instances using “Enable Multi-Master” option in Azure Portal or through PowerShell or ARM templates or through SDK.

These options are detailed below with necessary examples:

1.) Azure Portal – Enable Multi-region writes and Enable geo-redundancy

image

2.) Azure CLI 
Set the “enable-multiple-write-locations” parameter to “true”

az cosmosdb create \
   –-name "thingx-cosmosdb-dev" \
   --resource-group "consmosify-dev" \
   --default-consistency-level "Session" \
   --enable-automatic-failover "true" \
   --locations "EastUS=0" "WestUS=1" \
   --enable-multiple-write-locations true \

3.) AzureRM PowerShell
In AzureRM PowerShell cmdlet – Set enableMultipleWriteLocations parameter to “true”

$locations = @(@{"locationName"="East US"; "failoverPriority"=0},
             @{"locationName"="West US"; "failoverPriority"=1})

$iprangefilter = ""

$consistencyPolicy = @{"defaultConsistencyLevel"="Session";
                       "maxIntervalInSeconds"= "10";
                       "maxStalenessPrefix"="200"}

$CosmosDBProperties = @{"databaseAccountOfferType"="Standard";
                        "locations"=$locations;
                        "consistencyPolicy"=$consistencyPolicy;
                        "ipRangeFilter"=$iprangefilter;
                        "enableMultipleWriteLocations"="true"}

New-AzureRmResource -ResourceType "Microsoft.DocumentDb/databaseAccounts" `
  -ApiVersion "2015-04-08" `
  -ResourceGroupName "consmosify-dev" `
  -Location "East US" `
  -Name "thingx-cosmosdb-dev" `
  -Properties $CosmosDBProperties

4.) Through CosmosDB SDK
Setting connection policy in DocumentDBClient and set UseMultipleWriteLocations to true.

ConnectionPolicy policy = new ConnectionPolicy
{
   ConnectionMode = ConnectionMode.Direct,
   ConnectionProtocol = Protocol.Tcp,
   UseMultipleWriteLocations = true,
};
policy.PreferredLocations.Add("East US");
policy.PreferredLocations.Add("West US");
policy.PreferredLocations.Add("West Europe");
policy.PreferredLocations.Add("North Europe");
policy.PreferredLocations.Add("Southeast Asia");
policy.PreferredLocations.Add("Japan East");
policy.PreferredLocations.Add("Japan West");

Azure Cosmos DB multi-master configuration is the game changes that really makes it a true global scale database with automatic conflict resolution capabilities for data synchronization and consistancy.

In my later sessions I will write examples to cover how conflict resolutions can be configured and used in realtime scenarios.

Useful Refs:

Introduction to NDepend : Static Code Analysis Tool

June 16, 2018 .NET, .NET Core, .NET Framework, ASP.NET, Best Practices, C#.NET, Code Analysis, Code Quality, Dynamic Analysis, Emerging Technologies, Help Articles, Microsoft, Static Analysis, Tech-Trends, Tools, Tools, Visual Studio 2017, VisualStudio, Windows No comments , , , , , ,

As a developer, you always have to take the pain of getting adapted to the best practices and coding guidelines to be followed as per the organizational or industrial standards.  Easy way to ensure your coding style follows certain standard is to manually analyze your code or use a static code analyzer like FxCop, StyleCop etc. Earlier days I have been a fan of FxCop as it was free and it provides me all necessary general guidelines in terms  of improving my solution.

In this modern world of programming everything needs to be automated, as it saves time and money in terms of automating repetitive tasks and improves efficiency. This is where static code analysers coming effective.

What is Static Code Analysis?

Static program analysis is the analysis of computer software that is performed without actually executing programs, on some version of the program source code, and in the other cases, some form of the object code or intermediate compiled code .

Sophistication of static program analysis increases is based on how deep they analyze in terms of behavior of individual statements and declarations, to analyzing the entire source code.

PS: Analysis performed on executing programs is known as dynamic analysis.

In this article I will give you an overview of one such premier static code analysis tool that can be used for your daily development routine plus use it for CI integration for DevOps efficiency.

NDepend:

NDepend is a static analysis tool for .NET, specifically for managed code:  NDepdend supports a large number of code metrics, allowing to visualize dependencies using directed graphs and dependency matrix. It also performs code base snapshots comparisons, and validation of architectural and quality rules.

The important capabilities of NDepend are:

  • Dependency Visualization through dependency matrix and graphs.
  • Analyse and generate software quality metrics – as per the documentation it supports 82 quality metrices.
  • Declarative rule support through LINQ queries, and it is called CQLinq and comes with a large number of predefined CQLinq rules.
  • Integration support for Cruise Control.Net, SonarCube, am City. Code rules can be configured to be checked automatically in Visual Studio or during continuous integration(CI).

License: NDepend is a commercial tool with licensing options as below:

  1. Developer seats – $477 approx. / per seat.
  2. Build Machine seats  – $955 approx. / per seat.

** You could get volume discount if you bulk procure your licenses.

Installation: 

Once you obtained license you will able to download NDepend_2018.1.1.9041.zip, is latest version available while I write this article. Extract the zip file into your local folder, you could see the different packages/executables within the package.

image

1.) NDepend.Console    – Command line program to execute NDepend analysis.  You would be mostly using this component on CI Build server Help

2.) NDepend.PowerTools –  Helps write your own static analyzer based on NDepend.API, or tweak existing open-source Power Tools. Help

image

3.) NDepend.VisualStudioExtension.Installer – To install NDepend extension as part of Visual studio

image

4.) VisualNDepend – Independent visual environment for managing your NDepend tasks.

image

Visual Tool gives you different options to choose from:

  • You can analyse a Visual Studio Solution or project.
  • Analyse .NET assemblies in a folder.

image

image

image

For the demo purpose our analysis target would be one of the starter project from github –  ContosoUniversity by @alimon808.

image

image

Demo: Summary Report

image

Demo: Application Metrics

image

Demo: Dependency Dashboard:

image

Demo: Interactive Graph

image

Demo: Code Matrix View

image

Demo: Quality Gates Summary

image

Demo: Rules Summary

image

Conclusion:

NDepend is one of the best enterprise grade commercial static analyser seen so far.  There are Visual Studio Code Analysis, FxCop and Stylecop Analyzer tools available but they do not provide extensive level of analysis reports NDepend provides. Being a commercial tool it gives value for money for customers by what they need.  In terms of a day to day developer  or devops lifecycle, you can integrate NDepend in your build process, which could be simple as executing the NDepend Console and reviewing the output. With NDepend’s API it is easy to develop your own custom analysis tools based on CQLinq and NDepend.PowerTools(which is open source). You could find all the detailed help in NDepend documentation.

References:

Blazer – The new experimental web framework from Microsoft

May 2, 2018 .NET, .NET Core, .NET Core 2.0, C#.NET, Emerging Technologies, Microsoft, Razor No comments

In this world of multiple Web frameworks Microsoft would not want to stop experimenting with new frameworks for Web development. Innovation is a key to Microsoft, doesn’t matter the start later than the React(Facebook) and Angular(Google) , but Microsoft has proven most of the times they are good in developing cutting edge frameworks.  That’s how Blazer has born.

Blazer = Browser + Razer

As a ASP.net MVC developer I always loved Razer syntax that was shipped with ASP.NET MVC 3.0. Since then Microsoft has improved the Razor framework with async/await patterns and fluent syntaxes etc.

Concept is simple, use .NET for building browser based apps. Your familiar C# and Razor syntax can add lots of improvements in the way you build browser apps as a modern day web developer.

Why use .NET?

To simplify this question, quoting an excerpt  from Microsoft ASP.NET team blog:  “Web development has improved in many ways over the years but building modern web applications still poses challenges. Using .NET in the browser offers many advantages that can help make web development easier and more productive:

  • Stable and consistent: .NET offers standard APIs, tools, and build infrastructure across all .NET platforms that are stable, feature rich, and easy to use.
  • Modern innovative languages: .NET languages like C# and F# make programming a joy and keep getting better with innovative new language features.
  • Industry leading tools: The Visual Studio product family provides a great .NET development experience on Windows, Linux, and macOS.
  • Fast and scalable: .NET has a long history of performance, reliability, and security for web development on the server. Using .NET as a full-stack solution makes it easier to build fast, reliable and secure applications.

Blazor will have all the features of a modern web framework including:

  • A component model for building composable UI
  • Routing
  • Layouts
  • Forms and validation
  • Dependency injection
  • JavaScript interop
  • Live reloading in the browser during development
  • Server-side rendering
  • Full .NET debugging both in browsers and in the IDE
  • Rich IntelliSense and tooling
  • Ability to run on older (non-WebAssembly) browsers via asm.js
  • Publishing and app size trimming

Now the usual question arises? How is that possible? Running .NET in a Browser?

It is all started with WebAssembly, a new web standard for a “portable, size- and load-time-efficient format suitable for compilation to the web.

  • WebAssembly enables fundamentally new ways to write web apps. Code compiled to WebAssembly can run in any browser at native speeds.
  • WebAssembly is the foundational framework needed to build a .NET runtime that can run in the browser.
  • No plugins or extensions required.

Getting Started with Blazer:

Latest version of blazer framework available is 0.3.0 released on 02/05/2018.

Steps to setup Blazor 0.3.0:

  1. Install the .NET Core 2.1 SDK (2.1.300-preview2-008533 or later).
  2. Install Visual Studio 2017 (15.7 Preview 5 or later) with the ASP.NET and web development workload selected.
  3. Install the latest Blazor Language Services extension from the Visual Studio Marketplace.

Install the Blazor templates using command-line:

dotnet new -i Microsoft.AspNetCore.Blazor.Templates

Additional References:

Getting Started local development with Azure Cosmos DB services – Part 2

May 29, 2017 .NET, .NET Core 1.0, .NET Core 1.0.1, .NET Framework, ASP.NET, Azure, Azure SDK Tools, Azure Tools, Cloud Computing, CodeSnippets, CosmosDB, Document DB, Microsoft, PaaS, SaaS, Visual Studio 2015, Visual Studio 2015 Update 3, Visual Studio 2017, VisualStudio, VS2015, VS2017, Windows, Windows 10, Windows Azure Development, Windowz Azure No comments

In my previous article we discussed about setting local development environment using Cosmos DB Emulator for Windows. With this part 2 of the article, we will cover developing, debugging and integration related aspects of using Cosmos DB Emulator.

Developing with Cosmos DB Emulator

Once you have Cosmos DB emulator installed and running on your machine, you can use any supported Cosmos DB SDK or Cosmos DB REST API to interact with emulator. This process is same as you are using a Cosmos DB cloud service.

Cosmos DB Emulator also provides a build-in visual explorer through which you can view,create and edit collections and documents.

image

Before you integrate Cosmos DB SDK or Cosmos DB REST API you would need to generate master key for authentication. Unlike cloud service, Cosmos DB emulator only support single fixed account and master key.  You would not be able to communicate with Emulator without this master key.

Default Master Key:

Account name: localhost:<port>

Account key: C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==

PS: This key is only to be used in Emulator. You cannot use the same key for Production(Cosmos DB Cloud Service).

Furthermore, if you want to set your own key. You can go to command line references and run DocumentDB.Emulator.exe with sufficient command switch to set your own key. Remember it should meet the key security requirements. See command-line tool reference for more information.

The Azure Cosmos DB Emulator is installed by default to the C:\Program Files\Azure Cosmos DB Emulator  or C:\Program Files\DocumentDB Emulator  directory.

Once you have account name and key, you are good to go with development and debugging using Azure Cosmos DB emulator.

Let us start looking at how to use CosmosDB SDK. Once you add Cosmos DB SDK for .NET from NUGET sources. You would need to import the following namespaces to reference necessary classes.

 using Microsoft.Azure.Documents;
   
 using Microsoft.Azure.Documents.Client;
   
 using Microsoft.Azure.Documents.Linq;

Simple code to establish connection:

// Connect to the Azure Cosmos DB Emulator running locally use DocumentClient class in : 
DocumentClient client = new DocumentClient(
    new Uri("https://localhost:8081"), 
    "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==");

In the above code block we are directly embedding endpoint, key in the source code.But as a suggested approch keeping in mind to easily point to production service would be maintain the key in Web.config appSettings.

   <add value="https://localhost:8081/" key="endpoint"/>
    <add value="C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==" key="authKey"/>
 

Add NuGet reference to Microsoft.Azure.DocumentDB  (always use the latest version of the library)

image

For the ease of this article, I am going to use the existing ToDoList sample from DocumentDB Samples provided by Microsoft. You can originally find the same source from C:\Program Files\DocumentDB Emulator\Packages\DataExplorer\quickstart.

image

Copy and Unzip DocumentDB-Quickstart-DotNet.zip and open todo.sln in Visual Studio 2017 and your solution structure will look like below:

image

Now run the application in your Visual Studio.

1. You will see an initial screen:

image

2. Click on Create New:

image

3. New record will be added to your Azure Cosmos DB Emulator:

image

4. To verify in Cosmos DB emulator now open Cosmos DB explorer, click on Collections and Select ToDoList

image

5.Expand Documents and select item with id:da305da3-c1dc-4e34-94d9-fd7f82d26c58

image

Hope this article was helpful for you with initial development.  Share your feedback through comments and share this to your friends and colleagues.

Useful Links: