C# Fundamental | Introduction and Environment setup

Goal of this post is to give you the introduction that what we are going to achieve after completion of the video series. It will contain series of video which will make you proficient in C# programming language, and you will be able to develop your own software

Here is list of few major topics which we will cover.

  • Data types
  • Control statements
  • Class and Objects
  • Unit Testing
  • Value type and Reference type
  • Event and Delegate
  • Object Oriented Programming.
  • Collections
  • Error handling

These are few to name out, will learn a lot more than this.

Now we will install the Software Development Kit which will require for the software development.

We will install two components

  1. .NET Core SDK: This will help us to compile and run the system.
  2. Visual Studio code: Place to write the code, this is cross platform we can install it to any operating system.

Let’s install .NET Core SDK

You can navigate to the: this web address: dot.net or dotnet.microsoft.com it will land to the same page.

Now click on the download button.

As I am on windows system, this has by default selected windows, if you are using any other operating system then select the operating system you are on.

                we can see [Download .NET Core SDK] option, click on it will download the installer. Installation is very simple install and next – next it will install the sdk.

Now we will install the Visual studio core: Navigate your browser to you the: code.visualstudio.com

Select your operating system and click download.

Installation is same as above install and next – next.

Thank you. Will see in in next video: Where we will learn about the .Net core and .net framework.

Single Responsibility Principle – SOLID

One thing will have only one responsibilities to do thing

It state that there should not be more than one responsibility or dependency on one thing, and It should have one reason to change.

Every object should have single responsibility, and that responsibility should be entirely encapsulated by the class – Wikipedia 

There should never be more then one reason for a class to change -Robert C. “Uncle Bob” Martine 

Let’s have an example, where this is violating the rule than will correct the issue.

    public class Sale
    {
        public void ProcessOrder()
        {
            // Product price calculation and their quentity

            // Reduce the stock or inventory 

            // Place the order

            // Order to be assign to Customer 
        }
    }

Here we can see there is lots of activity is happening in one place, rather it should be divided into sub module or parts.

Here we can see how we can divided this using the Interface:

public class Sale
{
    private readonly IPriceCalculator priceCalculator;
    private readonly IStockManager stockManager;
    private readonly IPlaceOrder placeOrder;
    private readonly IAssignOrdertoCustomer assignOrdertoCustomer;

    public Sale(IPriceCalculator priceCalculator, 
        IStockManager stockManager, 
        IPlaceOrder placeOrder, 
        IAssignOrdertoCustomer assignOrdertoCustomer)
    {
        this.priceCalculator = priceCalculator;
        this.stockManager = stockManager;
        this.placeOrder = placeOrder;
        this.assignOrdertoCustomer = assignOrdertoCustomer;
    }
    public void ProcessOrder()
    {
        priceCalculator.CalculatePrice();

        stockManager.UpdateInventory();

        placeOrder.OrderPlace();

        assignOrdertoCustomer.Assign();
    }
}

SOLID Principles in simple word

SOLID is acronym of these word:
* Single Responsibility Principal
* Open Closed Principal
* Liskov  Substitution Principal
* Interface Segregation Principal
* Dependency Inversion Principal 

Single Responsibility Principal 
> One thing will have only one responsibilities to do thing
> Every object should have single responsibility, and that responsibility should be entirely encapsulated by the class – Wikipedia 
> There should never be more then one reason for a class to change -Robert C. “Uncle Bob” Martine 

Open Close Principal 
> Open for Extension but close for modification
> The Open/Closed Principal states that software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification -Wikipedia 

Liskov  Substitution Principal 
> Subs type should be substitutable for their base type
>  If S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e. an object of type T may be substituted with any object of a subtype S) without altering any of the desirable properties of the program (correctness, task performed, etc.) – Wikipedia 

The Interface Segregation Principal 
> Interface should have only things (method) which all the client suppose to use otherwise segregate those things (method) which might not be used by client in separate Interface  
> No client should be forced to depend on methods it does not use.[1] ISP splits interfaces that are very large into smaller and more specific ones so that clients will only have to know about the methods that are of interest to them – Wikipedia

Dependency Inversion Principal
> High-level modules should not depend on low-level modules. Both should depend on abstraction.
> Abstraction should not depend on details. Details should depend on abstractions. 

Getting started with Autofac with MVC and Kentico 12

//Initialize builder
var builder = new ContainerBuilder();
            
builder.RegisterSource(new ViewRegistrationSource());
builder.RegisterModule<AutofacWebTypesModule>();
builder.RegisterControllers(typeof(KenticoApplication).Assembly);

// Register repository
builder.RegisterAssemblyTypes(typeof(KenticoApplication).Assembly)
    .Where(m => m.IsClass && !m.IsAbstract && typeof(IRepository).IsAssignableFrom(m))
    .AsImplementedInterfaces()
    .InstancePerRequest();

// Register service
builder.RegisterAssemblyTypes(typeof(KenticoApplication).Assembly)
    .Where(m => m.IsClass && !m.IsAbstract && typeof(IService).IsAssignableFrom(m))
    .AsImplementedInterfaces()
    .InstancePerRequest();

//Register with differetn name then interface
builder.RegisterType<HomeRepository2>().As<IHomeRepository>().InstancePerLifetimeScope();

//Build
DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build()));

Call this above method in Application Start.

KenticoApplication is Global.ascx.cs class name who inherits to System.Web.HttpApplication In here

