Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Delegates and their flavours

0

Category :

Delegate Types

A delegate is simply a reference to a method. Delegates can be stored and passed around in a variable, and hence they must have a type definition:
private delegate int FuncTwoInts(int one, int two);

The line above defines the type FuncTwoInts. The FuncTwoInts type is a reference to a method that takes two int parameters and returns a single int result.

Delegate expressions

The FuncTwoInts type can be used to declare variables like this:
private static int Add(int one, int two)
{
    return one + two;
}

private FuncTwoInts theFunc = Add;
Or like this:
FuncTwoInts theFunc = delegate (int one, int two)
{
    return one + two;
};
Or this:
FuncTwoInts theFunc = (one, two) =>
{
    return one + two;
};
Or even like this:
FuncTwoInts theFunc = (one, two) => one + two;

Lambda expressions

The last two delegate examples above (the ones utilizing the => operator) are called lambda expressions. Lambda expressions are just a more efficient way of defining a delegate. If the function defined by the lambda expression is more than a single line, then the { } are required, as is the return keyword.

Built-in delegate types

There is a family of built-in delegate types that can be used to declare delegate variables without the need to define a custom type.

Action

The types that represent a delegate without a return value (void return) are the Action types in the System namespace.
private Action supFunction = () => Console.WriteLine("Sup?!");
Here's an example of a delegate that takes three parameters of different types:
private Action<string, int, bool> printThreeValues =
    (s, i, b) => Console.WriteLine($"string: {s}, int: {i}, bool: {b}");

Func

The Func family of delegate types can return a value of any type you wish. For example: Func<TResult> for no params and TResult return type.
private Func twoPlusThree = () => 2 + 3;
Func<T1, T2, TResult> for two parameters and TResult return type. Here is an example of a delegate declaration that takes two string parameters and returns an int:
private Func<string, string, int> sumCharacters = 
    (s1, s2) => s1.Length + s2.Length;


my thanks to this course:
https://www.codingame.com/playgrounds/345/c-linq-background-topics/review

Factory Method

0

Category : ,

The Factory completely hides/removes the process of creating objects from the client/caller.

Example

Lets say we have an eCommerce application and we have 2 payment gateways integrated with our application. Lets call these payment gateways BankOne and BankTwo.

Interface

We need a "Payment Gateway" interface to set the template/functionality that all payment gateways need to provide.

interface IPaymentGateway
{
    void MakePayment(Product product);        
}

Concrete implementations

Concrete implementations of Payment Gateways required:
public class BankOne : IPaymentGateway
{
    public void MakePayment(Product product)
    {
        // The bank specific API call to make the payment
        Console.WriteLine("Using bank1 to pay for {0}, amount {1}", product.Name, product.Price);
    }
}

public class BankTwo : IPaymentGateway
{
    public void MakePayment(Product product)
    {
        // The bank specific API call to make the payment
        Console.WriteLine("Using bank2 to pay for {0}, amount {1}", product.Name, product.Price);
    }
}
To be able to identify what payment mechanism has been selected, lets define a simple Enum PaymentMethod.
enum PaymentMethod
{
    BANK_ONE,
    BANK_TWO
}

Factory

Factory class to handle all the details of creating these objects.
public class PaymentGatewayFactory
{
    public virtual IPaymentGateway CreatePaymentGateway(PaymentMethod method, Product product)
    {
        IPaymentGateway gateway = null;

        switch(method)
        {
            case PaymentMethod.BANK_ONE:
                gateway = new BankOne();
                break;
            case PaymentMethod.BANK_TWO:
                gateway = new BankTwo();
                break;
        }

        return gateway;
    }
}
Our factory class accepts the selected payment gateway and then based on the selection it is creating the concrete payment gateway class. We have effectively abstracted out all these details from the client code. Otherwise every class that want to use a payment gateway would have to write all this logic.

Usage

Lets now look at how the client class can use this factory method to make the payment.
public class PaymentProcessor
{
    IPaymentGateway gateway = null;

    public void MakePayment(PaymentMethod method, Product product)
    {
        PaymentGatewayFactory factory = new PaymentGatewayFactory();
        this.gateway = factory.CreatePaymentGateway(method, product);

        this.gateway.MakePayment(product);
    }
}
Now our client class does not depend on the concrete payment gateway classes. It also does not have to worry about the creation logic of the concrete payment gateway classes. All this is nicely abstracted out in the factory class itself.


my thanks to the following article:
https://www.codeproject.com/Articles/874246/Understanding-and-Implementing-Factory-Pattern-i

