C#, WPF, ASP.Net core | Api Versioning |Content Negotiation | Rate limiting |Middleware | Dependency injection | Routing | .Net core | Filters
Friday, May 10, 2019
C# Design Pattern : Decorator.
Decorator design Pattern allows you to change objects behavior/functionality at run time. in other words you can decorate it. for example you have a window (consider for a moment that window doesn't have border feature inbuilt) and we want to decorate it with border.one way we can create a derived class of Window and override it but important point to remember here is that, we have an object, we are decorating object at run time we don't/can't want to change it's template( i.e.class). below example will show you how to change object at run time without changing it's interface. (copy-paste below code to visual studio/code to see comments properly).
public interface IWindows
{
void Draw();
void Maximize();
void Minimize();
}
public class Windows : IWindows
{
public void Draw()
{
Console.WriteLine("Drawing Window ...");
}
public void Maximize()
{
Console.WriteLine("Windows Maximized");
}
public void Minimize()
{
Console.WriteLine("Windows Minimized");
}
}
class WindowsBorderDecorator : IWindows
{
// As you are implementing Iwindows interface so, you have to implement all of it's methods.
// but as you are getting Window Objects from client which has already implemented Iwindow,
//it means now you are free to use exsting implementation or you can override any method, as per your wish.
// As we want to draw border around window so we will override Draw() method.
private IWindows windowToDecorate;
public WindowsBorderDecorator(IWindows window)
{
windowToDecorate = window;
}
public void Draw()
{
// changing the drawing logic..now ,drawing window with border.
// it's our logic or situation weather we are able to use some functionality
//from existing window object ('windowToDecorate')
//or we want to write logic from scratech.
SetBorderAroundWindow();
Console.Write("Decorating window with Border!");
}
private void SetBorderAroundWindow()
{
//Additional logic as per your requirement;
}
public void Maximize()
{
windowToDecorate.Maximize();
}
public virtual void Minimize()
{
windowToDecorate.Minimize();
}
}
class DecoratorDesignPatternTest
{
public static void Main()
{
IWindows window = new Windows();
window.Draw();// actaul implementation. OUTPUT:Drawing Window ...
//--------------instead of above code you can use like below (Note: interface is same)---------
//want to decorate it with border.
IWindows decoratedWindow= new WindowsBorderDecorator(window);
decoratedWindow.Draw(); //new impelemetation with border. OUTPUT:Decorating window with Border!
Console.Read();
}
}
C# : Design Pattern : Different flavor of Singleton design pattern implementation
Below code is showing different implementation of Singleton design pattern for Example
Thread safe singleton implementation:
public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object locker = new object();
private Singleton()
{
}
public static Singleton GetInstance
{
get
{
if (instance == null) //double locking.
{
lock (locker)//each time it will lock weather object create is required or not.
//so to avoid unnecessary locking we will use double locking pattern
// means apply lock only when instance is null. we will check instance==null before locking.
{
if (instance == null)
{
instance = new Singleton();
return instance;
}
}
}
return instance;
}
/*
. other methods, properties of singleton class.
.
.
.
*/
}
}
Note : class is sealed because no one should be able to inherit it. locker object is static and readonly so only one instance object will be present which will be used for locking purpose.
we are checking instance ==null two times to avoid unnecessary locking, locking will be applicable only if instance is null.
Eager loading Singleton Pattern:
public sealed class SingletonEagerLoading
{
private static readonly SingletonEagerLoading instance = new SingletonEagerLoading();
int counter = 0;
private SingletonEagerLoading()
{
counter++;
Console.WriteLine("No of instance=" + counter);
}
public static SingletonEagerLoading GetInstance
{
get { return instance; }
}
/*
. other methods, properties of singleton class.
.
.
.
*/
}
// Note :No need to implement locking as we are creating instance at the time of declaration so framework will take care of instantiation and concurrency. (i.e. this implementation is Thread safe)
Lazy Loading Singleton Pattern :
public sealed class SingletonLazyLoading
{
private static readonly Lazy
int counter = 0;
private SingletonLazyLoading()
{
counter++;
Console.WriteLine("No of instance=" + counter);
}
public static SingletonLazyLoading GetInstance
{
get { return instance.Value; }
}
/* other methods, properties of singleton class.*/
public static void Main() //To Test
{
SingletonLazyLoading obj1 = SingletonLazyLoading.GetInstance;
SingletonLazyLoading obj2 = SingletonLazyLoading.GetInstance;
}
}
Thursday, May 9, 2019
SQL Server : Count no. of employees in each department
Count no. of employees in each department
SELECT DEPT_NAME,COUNT(EMP_ID)
FROM DEPARTMENT D LEFT JOIN EMPLOYEE E ON D.DEPT_ID=E.DEPARTMENT_ID
GROUP BY DEPT_NAME
SELECT DEPT_NAME,COUNT(EMP_ID)
FROM DEPARTMENT D LEFT JOIN EMPLOYEE E ON D.DEPT_ID=E.DEPARTMENT_ID
GROUP BY DEPT_NAME
C# : How to declare Async method in Interface
We can not declare Async method in interface or it's not needed as Async is code marker for compiler it has no relation with overriding feature. If we want to declare Async methods in Interface we need to set return type of method to Task/Task
C# : Can we return value from events?
Yes, we can return value from events but returned value will be available to the publisher of events.
Generally, publisher do not want any value from subscriber of event, he wants to notify subscriber, so the subscriber can perform appropriate action on the particular event. for example Button click, Button class is publisher of event and allowing subscriber to perform some action when button clicked. Yes, but if we will talk technically and tried to find out answer of question "can we return value from event so, answer will be yes. Please see below example :
namespace MyLibrary
{
///
/// This class will show us use of delegate.
///
public class ReturnValuefromEvent
{
public event LoopConditionChangingEvent LoopConditionChanging;
// This method will run loop till given condition by user and when i and conition are equal then it will ask to client, that still he wants to continue..."
// by generating events and event will return value to the publisher of event.
// hence conclusion is that event can return value back to the publisher.
public void RunLoop(int condition)
{
for (int i = 0; i <= condition; i++)
{
//here we are doing some operation like :
Console.Out.WriteLine("value of i=" + i);
if (i == condition && condition != 100)
// here we are checking if loop is reached to it's initial condition provided by user, we will ask to user are you still want to continue.
{ // and also we are setting maximum limit of loop i.e.100.
if (LoopConditionChanging != null)
{
if (LoopConditionChanging())//Callback--asking to client and if client will tell yes we will increment loop
{
condition = condition + 10;
}
}
}
}
}
}
}
user will subscribe "LoopConditionChangingEvent " which will return bool value (true or false) that publisher will use inside of loop and according to given value either loop will continue or terminated.
Friday, April 12, 2019
WPF: Style definition and use
WPF : Style Introduction :
Style are way to set common property of a control at one place to reuse it.
Style are similar to CSS classes in HTML/Web Applications.
We can declare Style at multiple places like :
Resource Section of Control or it's Parent.(Scope :Control it self and it's child can use this Style)
Resource Section of Window.(Scope =containing form only)
Inside of Resource Dictionary.(Scope = Application level).
Below are some common attributes of Style:
TargetType :if we are setting only TargetType then Style will be application to all controls mention as Target type in applicableScope.
x:Key : used to declare a key, if we declare a Key then style will not be applied on controls automatically, we need to set explicitly.
BasedOn : used to create a new Style by inheriting from an existing Style.
Note : Control level Properties have higher precedence than Style. i.e. if you have applied style which is setting background color of control and you also have set background color at Control level, Color set at control will be applicable and system will ignore color what you mentioned in Style.
Subscribe to:
Posts (Atom)
C# Record type: Something to remember while using record types
Record in c# provide a concise and expressive way to create immutable data types, record is a keyword in c#, we can use this keyword with ...
-
Asynchronous programming makes it possible to run multiple operation concurrently, In other words Asynchronously. Dot Net framework 4.0 s...
-
Stack implementation in C# public class Stack { readonly int _capacity; int top; int[] _stack ; ...
-
Please read "Asynchronous programming using Async and Await" before reading it. Asynchronous method with multiple await : cl...



