A Basic MVC Application and UI Testing through Selenium Web Driver

0

Category :

This tip describes basic CRUD operations applied to a List of employees. The same operations are then unit tested through Selenium Webdriver.
http://www.codeproject.com/Tips/848279/A-basic-MVC-application-and-UI-testing-through-Sel

XPath Intro

0

Category : ,

Selecting Nodes

Expression Description
nodename Selects all nodes with the name "nodename"
/ Selects from the root node
// Selects nodes in the document from the current node that match the selection no matter where they are
. Selects the current node
.. Selects the parent of the current node
@ Selects attributes

The XML Example Document




  Harry Potter
  29.99


  Learning XML
  39.95




In the table below we have listed some path expressions and the result of the expressions:
Path Expression Result
bookstore Selects all nodes with the name "bookstore"
/bookstore Selects the root element bookstore

Note: If the path starts with a slash ( / ) it always represents an absolute path to an element!

bookstore/book Selects all book elements that are children of bookstore
//book Selects all book elements no matter where they are in the document
bookstore//book Selects all book elements that are descendant of the bookstore element, no matter where they are under the bookstore element
//@lang Selects all attributes that are named lang

Predicates

Predicates are used to find a specific node or a node that contains a specific value.
Predicates are always embedded in square brackets.

In the table below we have listed some path expressions with predicates and the result of the expressions:
Path Expression Result
/bookstore/book[1] Selects the first book element that is the child of the bookstore element.

Note: In IE 5,6,7,8,9 first node is[0], but according to W3C, it is [1]. To solve this problem in IE, set the SelectionLanguage to XPath:

In JavaScript: xml.setProperty("SelectionLanguage","XPath");
/bookstore/book[last()] Selects the last book element that is the child of the bookstore element
/bookstore/book[last()-1] Selects the last but one book element that is the child of the bookstore element
/bookstore/book[position()<3] Selects the first two book elements that are children of the bookstore element
//title[@lang] Selects all the title elements that have an attribute named lang
//title[@lang='en'] Selects all the title elements that have an attribute named lang with a value of 'en'
/bookstore/book[price>35.00] Selects all the book elements of the bookstore element that have a price element with a value greater than 35.00
/bookstore/book[price>35.00]/title Selects all the title elements of the book elements of the bookstore element that have a price element with a value greater than 35.00

Selecting Several Paths

By using the | operator in an XPath expression you can select several paths.

In the table below we have listed some path expressions and the result of the expressions:
Path Expression Result
//book/title | //book/price Selects all the title AND price elements of all book elements
//title | //price Selects all the title AND price elements in the document
/bookstore/book/title | //price Selects all the title elements of the book element of the bookstore element AND all the price elements in the document

Learning XPath by Example

http://www.liquid-technologies.com/xpath-tutorial.aspx

XPath Examples

http://msdn.microsoft.com/en-us/library/ms256086(v=vs.110).aspx


my thanks to: http://www.w3schools.com/xpath/xpath_syntax.asp

Developing MVC applications using SOLID principles

0

Category : ,

my thanks to: Developing MVC applications using SOLID principles http://www.codeguru.com/csharp/csharp/writing-c-code-using-solid-principles.htm

MVC in a nutshell

0

Category :

Getting Data from Controller to View

  1. ViewData - Assign a value with a key in the controller and read the value using the key in the View page
    public ActionResult Index()
    {
      ViewData["Message"] = "Hello, World";
      return View();
    }
    
  2. ViewBag - allows an object to dynamically have properties added to it. So with a ViewBag, you can use the “.” notation.
    public ActionResult Index()
    {
      ViewBag.Message = "Hello, World";
      return View();
    }
    
  3. TempData - is another dictionary for storing temporary data like the “ViewBag“ but is deleted at the end of the HTTP request
    //  marks the specified key in the dictionary for retention
    public void Keep(string key)
    // returns an object without marking the key for deletion
    public Object Peek(string key)
    
  4. Strongly-Typed View Model Object – WebFormViewEngine
    <%@ Page Inherits="System.Web.Mvc.ViewPage" %>
    

    Product Name: <%: Model.Name %>

  5. Strongly-Typed View Model Object – Razor
    @model Mvc3App.Models.Product
    

    Product: @Model.Name


Getting Data from View to Controller

  1. Traditional Approach - HttpRequestBase
  2. FormCollection Object
  3. Action Parameters
  4. Strongly type model binding to view

ActionResult() response types:

There are 11 different response types which can be sent to the end user :-
  1. ViewResult - Renders a specified view to the response stream
  2. PartialViewResult - Renders a specified partial view to the response stream
  3. EmptyResult - An empty response is returned
  4. RedirectResult - Performs an HTTP redirection to a specified URL
  5. RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
  6. JsonResult - Serializes a given object to JSON format
  7. JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
  8. ContentResult - Writes content to the response stream without requiring a view
  9. FileContentResult - Returns a file to the client
  10. FileStreamResult - Returns a file to the client, which is provided by a Stream
  11. FilePathResult - Returns a file to the client

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

CRUD Opearations using AutoMapper

0

Category :

Challenge

Sometimes while interacting with real time (database) entities and binding our model to them, we end up in a situation like:

var dbContext = new MyDBDataContext();
var userDetails = dbContext.Users.FirstOrDefault(userId => userId.UserId == id);
var user = new LearningMVC.Models.User();
if (userDetails != null)
{
    user.UserId = userDetails.UserId;
    user.FirstName = userDetails.FirstName;
    user.LastName = userDetails.LastName;
    user.Address = userDetails.Address;
    user.PhoneNo = userDetails.PhoneNo;
    user.EMail = userDetails.EMail;
    user.Company = userDetails.Company;
    user.Designation = userDetails.Designation;
}
return View(user);
We have an existing model named User (LearningMVC.Models.User()) that has similar properties as that of the Users class generated from the database. Now we initialize properties of the instance of our model from properties of instance of the User class from the database so that we can populate our View in an MVC application.

Now the problem is what if we have 100 column records coming from the database, and also our model has the same number of properties, and the code has to be repeated 6-7 times at different scenarios?

Auto Mapper

As per the AutoMapper CodePlex webpage: "AutoMapper is an object-object mapper. Object-object mapping works by transforming an input object of one type into an output object of a different type. What makes AutoMapper interesting is that it provides some interesting conventions to take the dirty work out of figuring out how to map type A to type B. As long as type B follows AutoMapper's established conventions, almost zero configuration is needed to map two types." Therefore, it provides the solution for our mapping issue.

Example

public ActionResult Index()
{
    var dbContext = new MyDBDataContext();
    var userList = from user in dbContext.Users select user;
    var users = new List();
    if (userList.Any())
    {
        foreach (var user in userList)
        {
            users.Add(new LearningMVC.Models.User()
                {
                    UserId = user.UserId, 
                    Address = user.Address, 
                    Company = user.Company, 
                    FirstName = user.FirstName,
                    LastName = user.LastName,
                    Designation = user.Designation,
                    EMail = user.EMail, 
                    PhoneNo = user.PhoneNo
                });
        }
    }
  
    return View(users);
}
To create the default mapping, call Mapper.CreateMap() with proper types. In this case, T1 will be LearningMVC.User and T2 will be LearningMVC.Models.User.

Mapper.CreateMap();
Now inside the foreach loop, replace the whole code by:
LearningMVC.Models.User userModel = Mapper.Map(user);
users.Add(userModel);
So, our final Action code:
public ActionResult Index()
{
    Mapper.CreateMap();
    var dbContext = new MyDBDataContext();
    var userList = from user in dbContext.Users select user;
    var users = new List();
    if (userList.Any())
    {
        foreach (var user in userList)
        {
            LearningMVC.Models.User userModel = 
              Mapper.Map(user);
            users.Add(userModel);
        }
    }
    return View(users);
}

ForMember() and MapFrom() in AutoMapper

Two important functions in AutoMapper play an important role in object mapping. Suppose our model/viewmodel class has a property FullName, and from the DTO we want to add the First Name and Last Name of the user to make it a full name and bind it to the model. For these kinds of scenarios ForMember() and MapFrom() come in handy.

Mapper.CreateMap().ForMember(emp => emp.Fullname,
map => map.MapFrom(p => p.FirstName + " " + p.LastName));
Here we are saying that ForMember FullName in our model class maps properties from FirstName and LastName of User DTO.

my thanks to: http://www.codeproject.com/Articles/639618/CRUD-Opearations-using-AutoMapper-in-an-MVC-Applic

Passing Data From View to Controller

0

Category :

Using Traditional Approach

In the traditional approach we use the request object of the HttpRequestBase class. The request object has view input field values in name/value pairs.
[HttpPost]
public ActionResult CalculateSimpleInterestResult()
{
    decimal principle = Convert.ToDecimal(Request["txtAmount"].ToString());
    decimal rate = Convert.ToDecimal(Request["txtRate"].ToString());
    int time = Convert.ToInt32(Request["txtYear"].ToString());

    decimal simpleInteresrt = (principle*time*rate)/100;

    StringBuilder sbInterest = new StringBuilder();
    sbInterest.Append("Interest : " + simpleInteresrt);
    return Content(sbInterest.ToString());
}