Fluent Migrator

0

Category :

Fluent Migrator is a migration framework for .NET much like Ruby on Rails Migrations. Migrations are a structured way to alter your database schema and are an alternative to creating lots of sql scripts that have to be run manually by every developer involved. Migrations solve the problem of evolving a database schema for multiple databases (for example, the developer’s local database, the test database and the production database). Database schema changes are described in classes written in C# that can be checked into a version control system.
Gettings Started

Getting Started

Create a new Visual Studio library project for your migrations.

Migration

[Migration(1)]
public class CreateUserTable : Migration
{
    public override void Up()
    {
        Create.Table("Users")
                             .WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity()
                             .WithColumn("Name").AsString(255).NotNullable().WithDefaultValue("Anonymous");
    }

    public override void Down()
    {
        Delete.Table("Users");
    }
}

Execute Migration

Find Migrate.exe file and run command from same directory
migrate.exe /conn "data source=(local);Trusted_Connection=yes;database=FluentMigrator_TestDB" --provider sqlserver2008 --assembly "../../../Guides.FluentMigrator/bin/Debug
/Guides.FluentMigrator.dll" --task migrate  --output -- outputFilename migrated.sql
I installed FluentMigrator using Nuget so i had to navigate to the "packages\FluentMigrator.x.x.x\tools" directory and run the above command from there.
I think this exe can also be found in the "Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Entity Framework Tools\NuGet Packages\EntityFramework.x.x.x\tools" directory.

Bat file to Execute Migration

Migrate Up
cd C:\sandbox\Guides.FluentMigrator\packages\FluentMigrator.1.6.2\tools

migrate.exe /conn "data source=(local);Trusted_Connection=yes;database=FluentMigrator_TestDB" --provider sqlserver2008 --assembly "../../../Guides.FluentMigrator/bin/Debug/Guides.FluentMigrator.dll" --task migrate:up  --output -- outputFilename migrated.sql

pause

Upgrade Database using SQL Scripts

create a separate folder in your project, name it like “Scripts” and put your SQL Script there.
Then, create another migration class, name it “M0002_CreateSP_GetAllMember.cs” and paste the following code in that class file:
using FluentMigrator;
namespace DatabaseMigration.Migrations
{
    [Migration(2)]
    public class M0002_CreateSP_GetAllMember : Migration
    {
        public override void Up()
        {
            Execute.EmbeddedScript("CreateSP_GetAllMember.sql");
        }

        public override void Down()
        {
            Execute.EmbeddedScript("DropSP_GetAllMember.sql");
        }
    }
}
NOTE: Don’t forget to set the Build Action property of both SQL files as Embedded Resource.


my thanks to:
https://github.com/schambers/fluentmigrator/wiki
http://www.codeproject.com/Articles/1012802/Fluent-Migrator-for-Database-Migration

C# Delegates, Anonymous Methods, and Lambda Expressions

0

Category :

C# Delegates, Anonymous Methods, and Lambda Expressions.

Delegates

Pointer to a function.
A way to pass methods the same way you pass values and objects around
 
delegate int DiscountDelegate(); 
 
Just like a class, however, it isn't very useful until we create an instance of it.

Remember that a delegate is nothing more then a reference to a method.

Even though DiscountDelegate does not have any constructors, when creating one, there is an implicit constructor that wants a method matching its signature (no params, returning int).

Type in the name in the same way you would call the method; all you do is omit the parentheses.

Another way to think of a delegate is that it defers the execution of a method.

} 

Func

Later, in 3.5, they were nice enough to give us some common delegates to use so we wouldn't have to constantly define our own. They expanded Action and added Func, and the only difference between them is that Func matches methods that return a value and Action matches ones that do not.

This means that we do not need to declare our DiscountDelegate and instead can use Func in its place.

Our delegate's signature now becomes Func. Notice the Calculate method now takes a boolean parameter and that we call discount() using a boolean.

class Program 
{ 
    static void Main(string[] args) 
    { 
        new ShoppingCart().Process(new Func(Calculator.Calculate)); 
    } 
} 
 
class Calculator 
{ 
    public static int Calculate(bool special) 
    { 
        int discount = 0; 
        if (DateTime.Now.Hour < 12) 
        { 
            discount = 5; 
        } 
        else if (DateTime.Now.Hour < 20) 
        { 
            discount = 10; 
        } 
        else if (special) 
        { 
            discount = 20; 
        } 
        else 
        { 
            discount = 15; 
        } 
        return discount; 
    } 
} 
 
