Friday 27 December 2019

ternary operator in C#

 this is a ? : Ternary Operator
it is return one of two values depending on Boolean condition 
Syntax:
condition ? expressionIfTrue : expressionIfFalse;
Example:
string name = "hamid";
Console.WriteLine(name == "hamid" ? "The name is hamid" : "The name is not hamid");

so it will return : The name is hamid

Console.WriteLine(name == "hamidXYZ" ? "The name is hamid" : "The name is not hamid");
so it will return : The name is not hamid

How To Implement NLog In WebAPI

I have created my blog here please view for full details in step by step

https://www.c-sharpcorner.com/article/how-to-implement-nlog-in-webapi/

How To Create EXE For .Net Core Console Application

I have created my blog here please view for full details in step by step

https://www.c-sharpcorner.com/article/how-to-create-exe-for-net-cor/

class vs structure


class
1- Class is a reference types.
2- Class uses new keyword for instance.
3- reference type is stored in heap memory.
4- Class can have constructor or destructor.

Struct
1- it is value type
2- it is not using new keyword
3- value type stored in stack memory
4- it do not have constructor or destructor

create your console application in C#

difference between String and string in C#?

1- technically, there is no difference.
2- string is an alias for System.String
3- others alias are as follows
   object:  System.Object
string:  System.String
bool:    System.Boolean
byte:    System.Byte
sbyte:   System.SByte
short:   System.Int16
ushort:  System.UInt16
int:     System.Int32
uint:    System.UInt32
long:    System.Int64
ulong:   System.UInt64
float:   System.Single
double:  System.Double
decimal: System.Decimal
char:    System.Char

top 10 commands in .net core cli

1-dotnet new console -o test
  it will create a console project in the directory test
2- dotnet restore
3- dotnet build
4- dotnet run
5- dotnet test
6- dotnet pack
7- dotnet clean
8- dotnet sln
9- dotnet add/remove reference
10-dotnet add/remove package

Wednesday 29 May 2019

how to add swagger in aspnetcore

follow the steps

type in searchbox : swashbuckle.aspnetcore
add this dll

now go to startup.cs file and add the code in ConfigureServices methosd

 public void ConfigureServices(IServiceCollection services)
        {
         
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "Employees Api", Version = "v1" });
            }
                );
           
        }

then in last inside the configure method write line of code
app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Employee Api V1");
            }
                );

then finally run your app

and type just like:
http://localhost:60855/swagger/

how to use inmemory database in aspdotnet core

Please follow the bellow steps
Step 1 -> Create your class and db context in model
 public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    }
    public class EmployeeContext : DbContext
    {
        public EmployeeContext(DbContextOptions<EmployeeContext> dbContextOptions):base(dbContextOptions)
        {           
        }
        public DbSet<Employee> Employees { get; set; }
    }

Step2 -> In startup class add line of code in ConfigureServices method
  public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<EmployeeContext>(dbc => dbc.UseInMemoryDatabase("EmpList"));
        }

step3->add your controller and then add line of code to get all data

 [Produces("application/json")]
    [Route("api/Employee")]
    public class EmployeeController : Controller
    {
        private EmployeeContext _employeeContext;
        public EmployeeController(EmployeeContext employeeContext)
        {
            _employeeContext = employeeContext;
            if (_employeeContext.Employees.Count()==0)
            {
                _employeeContext.Employees.AddRange( new Employee { Name = "emp1" }, new Employee { Name = "emp2" });
                _employeeContext.SaveChanges();
            }
        }
        [HttpGet]
        public IEnumerable<Employee> GetAll()
        {
            return _employeeContext.Employees.AsNoTracking().ToList();
        }
    }

Wednesday 3 April 2019

create react js project step by step

1- install node js
2- install > npm install -g create-react-app
3- create project > create-react-app react_test
[Note App name is not allowed in capital letters]
4- change dir cd <your project name>
5- npm start

Wednesday 27 March 2019

add style in angular2 using method

isBold: boolean = false;
  fontSize: number = 40;
  isItalic: boolean = true;

  addCustomStyles() {
      let styles = {
'font-weight': this.isBold ? 'bold' : 'normal',
          'font-style': this.isItalic ? 'italic' : 'normal',
          'font-size.px': this.fontSize
      };

      return styles;
  }