Using the FormCollection Object

We can also get post requested data by the FormCollection object. The FormCollection object also has requested data in the name/value collection as the Request object. To get data from the FormCollection object we need to pass it is as a parameter and it has all the input field data submitted on the form.
[HttpPost]
public ActionResult CalculateSimpleInterestResult(FormCollection form)
{
    decimal principle = Convert.ToDecimal(form["txtAmount"].ToString());
    decimal rate = Convert.ToDecimal(form["txtRate"].ToString());
    int time = Convert.ToInt32(form["txtYear"].ToString());

    decimal simpleInteresrt = (principle*time*rate)/100;

    StringBuilder sbInterest = new StringBuilder();
    sbInterest.Append("Interest : " + simpleInteresrt);
    return Content(sbInterest.ToString());
}

Using the Parameters

We can pass all input field names as a parameter to the post action method. The input field name and parameter name should be the same. These parameters have input field values that were entered by the user. So we can access view input field values from these parameters. The input field takes a string value from the user so the parameter should be a string type. There is no need to define a parameter in any specific sequence.
[HttpPost]
public ActionResult CalculateSimpleInterestResult(string txtAmount, string txtRate, string txtYear)
{
    decimal principle = Convert.ToDecimal(txtAmount);
    decimal rate = Convert.ToDecimal(txtRate);
    int time = Convert.ToInt32(txtYear);

    decimal simpleInteresrt = (principle*time*rate)/100;

    StringBuilder sbInterest = new StringBuilder();
    sbInterest.Append("Interest : " + simpleInteresrt);
    return Content(sbInterest.ToString());
}

Strongly typed model binding to view