class ShoppingCart 
{ 
    public void Process(Func discount) 
    { 
        int magicDiscount = discount(false); 
        int magicDiscount2 = discount(true); 
    } 
}
Type inference allows us to completely omit the explicit creation of Func as long as the method we pass has the proper signature of the expected delegate.
eliminating the need to even explicitly create a Func delegate

// works because Process expects a method that takes a bool and returns int 
new ShoppingCart().Process(Calculator.Calculate); 

Anonymous methods

Anonymous methods let you declare a method body without giving it a name.
Anonymous methods can only be created when using delegates and, in fact, they are created using the delegate keyword.

new ShoppingCart().Process( 
        new Func(delegate(bool x) { return x ? 10 : 5; } 
    )); 

You can put as much or as little logic between the curly braces as you would in any other method.

there is even more trimming we can do. Naturally, we can omit the need to explicitly declare the Func delegate; .NET takes care of that for us when we use the delegate keyword.

new ShoppingCart().Process( 
      delegate(bool x) { return x ? 10 : 5; } 
    );  

The true power of anonymous methods can be seen when using .NET methods that expect delegates as parameters and when responding to events. Previously, you had to create a method for every possible action you wanted to take. Now you can just create them inline and avoid polluting your namespace.

// creates an anonymous comparer 
custs.Sort(delegate(Customer c1, Customer c2) 
{ 
    return Comparer.Default.Compare(c1.ID, c2.ID); 
}); 
 
// creates an anonymous event handler 
button1.Click += delegate(object o, EventArgs e) 
                      { MessageBox.Show("Click!"); }; 

Lambda expressions

From MSDN: 'A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.'

lambda expressions replace anonymous methods and add many features.

Looking back at our last example, we had trimmed the code down to where we were basically creating the entire discount algorithm in a single line.
new ShoppingCart().Process( 
        new Func(delegate(bool x) { return x ? 10 : 5; } 
    )); 

Lambda expressions use the 'goes to' operator => to indicate what parameters are being passed to the expression.
The compiler takes this a step further, and allows us to omit the types and infers them for us.
If you have two or more parameters, you need to use parentheses: (x,y) =>. If you only have one, however, you don’t need them: x =>.
static void Main(string[] args) 
{ 
    Func del = x => x ? 10 : 5; 
    new ShoppingCart().Process(del); 
} 
// even shorter... 
static void Main(string[] args) 
{ 
    new ShoppingCart().Process(x => x ? 10 : 5); 
} 

Yep, that's it. The boolean type of x is inferred and so is the return type, because Process takes a Func. If we want to implement the full code block like we had before, all we need to do is add the braces.

static void Main(string[] args) 
{ 
    new ShoppingCart().Process( 
    x => { 
        int discount = 0; 
        if (DateTime.Now.Hour < 12) 
        { 
            discount = 5; 
        } 
        else if (DateTime.Now.Hour < 20) 
        { 
            discount = 10; 
        } 
        else if(x) 
        { 
            discount = 20; 
        } 
        else 
        { 
             discount = 15; 
        } 
        return discount; 
    }); 
} 

One last thing…

There is an important difference between using braces and not using them. When you use them, you are creating a 'statement lambda', otherwise it is 'expression lambda'. Statement lambdas can execute multiple statements (hence the need for braces) and can not create expression trees. You will probably only run into this problem when working with the IQueryable interface. The example below shows the problem.

Statement Lambda use curly braces and can execute multiple statements (hence the need for braces) and can not create expression trees.
List list = new List(); 
IQueryable query = list.AsQueryable(); 
list.Add("one"); 
list.Add("two"); 
list.Add("three"); 
 
string foo = list.First(x => x.EndsWith("o")); 
string bar = query.First(x => x.EndsWith("o")); 
// foo and bar are now both 'two' as expected 
foo = list.First(x => { return x.EndsWith("e"); }); //no error 
bar = query.First(x => { return x.EndsWith("e"); }); //error 
bar = query.First((Func)(x => { return x.EndsWith("e"); })); //no error 
The second assignment of bar fails at compile time. This is because IQueryable.First expects an expression as a parameter whereas the extension method List.First expects a delegate. You can force the lambda to evaluate to a delegate (and use the First's method overload) by making a cast as I did in the third assignment to bar.

It's hard to end the discussion here, but I feel I must. Lambdas are basically broken into two categories; the kind that create anonymous methods and delegates, and the kind that create expressions. Expressions are an article by themselves and are not necessarily required knowledge to be a .NET developer (although their implementation in LINQ certainly is).

Informative graphic showing different parts of LINQ query




my thanks to:
http://www.codeproject.com/Articles/47887/C-Delegates-Anonymous-Methods-and-Lambda-Expressio
http://www.codeproject.com/Articles/19154/Understanding-LINQ-C

Decorator Design Pattern Intro

0

Category : , ,

Decorator Design pattern allows developer to satisfy some SOLID rules:

  • 1) Single Responsibility Principle – Class/Function should do only one task or Class/Function should have only one reason to change.
  • 2) Open Close Principle – Class/Function is open for extension but close for modification.
  • 3) Liskov Substitution type – If type S is derived from Type T then object of Type T can be replaced by object of Type S.