<button style='color:black' [ngStyle]="addCustomStyles()">Test Button</button>

abstract factory in c# good example

Tuesday 26 March 2019

read resource file by culture in C#

 Console.WriteLine(ClassLibResource.Resource.ResourceManager.GetString("key1", new System.Globalization.CultureInfo("ja-jp")));

redirect from action filter to another action method in mvc


Step1: create your action attribute

public class RedirectCustomFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
             // // Way-1
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "About" }));
            //filterContext.Result.ExecuteResult(filterContext.Controller.ControllerContext);

            //// Way-2
            //var controller = (HomeController)filterContext.Controller;
            //filterContext.Result = controller.RedirectToAction("about", "home");

            ////base.OnActionExecuting(filterContext);
        }


Not If you wat to go with Way-2 then you need to create a method inside your controller

  public class HomeController : Controller
    {
        public new RedirectToRouteResult RedirectToAction(string action, string controller)
        {
            return base.RedirectToAction(action, controller);
        }
        [RedirectCustomFilter]
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";
            return View();
        }

Wednesday 20 March 2019

Await in Catch and Finally blocks

Await in Catch and Finally blocks is a part of C# 6.0

 public static async Task<string> Test()
        {
            await logMethodEntrance();
            var client = new System.Net.Http.HttpClient();
            var streamTask = client.GetStringAsync("https://localHost:1234");
            try
            {
                var responseText = await streamTask;
                return responseText;
            }
            catch (System.Net.Http.HttpRequestException e) when (e.Message.Contains("401"))
            {
                await logError("test your accessbility", e);
                return "not applicable";
            }
            finally
            {
                await logMethodExit();
                client.Dispose();
            }
        }
        private static Task logError(string v, HttpRequestException e)
        {
            throw new NotImplementedException();
        }
        private static Task logMethodExit()
        {
            throw new NotImplementedException();
        }
        private static Task logMethodEntrance()
        {
            throw new NotImplementedException();
        }

Monday 18 March 2019

Helpful URL for study

https://docs.microsoft.com/en-us/visualstudio/profiling/profiling-feature-tour?view=vs-2017

https://docs.microsoft.com/en-us/visualstudio/profiling/profiling-feature-tour?view=vs-2017

https://www.c-sharpcorner.com/article/deply-of-a-angular-application-on-iis/


// Generic concept

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/





https://signalrchat20190307055019.azurewebsites.net/



https://docs.microsoft.com/en-us/aspnet/core/tutorials/razor-pages/razor-pages-start?view=aspnetcore-2.2&tabs=visual-studio




https://docs.microsoft.com/en-us/learn/modules/host-a-web-app-with-azure-app-service/



https://www.c-sharpcorner.com/article/deploy-asp-net-mvc-application-to-windows-azure/



https://www.codeproject.com/Tips/1044950/How-to-Publish-ASP-NET-MVC-Web-Application-to-Azur



https://www.aspsnippets.com/Articles/ASPNet-MVC-Send-user-Confirmation-email-after-Registration-with-Activation-Link.aspx



http://www.dotnetawesome.com/2017/04/complete-login-registration-system-asp-mvc.html



https://docs.microsoft.com/en-us/aspnet/identity/overview/features-api/account-confirmation-and-password-recovery-with-aspnet-identity







Note: Clinic Management System

https://www.c-sharpcorner.com/article/clinic-management-project-using-asp-net-mvc-5/



run : enable-migrations
add-migration "InitialDb"
update-database





https://docs.microsoft.com/en-us/aspnet/aspnet/overview/developing-apps-with-windows-azure/building-real-world-cloud-apps-with-windows-azure/web-development-best-practices#async

https://www.c-sharpcorner.com/UploadFile/4d9083/project-gymone-demo-project-in-mvc/



http://bitoftech.net/2014/06/09/angularjs-token-authentication-using-asp-net-web-api-2-owin-asp-net-identity/



http://bitoftech.net/2014/08/11/asp-net-web-api-2-external-logins-social-logins-facebook-google-angularjs-app/



