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.

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; }
}

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);

Normalization

1st normal form

Remove duplicate data and break data at a granular level, as if a column has cities files: it should be brake into the different column or should maintain the different table

2nd normal form

All column data should  depend on full primary key and not part of key

3rd normal form

No column should depend on other columns and it shouldn’t have calculated values

JavaScript object and prototype

JavaScript Object and prototype:

These two different codes will produce the same output

var cat = {name: 'Fluffy'}

var cat = Object.create(Object.prototype, { 
 name: { 
  value: "Fluffy", 
  enumerable: true, 
  writable: true, 
  configurable: true
 }
});

Follow the below code to get the same output, and the same can be configured


Object.getOwnPropertyDescriptor(cat, 'name')

Object.defineProperty(cat, 'name', {writable: false})
Object.defineProperty(cat, 'name', {enumerable: false})

Object.keys(cat)

Object.defineProperty(cat, 'fullName', 
{
 get: function () { return this.name.first + ' ' + this.name.last},
 set: function () {
  var nameParts = values.split(' ');
  this.name.first = nameParts[0];
  this.name.last = nameParts[1];
 }
})

var arr = ['aa', 'bb']
Object.defineProperty(arr, 'last', { get: function () {return this[this.lenght-1]}})

Object.defineProperty(Array.prototype, 'last', { get: function () {return this[this.lenght-1]}})

var last = arr.last

---
function Cat (name, color)  {
 this.name = name;
 this.color = color
}

var fluffy = new Cat('fluffy', 'white')
Cat.prototype
fluffy.__proto__

var muffine = new Cat('Muffin', 'Brown')
muffine.__proto__

fluffy.age = 5
fluffy.age
fluffy.__proto__.age

Object.keys(fluffy)
fluffy.hadOwnProperty('age')
fluffy.hadOwnProperty('color')