Simple Example of Design Pattern

namespace BasicDecoratorPattern
{
    public class Client
    {
        public Client()
        {
            IBaseService realTimeService = new BasicServiceImplementaion();

            IBaseService basicRealTimeServiceDecorator1 = new Decorator1OnBasic(realTimeService);
            IBaseService basicRealTimeServiceDecorator2 = new Decorator2OnBasic(realTimeService);

            basicRealTimeServiceDecorator1.Print();
            basicRealTimeServiceDecorator2.Print();
        }
    }

    public interface IBaseService
    {
        void Print();
    }

    public class BasicServiceImplementaion : IBaseService
    {
        public void Print()
        {
            Console.WriteLine("Basic Item");
        }
    }

    public class Decorator1OnBasic : IBaseService
    {
        private readonly IBaseService BasicRealTimeService;
        public Decorator1OnBasic(IBaseService service)
        {
            BasicRealTimeService = service;
        }

        public void Print()
        {
            BasicRealTimeService.Print();
            Console.WriteLine("Extra functionality from Decorator ONE");
        }
    }

    public class Decorator2OnBasic : IBaseService
    {
        private readonly IBaseService BasicRealTimeService;
        public Decorator2OnBasic(IBaseService service)
        {
            BasicRealTimeService = service;
        }

        public void Print()
        {
            BasicRealTimeService.Print();
            Console.WriteLine("Extra functionality from Decorator SECOND");
        }
    }
}




my thanks to: http://www.codeproject.com/Articles/872818/How-and-Where-Decorator-Design-Pattern

C# 6.0 features

0

Category :

Primary Constructor

When declaring a primary constructor all other constructors must call the primary constructor using :this().
class Person(string name, int age)
{
    private string _name = name;
    private int _age = age;
 
    private string _address;
 
    public Person(string name, int age, string address) : this(name, age)
    {
         _address = address;
    }
 
    public void Speak()
    {
        Console.WriteLine("Hi, my name is {0} and I am {1} years old", _name, _age);
    }
}

Auto-properties

class Person(string name, int age)
{
    public string Name { get; set; } = name;
    public string Name1 { get; } = name;
}

Dictionary initializer

When using dictionaries, sometimes you want to initialize them with values just as you can do with arrays and lists.
You will see in the following code sample that these new initializers even work with instance variables.
class Person(string name)
{
    private Dictionary _data = new Dictionary {["Name"] = name };

    Dictionary newWay = new Dictionary()
            {
                // Look at this!
                ["Afghanistan"] = "Kabul",
                ["Iran"] = "Tehran",
                ["India"] = "Delhi"
            };
}
It will of course also work with the auto-property initializers
class Person(string name, int age)
{
         
    public Dictionary Data { get; } = new Dictionary {["Name"] = name };
}

Declaration expressions

With the out keyword you would have to declare a variable for the result before calling the actual method.
int age;
CalculateAgeBasedOn(1987, out age);
We no longer have to do that
CalculateAgeBasedOn(1987, out var age);

Using await in a catch or finally block

Consider logging for instance. You may want to write a file log when you catch an error but not hold up the caller for too long. In this scenario, it would be great to have the ability to await an asynchronous call inside the catch block.
Equally when talking about the finally block, we may want to clean up some resources or do something particular inside the finally block that invokes an asynchronous API. As seen in the following code sample, this is now allowed.
public async Task DownloadAsync()
{
    try
    {}
    catch
    {
        await Task.Delay(2000);
    }
    finally
    {
        await Task.Delay(2000);
    }
}

Filtering Exceptions with Exception Filters