https://docs.microsoft.com/en-us/aspnet/signalr/overview/getting-started/real-time-web-applications-with-signalr



https://www.dotnetcurry.com/angularjs/1062/website-using-angularjs-aspnet-webapi

https://github.com/aspnet/Docs/tree/master/aspnetcore/data/ef-mvc/intro/samples/cu-final

https://docs.microsoft.com/en-us/azure/app-service/app-service-web-get-started-dotnet

https://github.com/Vimal123/Angular5DemoAdmin



https://www.codeproject.com/articles/36511/task-management-system

Thursday 14 March 2019

custom exception on your business logic layer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Utilities.ExceptionHandler
{
    public class CustomRule
    {
        [JsonConstructor]
        public CustomRule(string name, string description)
        {
            Name = name;
            Description = description;
            ErrorCategory = CustomRuleEnum.Validation.ToStringValue();
        }

        public CustomRule(string errorCategory, string name, string description)
        {
            ErrorCategory = errorCategory;
            Name = name;
            Description = description;
        }



        public string ErrorCategory { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }


    public enum CustomRuleEnum
    {
        [StringValue("General")]
        General,

        // Use this for pre-processing checks; e.g. before any database activity
        [StringValue("Validation")]
        Validation,

        // Use this for any post checks cause from a data related issue after trying to process a request
        [StringValue("Data")]
        Data
    }

    public class StringValueAttribute : Attribute
    {
        public StringValueAttribute(string value)
        {
            Value = value;
        }

        public string Value { get; protected set; }
    }


   public static class ExtensionHelper
    {
        /// <summary>
        ///     https://cisart.wordpress.com/2013/09/11/string-value-attribute-for-enums/
        ///     Example Enum to String:
        ///     TestEnum test = TestEnum.Value2;
        ///     string str = test.ToStringValue();
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToStringValue(this Enum value)
        {
            var attributes =
                (StringValueAttribute[])
                    value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(StringValueAttribute), false);
            return ((attributes.Length > 0)) ? attributes[0].Value : value.ToString();
        }
    }

    public class CustomValidationException : System.Exception
    {
        public IEnumerable<CustomRule> CustomRules;

        public CustomValidationException(string message, IEnumerable<CustomRule> customRules)
                : base(message)
        {
            CustomRules = customRules;
        }

        public CustomValidationException(string message)
            : base(message)
        {
        }

        public CustomValidationException(string message, System.Exception inner)
            : base(message, inner)
        {
        }
    }
}

// apply on class

public bool IsValid()
        {
            return !CustomRules().Any();
        }

        public IEnumerable<CustomRule> CustomRules()
        {
            if (string.IsNullOrWhiteSpace(Name))
                yield return new CustomRule("MissingName", "Test name is required.");

        }

// apply on service method
 // validation
                if (!dbTest.IsValid())
                    throw new CustomValidationException("Validation Error", dbTest.CustomRules());



Wednesday 13 March 2019

string format in C#

 public string GetDetails()
        {
            return string.Format("{0} - {1} - {2}", Name, Role, PreferredLanguage, Projects);
        }

public string GetDetails()
{
    return ($"The value of  ({Name},{Role}) and ({PreferredLanguage},{Projects})");
}

Sigleton without lock but follow thread safe in C#

 /// <summary>
    /// Sigleton without lock but follow thread safe
    /// </summary>
    public class SingletonWTLock
    {
        private static readonly Lazy<SingletonWTLock> _mySingleton = new Lazy<SingletonWTLock>(() => new SingletonWTLock());
        private SingletonWTLock() { }
        public static SingletonWTLock Instance
        {
            get
            {
                return _mySingleton.Value;
            }
        }
    }

Tuesday 12 March 2019

null check in angular2

import { Injectable } from '@angular/core';
@Injectable()
export class Common {
    constructor() { }
    IsEmpty(str: string): boolean {
        return str === undefined || str === null || str === '';
    }
}

// Implementation:
var val="abc";
if (this.common.IsEmpty(val)) { return; }