We bind a model to the view; that is called strongly type model binding.
namespace CalculateSimpleInterest.Models
{
    public class SimpleInterestModel
    {
        public decimal Amount { get; set; }
        public decimal Rate { get; set; }
        public int Year { get; set; }
    }
}
[HttpPost]
public ActionResult CalculateSimpleInterestResult(SimpleInterestModel model)
{
    decimal simpleInteresrt = (model.Amount*model.Year*model.Rate)/100;

    StringBuilder sbInterest = new StringBuilder();
    sbInterest.Append("Interest : " + simpleInteresrt);
    return Content(sbInterest.ToString());
}
my thanks to: http://www.codeproject.com/Articles/639709/Getting-Data-From-View-to-Controller-in-MVC

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

    Observer Pattern in .NET

    0

    Category :

    a.k.a. Publisher-Subscriber Pattern.

    Before .NET 4.0, we had to write custom code to implement Observer Pattern or use delegates and events. With the release of framework 4.0 came the IObservable and IObserver interfaces for implementing Observer Pattern.

    Background

    The Observer Pattern defines a one-to-many dependency between objects (Publisher and multiple Subscribers) so that when one object (Publisher) changes state, all the dependents (Subscriber) are notified and updated automatically.

    Sample Scenario

    The Code below is based on a scenario wherein we have a weather station which records weather data (temperature, humidity and pressure).

    This data has to be consumed by multiple displays and displayed acordingly. Everytime there is new data available to the weather station it should "push" the data to the displays which should all be updated accordingly. Suppose we have 3 displays (Current Conditions, Statistics Display and Forecast Display), all of these have to be updated whenever new data is available at the Weather Station.

    Technique #1 - Using Pure Object Oriented (OO) programming concepts.

    Publisher
    Weather Data Provider which provides the weather data, WeatherDataProvider Class implements the IPublisher interface as shown below:
    public interface IPublisher
    {
    	// Registers a new subscriber on the list of subscribers it has to 
        // notify whenever WeatherData has changed
        void RegisterSubscriber(ISubscriber subscriber);
    
        // Removes a registered subscriber from the publisher's notification list
        void RemoveSubscriber(ISubscriber subscriber);
    
        // This method actually invokes a method on the subscriber object to
        // notify that some new WeatherData is available
        void NotifySubscribers();
    }
    
    The concrete implementaion of a WeatherDataProvider would be as below:
    public class WeatherDataProvider : IPublisher
    {
        List ListOfSubscribers;
        WeatherData data;
        public WeatherDataProvider()
        {
            ListOfSubscribers = new List();
        }
        public void RegisterSubscriber(ISubscriber subscriber)
        {
            ListOfSubscribers.Add(subscriber);
        }
    
        public void RemoveSubscriber(ISubscriber subscriber)
        {
            ListOfSubscribers.Remove(subscriber);
        }
    
        public void NotifySubscribers()
        {
            foreach (var sub in ListOfSubscribers)
            {
                sub.Update(data);
            }
        }
    
        private void MeasurementsChanged()
        {
            NotifySubscribers();
        }
        public void SetMeasurements(float temp, float humid, float pres)
        {
            data = new WeatherData(temp, humid, pres);           
            MeasurementsChanged();
        }
    }
    

    Subscriber

    The subscribers here are actually the weather displays, which consume the data. Each subcsriber should implement the ISubscriber interface.
    public interface ISubscriber
    {
        void Update(WeatherData data);
    }
    
    An implementation of the CurrentConditionsDisplay is as under.
    public class CurrentConditionsDisplay : ISubscriber
    {
        WeatherData data;
        IPublisher weatherData;
    
        public CurrentConditionsDisplay(IPublisher weatherDataProvider)
        {
            weatherData = weatherDataProvider;
            weatherData.RegisterSubscriber(this);
        }
    
        public void Display()
        {
            Console.WriteLine("Current Conditions : Temp = {0}Deg | Humidity = {1}% | Pressure = {2}bar", data.Temperature, data.Humidity, data.Pressure);
        }
       
        public void Update(WeatherData data)
        {
            this.data = data;
            Display();
        }
    }
    
    Above we have injected the IPublisher interface via the Constructor.
    When the display in instantiated it makes a call to the RegisterSubscriber method of the WeatherDataProvider and registers itself as an interested subscriber.
    If a display wants to unregister itself, it has to call the RemoveSubscriber method of the WeatherDataProvider.

    Technique #3 - Using IObservable and IObserver.

    In the generic Type IObservable and IObserver, the T in our case would be WeatherData.

    Publisher

    The publisher (WeatherDataProvider) has to just implement the IObservable interface (below).
    public class WeatherDataProvider : IObservable
        {
            List> observers;
    
            public WeatherDataProvider()
            {
                observers = new List>();
            }
    
            public IDisposable Subscribe(IObserver observer)
            {
                if (!observers.Contains(observer))
                {
                    observers.Add(observer);
                }
                return new UnSubscriber(observers, observer);
            }
    
            private class UnSubscriber : IDisposable
            {
                private List> lstObservers;
                private IObserver observer;
    
                public UnSubscriber(List> ObserversCollection, IObserver observer)
                {
                    this.lstObservers = ObserversCollection;
                    this.observer = observer;
                }
    
                public void Dispose()
                {
                    if (this.observer != null)
                    {
                        lstObservers.Remove(this.observer);
                    }
                }
            }
    
            private void MeasurementsChanged(float temp, float humid, float pres)
            {
                foreach (var obs in observers)
                {
                    obs.OnNext(new WeatherData(temp, humid, pres));
                }
            }
    
            public void SetMeasurements(float temp, float humid, float pres)
            {
                MeasurementsChanged(temp, humid, pres);
            }
        }
    
    Observers register to receive notifications by calling its IObservable.Subscribe method, which assigns a reference to the observer object to a private generic List object. The method returns an Unsubscriber object, which is an IDisposable implementation that enables observers to stop receiving notifications. The Unsubscriber class is simple a nested class that implements IDisposable and also keeps a list of Subscribed users and is used by the observers (Displays in our case), to unsubscribe.

    Also, there is a function OnNext which we have invoked on the subscriber/observer. This function is actually an inbuilt function of IObserver which indicates that something has changed in the collection. This is actually the function which notifies the subscribers of changes.

    Subscriber

    The subscriber (Displays) have to just implement the IObserver interface. The implementation of the CurrentConditionsDisplay is as under. We can have similarly any number of displays.
    public class CurrentConditionsDisplay : IObserver
    {
        WeatherData data;
        private IDisposable unsubscriber;
    
        public CurrentConditionsDisplay()
        {
    
        }
        public CurrentConditionsDisplay(IObservable provider)
        {
            unsubscriber = provider.Subscribe(this);
        }
        public void Display()
        {
            Console.WriteLine("Current Conditions : Temp = {0}Deg | 
                                Humidity = {1}% | Pressure = {2}bar", 
                                data.Temperature, data.Humidity, data.Pressure);
        }
    
        public void Subscribe(IObservable provider)
        {
            if (unsubscriber == null)
            {
                unsubscriber = provider.Subscribe(this);
            }
        }
    
        public void Unsubscribe()
        {
            unsubscriber.Dispose();
        }
    
        // Pass the observer a T object that has current data, changed data, or fresh data.
        public void OnNext(WeatherData value)
        {
            this.data = value;
            Display();
        }
    
        // Notify the observer that some error condition has occurred
        public void OnError(Exception error)
        {
            Console.WriteLine("Some error has occurred..");
        }
    
        // Notify the observer that it has finished sending notifications
        public void OnCompleted()
        {
            Console.WriteLine("Additional temperature data will not be transmitted.");
        }
    }
    

    my thanks to:
    http://www.codeproject.com/Articles/796075/Implement-Observer-Pattern-in-NET-techniques

    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

    Moment.js

    0

    Category :

    A javascript date library for parsing, validating, manipulating, and formatting dates.

    Format Date
    moment(tourDate).format('DD/MM/YYYY')

    Format Todays Date
    moment().format("DD/MM/YYYY");

    http://momentjs.com/

    The Principles of Agile Development

    0

    Category :

    http://code.tutsplus.com/articles/the-principles-of-agile-development--net-25732

    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

    Pass Collection to Function or Procedure

    0

    Category :

    
    IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = 'TestPassList')
     DROP TYPE TestPassList
    GO
    
    CREATE TYPE dbo.TestPassList
    AS TABLE
    (
     BookingIdMaster INT,
     BookingId  INT
    );
    GO
    
    
    CREATE PROCEDURE sp_TestPassList
      @List AS dbo.TestPassList READONLY
    AS
    BEGIN
     SELECT *
      FROM @List
    
    END
    GO
    
    
    IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'fn_TestPassList') AND type in (N'P', N'TF'))
     DROP FUNCTION fn_TestPassList
    GO
    
    CREATE FUNCTION fn_TestPassList(@List AS dbo.TestPassList READONLY)
    RETURNS @temptable 
     TABLE (  
       BookingId INT
     )       
    AS 
    BEGIN 
      
     INSERT INTO @temptable    
      SELECT BookingId
      FROM @List
     
     RETURN      
    END
    GO
    
    ----------- test
    DECLARE @TestPassListVar dbo.TestPassList
    INSERT INTO @TestPassListVar 
    SELECT TOP 10 billing_id Booking_IdMaster,
        Booking_Id
     FROM d_booking
     
    SELECT * 
     FROM fn_TestPassList(@TestPassListVar)
     
    

    SOLID: Part 4 - The Dependency Inversion Principle

    0

    Category :

    Definition

    • A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
    • B. Abstractions should not depend upon details. Details should depend upon abstractions.


    my thanks to:
    http://code.tutsplus.com/tutorials/solid-part-4-the-dependency-inversion-principle--net-36872

    Pivot - SQL Server

    0

    Category :

    “Pivot is a sql server operator that can be used to turn unique values from one column, into multiple columns in the output, there by effectively rotating a table”. Column values are converted into column names

    Read Pivot Statement

    We are performing this aggregate function on the 1st column for 2nd column for column in “in”



    Represented in cross tab format…

    my thanks to: http://www.youtube.com/watch?v=h3BtudZehuo

    SOLID: Part 3 – Liskov Substitution & Interface Segregation Principles

    0

    Category : ,

    http://net.tutsplus.com/tutorials/php/solid-part-3-liskov-substitution-interface-segregation-principles/

    Subtypes must be substitutable for their base types.

    SOLID: Part 2 – The Open/Closed Principle

    0

    Category : ,

    To design our modules, classes and functions in a way that when a new functionality is needed, we should not modify our existing code but rather write new code that will be used by existing code.


    http://net.tutsplus.com/tutorials/php/solid-part-2-the-openclosed-principle

    SOLID: Part 1 – The Single Responsibility Principle

    0

    Category : ,

    http://net.tutsplus.com/tutorials/php/solid-part-1-the-single-responsibility-principle/

    Class and module design is highly affected by The Single Responsibility Principle and leads to a low coupled design with less and lighter dependencies. But as any coin, it has two faces. Excessive SRP consideration can easily lead to premature optimization and instead of a better design, it may lead to a scattered one where the clear responsibilities of classes or modules may be hard to understand

    Introduction to CQRS

    0

    Category :

    http://www.codeproject.com/Articles/555855/Introduction-to-CQRS

    CQRS (Command Query Responsibility Segregation, http://martinfowler.com/bliki/CQRS.html) is a technique that separates data creation and modification from data querying. In a pure CQRS model a stored procedure would not both insert/update data and then retrieve data. Those are two distinct operations, and therefore separated.

    Ok, I’ll do want to acknowledge that CQRS can complicate your application infrastructure, and that it does not make sense to use this pattern in any and every application you ever build. This is a pattern you would use when you have requirements for Resilience or massive scale.

    http://www.sswug.org/editorials/readed.aspx?id=3004