try
{
    throw new CustomException { Severity = 100 };
}
catch (CustomException ex) if (ex.Severity > 50)
{
    Console.WriteLine("*BING BING* WARNING *BING BING*");
}
catch (CustomException ex) // to catch all other exceptions
{
    Console.WriteLine("Whooops!");
}
my thanks to: http://www.codeproject.com/Articles/808732/Briefly-exploring-Csharp-new-features
http://www.dotnetcurry.com/showarticle.aspx?ID=1042

Async and Await

0

Category :

Introducing the Keywords

Asynchronous methods look something like this:
public async Task DoSomethingAsync()
{
  // In the Real World, we would actually do something...
  // For this example, we're just going to (asynchronously) wait 100ms.
  await Task.Delay(100);
}

The “async” keyword enables the “await” keyword in that method. That’s all the async keyword does!
The beginning of an async method is executed just like any other method. That is, it runs synchronously until it hits an “await” (or throws an exception).
If “await” sees that the awaitable has not completed, then it acts asynchronously. It tells the awaitable to run the remainder of the method when it completes, and then returns from the async method.
Later on, when the awaitable completes, it will execute the remainder of the async method. If you’re awaiting a built-in awaitable (such as a task), then the remainder of the async method will execute on a “context” that was captured before the “await” returned.
I like to think of “await” as an “asynchronous wait”. That is to say, the async method pauses until the awaitable is complete (so it waits), but the actual thread is not blocked (so it’s asynchronous).

Return Types

Async methods can return Task, Task, or void. In almost all cases, you want to return Task or Task, and return void only when you have to.
If you have an async method returning Task or Task, then you can pass the result to await. With a void method, you don’t have anything to pass to await.
You have to return void when you have async event handlers.

Return Values

Async methods returning Task or void do not have a return value. Async methods returning Task must return a value of type T:
public async Task CalculateAnswer()
{
  await Task.Delay(100); // (Probably should be longer...)

  // Return a type of "int", not "Task"
  return 42;
}

Context