factory method design pattern in C#

 public class FactoryTest
    {
        public static void Test()
        {
            AbstractFactory factory = new ConcreteVehicleFactory();
            IFactory scooter = factory.GetType("a");
            scooter.Do();
            IFactory bike = factory.GetType("Bike");
            bike.Do();
            Console.ReadKey();
        }
    }

    public interface IFactory
    {
        void Do();
    }
    /// <summary>
    /// A 'ConcreteProduct' class
    /// </summary>
    public class Scooter : IFactory
    {
        public void Do()
        {
            Console.WriteLine("Drive the Scooter : ");
        }
    }
    /// <summary>
    /// A 'ConcreteProduct' class
    /// </summary>
    public class Bike : IFactory
    {
        public void Do()
        {
            Console.WriteLine("Drive the Bike : ");
        }
    }
    /// <summary>
    /// The Creator Abstract Class
    /// </summary>
    public abstract class AbstractFactory
    {
        public abstract IFactory GetType(string type);
    }
    /// <summary>
    /// A 'ConcreteCreator' class
    /// </summary>
    public class ConcreteVehicleFactory : AbstractFactory
    {
        public override IFactory GetType(string type)
        {
            switch (type)
            {
                case "A":
                    return new Scooter();
                case "B":
                    return new Bike();
                default:
                    throw new ApplicationException(string.Format("cannot be created", type));
            }
        }
    }

signleton in C#

 public class SingleTonTest
    {
        public static void Test()
        {
            MySingleton.Instance.DO();
            MySingleton.Instance.DO();
        }
    }
    public class MySingleton
    {
        private static MySingleton instance = null;
        static MySingleton()
        {
            Console.WriteLine("Static Constructor called");
        }
        private MySingleton()
        {
            Console.Write("Private conatructor called");
          
        }
        // Lock synchronization object
        private static object myLock = new object();
        public static MySingleton Instance
        {
            get
            {
                lock (myLock)
                {
                    if (instance == null)
                        instance = new MySingleton();
                    return instance;
                }
            }
        }
        public void DO()
        {
            Console.WriteLine("Do your work");
        }
    }

hashtable and dictionary

public class HashTableAndDictionary
    {
       IList<string> strIList = new List<string>();
        List<int> intList = new List<int>();
        public static void Test()
        {
           
            HashTableTest();
            Dictionarytest();
        }
        public static Hashtable GetHashtable()
        {
          
            // Create and return new Hashtable.
            Hashtable hashtable = new Hashtable();
            hashtable.Add("a", 1);
            hashtable.Add("b", 2);
            return hashtable;
        }
        public static void HashTableTest()
        {
            var hashObject = GetHashtable();
            try
            {
                var s1 = hashObject["a"];
                var s2 = hashObject["c"];
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public static void Dictionarytest()
        {
            Dictionary<string, int> d = new Dictionary<string, int>()
               {
                        {"a", 2},
                        { "b", 1}
                };
            // Loop over pairs with foreach
            foreach (KeyValuePair<string, int> pair in d)
            {
                Console.WriteLine("{0}, {1}", pair.Key, pair.Value);
            }
            try
            {
                var s1 = d["a"];
                var s2 = d["c"];
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }

Sunday 10 March 2019

2019 interview question

Cross Apply vs Cross Join
Merge query in sql
Group by query in sql
How to optimize stored procedure
One to One Relationship in sql
Normalization and what is 3rd NF
ACID Property
default exceptio  in webapi
MVC routing vs Webapi routing
Group by query in linq
Singleton
Factory method
Strategy Pattern
Abstract Factory
Prototype
Adapter
Webapi return types
IActionResutl vs HttpResponseMessage
IEnumerable Vs Iquarable
throw vs throw exception
Abstract vs Interface
Dictionary vs Concurant Dictionary
Solid Principle
DI and its trype
Unit test (NUnit and Moq)
Token based authentication vs UserName/Password
static constructor
Static class and method

Saturday 26 January 2019

how to return last month records from huge data row

DECLARE @StartDate DATETIME, @EndDate DATETIME   
SET @StartDate = DATEADD(mm, DATEDIFF(mm, 0, getdate()) - 1, 0)   
SET @EndDate = DATEADD(dd, -1, DATEADD(mm, 1, @StartDate))

SELECT @StartDate,@EndDate
SELECT Name FROM Employee WHERE date_created BETWEEN @StartDate AND @EndDate