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