In the overview, I mentioned that when you await a built-in awaitable, then the awaitable will capture the current “context” and later apply it to the remainder of the async method. What exactly is that “context”?
Simple answer:
  • If you’re on a UI thread, then it’s a UI context.
  • If you’re responding to an ASP.NET request, then it’s an ASP.NET request context.
  • Otherwise, it’s usually a thread pool context.

  • // ASP.NET example
    protected async void MyButton_Click(object sender, EventArgs e)
    {
      // Since we asynchronously wait, the ASP.NET thread is not blocked by the file download.
      // This allows the thread to handle other requests while we're waiting.
      await DownloadFileAsync(...);
    
      // Since we resume on the ASP.NET context, we can access the current request.
      // We may actually be on another *thread*, but we have the same ASP.NET request context.
      Response.Write("File downloaded!");
    }
    

    This is great for event handlers, but it turns out to not be what you want for most other code (which is, really, most of the async code you’ll be writing).

    Avoiding Context

    Most of the time, you don’t need to sync back to the “main” context. Most async methods will be designed with composition in mind: they await other operations, and each one represents an asynchronous operation itself (which can be composed by others). In this case, you want to tell the awaiter to not capture the current context by calling ConfigureAwait and passing false, e.g.:
    private async Task DownloadFileAsync(string fileName)
    {
      // Use HttpClient or whatever to download the file contents.
      var fileContents = await DownloadFileContentsAsync(fileName).ConfigureAwait(false);
    
      // Note that because of the ConfigureAwait(false), we are not on the original context here.
      // Instead, we're running on the thread pool.
    
      // Write the file contents out to a disk file.
      await WriteToDiskAsync(fileName, fileContents).ConfigureAwait(false);
    
      // The second call to ConfigureAwait(false) is not *required*, but it is Good Practice.
    }
    
    // WinForms example (it works exactly the same for WPF).
    private async void DownloadFileButton_Click(object sender, EventArgs e)
    {
      // Since we asynchronously wait, the UI thread is not blocked by the file download.
      await DownloadFileAsync(fileNameTextBox.Text);
    
      // Since we resume on the UI context, we can directly access UI elements.
      resultTextBox.Text = "File downloaded!";
    }
    

    The important thing to note with this example is that each “level” of async method calls has its own context. DownloadFileButton_Click started in the UI context, and called DownloadFileAsync. DownloadFileAsync also started in the UI context, but then stepped out of its context by calling ConfigureAwait(false). The rest of DownloadFileAsync runs in the thread pool context. However, when DownloadFileAsync completes and DownloadFileButton_Click resumes, it does resume in the UI context.

    A good rule of thumb is to use ConfigureAwait(false) unless you know you do need the context.

    Async Composition

    So far, we’ve only considered serial composition: an async method waits for one operation at a time. It’s also possible to start several operations and await for one (or all) of them to complete. You can do this by starting the operations but not awaiting them until later:

    public async Task DoOperationsConcurrentlyAsync()
    {
      Task[] tasks = new Task[3];
      tasks[0] = DoOperation0Async();
      tasks[1] = DoOperation1Async();
      tasks[2] = DoOperation2Async();
    
      // At this point, all three tasks are running at the same time.
    
      // Now, we await them all.
      await Task.WhenAll(tasks);
    }
    
    public async Task GetFirstToRespondAsync()
    {
      // Call two web services; take the first response.
      Task[] tasks = new[] { WebService1Async(), WebService2Async() };
    
      // Await for the first one to respond.
      Task firstTask = await Task.WhenAny(tasks);
    
      // Return the result.
      return await firstTask;
    }
    

    By using concurrent composition (Task.WhenAll or Task.WhenAny), you can perform simple concurrent operations. You can also use these methods along with Task.Run to do simple parallel computation. However, this is not a substitute for the Task Parallel Library - any advanced CPU-intensive parallel operations should be done with the TPL.

    Guidelines

    Read the Task-based Asynchronous Pattern (TAP) document. It is extremely well-written, and includes guidance on API design and the proper use of async/await (including cancellation and progress reporting).
    There are many new await-friendly techniques that should be used instead of the old blocking techniques. If you have any of these Old examples in your new async code, you’re Doing It Wrong(TM):
    Old New Description
    task.Wait await task Wait/await for a task to complete
    task.Result await task Get the result of a completed task
    Task.WaitAny await Task.WhenAny Wait/await for one of a collection of tasks to complete
    Task.WaitAll await Task.WhenAll Wait/await for every one of a collection of tasks to complete
    Thread.Sleep await Task.Delay Wait/await for a period of time
    Task constructor Task.Run or TaskFactory.StartNew Create a code-based task


    Next Steps

    I have published an MSDN article Best Practices in Asynchronous Programming, which further explains the “avoid async void”, “async all the way” and “configure context” guidelines.
    The official MSDN documentation is quite good; they include an online version of the Task-based Asynchronous Pattern document which is excellent, covering the designs of asynchronous methods.
    The async team has published an async/await FAQ that is a great place to continue learning about async. They have pointers to the best blog posts and videos on there. Also, pretty much any blog post by Stephen Toub is instructive!

    my thanks to: http://blog.stephencleary.com/2012/02/async-and-await.html
    series about async and OOP programming

    C# Version Feature Additions

    0

    Category :

    Contents

    • Introduction
    • C# 2.0 Features
      • Generics
        • Without Generics
        • With Generics
        • Constraints and Method Parameters and Return Types
        • Factories
      • Partial Types
      • Anonymous Methods
        • The Old Way
        • The New Way
        • Async Tasks
        • Updating The UI
      • Iterators
        • The Old Way
        • The New Way
      • Nullable Types
      • Private Setters (properties)
      • Method Group Conversions (delegates)
        • The Old Way
        • The New Way
    • C# 3.0 Features
      • Implicitly Typed Local Variables
        • Restrictions
      • Object and Collection Initializers
        • The Old Way
        • The New Way
        • Initializing Collections
      • Auto-Implemented Properties
      • Anonymous Types
      • Extension Methods
        • Before Extension Methods
        • With Extension Methods
      • Query Expressions
        • Left and Right Joins
      • Lambda Expressions
      • Expression Trees
    • C# 4.0 Features
      • Dynamic Binding
      • Named and Optional Arguments
        • Example
        • Optional Arguments, The Old Way
      • Generic Covariance and Contravariance
        • Delegates
        • Generics
        • But How Do I Define My Own?
    • Conclusion


    my thanks to this fantastic article
    http://www.codeproject.com/Articles/327916/C-Language-Features-From-C-to

    Extension Methods in C#

    0

    Category :

    Using extension methods, you can use your new methods as a part of int/any class in .NET.

    An extension method is a special kind of static method that allows you to add new methods to existing types without creating derived types.

    The extension methods are called as if they were instance methods from the extended type, For example: x is an object from int class and we called it as an instance method in int class.

    How to Create my Extension Method?

    Simply, you create your own static method in your class and put this keyword in front of the first parameter in this method (the type that will be extended).
    public static class MyExtension 
    { 
        public static int factorial(this int x) 
        { 
            if (x <= 1) return 1; 
            if (x == 2) return 2; 
            else 
                return x * factorial(x - 1); 
        }
    
        public static IEnumerable> Combinations(this IEnumerable elements, int k)
        {
            return k == 0 ? new[] { new T[0] } :
                elements.SelectMany((e, i) =>
                elements.Skip(i + 1).Combinations(k - 1).Select(c => (new[] { e }).Concat(c)));
        }
    }
    
    Usage
    int x = 3;
    x.factorial();
    
    Combinations Usage
    
    List td = new List();
    td.Add(new TransportDetails() { MaxPax = 8, Price = decimal.Parse("88.04") });
    td.Add(new TransportDetails() { MaxPax = 20, Price = decimal.Parse("128.70") });
    td.Add(new TransportDetails() { MaxPax = 31, Price = decimal.Parse("161.37") });
    
    var res = td.Combinations(2);
    
    

    General Tips in Extension Methods Usage

    1. This keyword has to be the first parameter in the extension method parameter list.
    2. It is important to note that extension methods can't access the private methods in the extended type.
    3. If you want to add new methods to a type, you don't have the source code for it, the ideal solution is to use and implement extension methods of that type.
    4. If you create extension methods that have the same signature methods inside the type you are extending, then the extension methods will never be called.
    my thanks to:
    http://www.codeproject.com/Articles/34209/Extension-Methods-in-C
    http://msdn.microsoft.com/en-us/library/bb383977.aspx
    http://www.blackwasp.co.uk/ExtensionMethods.aspx
    http://www.extensionmethod.net/
    101-LINQ-Samples

    Using struct and class - what's that all about?

    0

    Category :

    Class allocates memory on the stack to hold a reference to a MyClass instance in future, it does not create an instance of MyClass, and you will have seen that before - when you try to use any property or method of a class and you get a "Object reference not set to an instance of an object" exception and your program crashes, it's because you created a variable, but didn't create or assign an actual instance to the variable.

    Struct what this does is create a new instance of MyClass on the heap, and assign the reference to it to the variable mc. This is important, because the stack and the heap are different "types" of memory: the heap is a big "lump" of memory which is sorted out by the Garbage collector and all classes, methods and threads share it. The stack on the other hand is specific to a thread, and everything on the stack is discarded when you exit the method - which means that the mc variable is lost, but the data it references is not - if you have copied the reference to a variable outside the method, then you can still access it from the rest of your program.

    When to use a Struct

    CONSIDER defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.

    AVOID defining a struct unless the type has all of the following characteristics:
    1. It logically represents a single value, similar to primitive types (int, double, etc.).
    2. It has an instance size under 16 bytes.
    3. It is immutable.
    4. It will not have to be boxed frequently.

    http://msdn.microsoft.com/en-us/library/ms229017%28v=vs.110%29.aspx
    my thanks to:
    http://www.codeproject.com/Articles/728836/Using-struct-and-class-whats-that-all-about

    Gang of Four Design Patterns

    0

    Category : , ,

    What are Design Patterns?

    Design patterns provide solutions to common software design problems. In the case of object-oriented programming, design patterns are generally aimed at solving the problems of object generation and interaction, rather than the larger scale problems of overall software architecture. They give generalised solutions in the form of templates that may be applied to real-world problems.

    Design patterns are a powerful tool for software developers. However, they should not be seen as prescriptive specifications for software. It is more important to understand the concepts that design patterns describe, rather than memorising their exact classes, methods and properties. It is also important to apply patterns appropriately. Using the incorrect pattern for a situation or applying a design pattern to a trivial solution can overcomplicate your code and lead to maintainability issues.


    Creational Patterns

    The first type of design pattern is the creational pattern. Creational patterns provide ways to instantiate single objects or groups of related objects. There are five such patterns:

    Abstract Factory. The abstract factory pattern is used to provide a client with a set of related or dependant objects. The "family" of objects created by the factory are determined at run-time.

    Builder. The builder pattern is used to create complex objects with constituent parts that must be created in the same order or using a specific algorithm. An external class controls the construction algorithm.

    Factory Method. The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.

    Prototype. The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone. This practise is particularly useful when the construction of a new object is inefficient.

    Singleton. The singleton pattern ensures that only one object of a particular class is ever created. All further references to objects of the singleton class refer to the same underlying instance.


    Structural Patterns

    The second type of design pattern is the structural pattern. Structural patterns provide a manner to define relationships between classes or objects.

    Adapter. The adapter pattern is used to provide a link between two otherwise incompatible types by wrapping the "adaptee" with a class that supports the interface required by the client.

    Bridge. The bridge pattern is used to separate the abstract elements of a class from the implementation details, providing the means to replace the implementation details without modifying the abstraction.

    Composite. The composite pattern is used to create hierarchical, recursive tree structures of related objects where any element of the structure may be accessed and utilised in a standard manner.

    Decorator. The decorator pattern is used to extend or alter the functionality of objects at run-time by wrapping them in an object of a decorator class. This provides a flexible alternative to using inheritance to modify behaviour.

    Facade. The facade pattern is used to define a simplified interface to a more complex subsystem.

    Flyweight. The flyweight pattern is used to reduce the memory and resource usage for complex models containing many hundreds, thousands or hundreds of thousands of similar objects.

    Proxy. The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. The proxy provides the same public interface as the underlying subject class, adding a level of indirection by accepting requests from a client object and passing these to the real subject object as necessary.

    Behavioural Patterns

    The final type of design pattern is the behavioural pattern. Behavioural patterns define manners of communication between classes and objects.

    Chain of Responsibility. The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.
    Command. The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use.

    Interpreter. The interpreter pattern is used to define the grammar for instructions that form part of a language or notation, whilst allowing the grammar to be easily extended.

    Iterator. The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure.

    Mediator. The mediator pattern is used to reduce coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object.
    Memento. The memento pattern is used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation.

    Observer. The observer pattern is used to allow an object to publish changes to its state. Other objects subscribe to be immediately notified of any changes.

    State. The state pattern is used to alter the behaviour of an object as its internal state changes. The pattern allows the class for an object to apparently change at run-time.

    Strategy. The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.

    Template Method.
    The template method pattern is used to define the basic steps of an algorithm and allow the implementation of the individual steps to be changed.

    Visitor. The visitor pattern is used to separate a relatively complex set of structured data classes from the functionality that may be performed upon the data that they hold.


    my thanks to:
    http://www.blackwasp.co.uk/GofPatterns.aspx

    C# Field vs Property

    0

    Category : ,

    Property is a function call. Field is not a call - just access into a memory of the class.

    Properties are more maintainable than fields. Some properties do not have the equivalent field - you need to write some code to set/get them.

    Simple example: say you have a car object. It has a mileage and a gallons as fields. You can make a property MPG by dividing these fields. Notice that there is no MPG field inside an object - you do it on the fly by using a property. And that property is read-only - you cannot set it. It can only be changed by changing mileage field or gallons field.

    From the other hand - the critical code path (large loops, for example) should avoid using a lot of properties or get the properties once before the loop.

    Take a look here:
    http://msdn.microsoft.com/en-us/library/w86s7x04(VS.80).aspx

    Log4Net Tutorial in C#

    0

    Category : , ,

    Logging Levels

    There are seven logging levels, five of which can be called in your code. They are as follows (with the highest being at the top of the list):
    1. OFF - nothing gets logged (cannot be called)
    2. FATAL
    3. ERROR
    4. WARN
    5. INFO
    6. DEBUG
    7. ALL - everything gets logged (cannot be called)

    These levels will be used multiple times, both in your code as well as in the config file. There are no set rules on what these levels represent (except the first and last).

    Add the following code to the Assembly.cs file.

    // Configure log4net using the .config file
     [assembly: log4net.Config.XmlConfigurator(Watch = true)]
     // This will cause log4net to look for a configuration file
     // called TestApp.exe.config in the application base
     // directory (i.e. the directory containing TestApp.exe)
     // The config file will be watched for changes.
    

    Add the following section to the web/app.config file in the node:


    
        

    Create a new section in the web/app.config using log4net as the node name:

    
     
       
       
       
      
       
     
     
       
       
     
      
    

    Define a static logger variable at the top of your class. Something like this will work:

    private static readonly ILog log = LogManager.GetLogger(typeof(Program));
    

    Altogether then, your class might look something like this:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using log4net;
    
    namespace log4netDemo
    {
      class Program
      {
       // Define a static logger variable so that it references the name of your class
       private static readonly ILog log = LogManager.GetLogger(typeof(Program));
    
       static void Main(string[] args)
       {
        log.Info("Entering application.");
    
        for (int i = 0; i < 10; i++)
        {
         log.DebugFormat("Inside of the loop (i = {0})", i);
        }
    
        log.Info("Exiting application.");
       }
      }
    }
    

    my thanks to:
    http://www.justinrhinesmith.com/blog/2008/05/12/quick-and-easy-log4net-setup/