Note: Autofac can resolver all the dependency if the name is same else it will not like if my interface is with name IHomeRepository and implementation is in HomeRepository then it will resolve automatically but it will not resolve HomeRepository2 that will have to register manually.

Getting started with SignalR using ASP.NET Framework

SignalR is way to have bi-directional/live communication between client and server.

Install NuGet package: Microsoft ASP.NET SignalR.
It will add SignalR JavaScript

Now lets add Startup class in root directory, if not available in the project

using Microsoft.Owin;
using Owin;

[assembly: OwingStartup(typeof(SignalRDemo.Startup))]
namespace SignalRDemo
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

Now add SignalR Hub to serve the client.

namespace SignalRDemo
{
    public class SignalRHub : Hub
    {
        public static void SendNotifications()
        {
            // todo: after hub started by client
        }
    }
}

Now add SignalR script on client page where we want live interaction.

<script src="/Scripts/jquery.signalR-2.0.2.js"></script>
    <script src="~/signalr/hubs"></script>

    <script type="text/javascript">

        $(function () {       
            var hub = $.connection.signalRHub;
            hub.client.sendNotifications = function (message) {
                // todo: client
            };

            $.connection.hub.start({ transport: 'auto' }, function () {
            });
        });
    </script>

Get Power BI access token

To get Power BI access token by grand type password, use the bellow code

public async Task<OAuthResultDto> GetAccessTokenAsync()
{
	var oauthEndpoint = new Uri("https://login.microsoftonline.com/common/oauth2/token");

	using (var client = new HttpClient())
	{
		var result = await client.PostAsync(oauthEndpoint, new FormUrlEncodedContent(new[]
		{
			new KeyValuePair<string, string>("resource", "https://analysis.windows.net/powerbi/api"),
			new KeyValuePair<string, string>("client_id", "1638c1dd-xxxx-4444-xxxx-xxxx4444xxxx"),
			new KeyValuePair<string, string>("grant_type", "password"),
			new KeyValuePair<string, string>("username", "username"),
			new KeyValuePair<string, string>("password", "password"),
			new KeyValuePair<string, string>("scope", "openid")
		}));


		var content = await result.Content.ReadAsStringAsync();                
		var deserilized = JsonConvert.DeserializeObject<OAuthResult>(content);
		return deserilized;
	}
}

Details about above method:

oauthEndpoint : Authorization will happen here
resource: Resource URI
client_id: Client Id or Application Id, which can be obtain from Azure Active directory by creating an application.
grant_type: It is type of authentication
username: User name register with Power BI
password: User Password
scope: Scope

OAuthResult:
public class OAuthResult
{
	[JsonProperty("token_type")]
	public string TokenType { get; set; }
	[JsonProperty("scope")]
	public string Scope { get; set; }
	[JsonProperty("expires_in")]
	public int ExpiresIn { get; set; }
	[JsonProperty("ext_expires_in")]
	public int ExtExpiresIn { get; set; }
	[JsonProperty("expires_on")]
	public int ExpiresOn { get; set; }
	[JsonProperty("not_before")]
	public int NotBefore { get; set; }
	[JsonProperty("resource")]
	public string Resource { get; set; }
	[JsonProperty("access_token")]
	public string AccessToken { get; set; }
	[JsonProperty("refresh_token")]
	public string RefreshToken { get; set; }
	[JsonProperty("id_token")]
	public string TokenId { get; set; }
}

DOT NET Core 3 announced

It will support now Windows desktop application

* Windows Forms
* Windows Presentation Framework (WPF)
* Universal Windows Platform (UWP) XAML

Benefits of .NET Core for Desktop

* Performance improvements and other runtime updates
* Very easy to use and/or test
* Machine-global and application-local deployment
* .NET Core CLI tools and SDK-style projects

Preview could come in year-end 2018
And the final version in early 2019

For more details visit:

https://blogs.msdn.microsoft.com/dotnet/2018/05/07/net-core-3-and-support-for-windows-desktop-applications/


Other links:

https://blogs.msdn.microsoft.com/dotnet/2018/04/18/performance-improvements-in-net-core-2-1/

Simple string encryption or decryption

Here we will write code for encryption of any given input to the different character.


Example: if user input a it will convert to e next 4 charactor
if user enter z it will convert to d

Suppose if user input abcxyz it will be converted to efgbcd


Below code snippet will do the same

var userInput = ReadLine().ToLower();
char[] array = new char[userInput.Length];

for (int i = 0; i < userInput.Length; i++)
{
  var current = (int)userInput[i];
  //97(a) to 122(z)
  if (current > 96 && current < 119)
  {
	array[i] = (char)(current + 4);
  }
  else if (current > 118 && current < 123)
  {
	array[i] = (char)(current - 22);
  }
}
Console.WriteLine(array);

C# custom validation ValidationAttribute

Using the ValidationAttribute we can handle custom validation. It is available in namespace: System.ComponentModel.DataAnnotations Below is snippet for the same here age is being evaluated.

public class AgeValidator : ValidationAttribute
{
  public int Age { get; set; }

  public override bool IsValid(object value)
  {
    DateTime dob;
    if (value != null
       && DateTime.TryParse(value.ToString(), out dob))
    {
      if (dob.AddYears(Age) <= DateTime.Now)
      {
        return true;
      }
    }
    return false;
  }
}