C# Best Practices: Improving on the Basics

0

Category :

Null Reference Check - Null Conditional Operator

product?.Option?.Name

Nullable Types

help distinguish default and "not set" values

Static Class

Container for Utility methods logging + email

Read-only properties

set on intialisation or constructor and not changed.

Expression based Properties

using lambda operator => public string FullName => FirstName + " " + LastName;

Auto-Implemented Properties

simple properties, no additional get/set code necessary

Validate Incoming Params - "Guard clauses"

 if(product == null) throw new ArgurmentNulException(nameof(product));
Guard clauses should also be tested.
 [ExpectedException(typeof(ArgumentNullException))]

Method Chaining - Optional Params

One method overload calls another method overload to prevent repeated code.
public Result PlaceOrder(Product product, int quantity)
{
   return PlaceOrder(product, quantity, null, null);
}

public Result PlaceOrder(Product product, int quantity, DateTimeOffset? deliverBy)
{
   return PlaceOrder(product, quantity, deliverBy, null);
}

public Result PlaceOrder(Product product, int quantity, DateTimeOffset? deliverBy, string instructions)
{
   // all of code here
}

Expression-bodied Methods

Syntax shortcut for single statement methods that return a value. Avoid when:
Guard clauses are necessary.
Exception handling necessary.
public decimal CalculateSuggestedPrice(decimal markupPercent)
{
 return this.Cost + (this.Cost * markupPercent / 100);
}

public decimal CalculateSuggestedPrice(decimal markupPercent) =>
 this.Cost + (this.Cost * markupPercent / 100);


my thanks to:
https://app.pluralsight.com/library/courses/csharp-best-practices-improving-basics/table-of-contents

C# Predicate

0

Category :

Predicate is a functional construct providing a convenient way of basically testing if something is true of a given T object.

The Predicate will always return a boolean, by definition.
Predicate is basically identical to Func
List of People objects and we need to find if one is named Oscar:

Old Method

Person oscar = null;
foreach (Person person in people) {
    if (person.Name == "Oscar") {
        oscar = person;
        break;
    }
}

if (oscar != null) {
    // Oscar exists!
}
If we need to find someone with a different name then we will need a lot more code using this method.

Predicate

Using Predicates involves much less code and maybe easier to read....maybe
Predicate oscarFinder = (Person p) => { return p.Name == "Oscar"; };
Predicate ruthFinder = (Person p) => { return p.Name == "Ruth"; };
Predicate seventnYOFinder = (Person p) => { return p.Age == 17; };

Person oscar = people.Find(oscarFinder);
Person ruth = people.Find(ruthFinder);
Person seventeenYearOld = people.Find(seventnYOFinder );


my thanks to:
http://stackoverflow.com/questions/1710301/what-is-a-predicate-in-c

C# Yield

0

Category :

The following example shows the two forms of the yield statement.

1. Yield Break

You can use a yield break statement to end the iteration.

2. Yield Return expression

Return each iterator element one at a time. Each iteration of the foreach loop calls the iterator method. When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.

C# Example:

    static void Main()
    {
        // Display powers of 2 up to the exponent of 8:
        foreach (int i in Power(2, 8))
        {
            Console.Write("{0} ", i);
        }
    }

    public static IEnumerable Power(int number, int exponent)
    {
        int result = 1;

        for (int i = 0; i < exponent; i++)
        {
            result = result * number;
            yield return result;
        }
    }

    // Output: 2 4 8 16 32 64 128 256

Control flow:

1. Hits foreach
2. Enters Power method
3. Yield return result
4. Returns to outer foreach
5. Console write
6. Next loop of foreach re-enters Power method
7. Remembers previous value of "result"
8. And so oooooon......

Main Uses

Custom Iteration: No need for temp collection to store result-set that matches criteria.
Stateful Iteration: Keeping track of state during foreach

my thanks to:

https://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx
https://www.youtube.com/watch?v=4fju3xcm21M

Delegates

0

Category :

Delegate is a Pointer to a function/method.

What is the benefit of calling the method indirectly via a pointer?

Dictionary def - Delegate: is a representative to communicate between two parties.

    
    class Program
    {
        static void Main(string[] args)
        {
            MyClass obj = new MyClass();
            obj.LongRunning(Callback);
        }

        static void Callback(int i)
        {
            Console.WriteLine(i);
        }
    }

    public class MyClass
    {
        public delegate void CallBack(int i);
        public void LongRunning(CallBack obj)
        {
            for (int i = 0; i < 10000; i++)
            {
                obj(i);
            }
        }
    }

Program Flow

1. Call LongRunning passing Callback method.
2. LongRunning method within MyClass is executed and executes passed in method which is now called obj but in reality it is a Pointer to the Callback method.
3. Callback method is executed on Program class, which writes the current value of i to the console.

my thanks to:
https://www.youtube.com/watch?v=ifbYA8hyvjc
http://www.codeproject.com/Articles/1061085/Delegates-Multicast-delegates-and-Events-in-Csharp

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

AngularJS Basics

0

Category :

1) Angular Directive = ng-app

2) Access Angular Model through controllers

3) $scope is Angular Model

4) ng-controller directive sets js function name to use as controller for a portion of page, different portions of the page could have diff controllers.

5) Setting ng-app="nameApp" prevents polluting of the global namespace:
 
 <html ng-app="nameApp">
   <head>
     <meta charset="utf-8">
     <title>Angular.js Example</title>
     <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
     <script>
       var nameApp = angular.module('nameApp', []);
       nameApp.controller('NameCtrl', function ($scope){
         $scope.firstName = 'John';
         $scope.lastName = 'Smith';
       });
     </script>
   </head>
   <body ng-controller="NameCtrl">
     First name:<input ng-model="firstName" type="text"/>
     <br>
     Last name:<input ng-model="lastName" type="text"/>
     <br>
     Hello {{firstName}} {{lastName}}
   </body>
     </html>
    
6) Could have multiple Angular apps running on the same page.







my thanks to:
https://github.com/curran/screencasts/tree/gh-pages/introToAngular

AngularJS Intro

3

Category :

Data Binding Framework

Main usage creating single-page apps.
Based on MVC architecture

Provide solutions for:

  • Routing - handling updates to the url hash fragment
  • Templating - dynamically creating and updating HTML based on templates and models
  • Data binding - synchronise the model and user interface
  • Top data-binding frameworks:

    AngularJS
    KnockoutJS
    Ember
    JsViews

    Related libraries

    • jQuery - industry standard library for DOM manipulation and AJAX
    • AMD - for seperating JavaScrip projects across many files using modules, allowing depencies from one files on another. Require
    • Angular provides a jQuery like API jqLite - which is like jQuery minimal functionality
    • Promises - industry standard pattern for dealing with asynchronous control flow. The top Promises implementation is Q.
    • Async.js
    • Handlebars - templating engine. Angular Templates use similar syntax.

    Angular Learning Resources

    It is straightforward to teach yourself about Angular, as there are so many learning resources on the Web.

    Bird's-eye-view:

    Learn Angularjs This Weekend - Advice on which resources to use for getting up to speed on Angular.
    A Better Way to Learn AngularJS - A great collection of links to resources for learning Angular.
    AngularJS-Learning - A kitchen sink of links to Angular learning resources.

    Introductory tutorials and guides:

    Angular Developer Guide Conceptual Overview
    • Enumerates fundamental concepts
    • Provides several code examples
    Official Angular Tutorial
    • Useful to read through
    • Emphasizes testing
    • Starts with complex boilerplate project
    • Great diagrams
    Egghead.io
    • A collection of short screencasts (scroll to the bottom for intoduction content)
    AngularJS Fundamentals In 60-ish Minutes
    • A talk on YouTube that covers fundamentals of Angular
    Learn Angular.js in 30 Min
    • A screencast showing how to build an app using UI-Router
    • Does not cover basics, jumps to advanced usage
    • Great example of how development flows in practice
    An Introduction to AngularJS Forms Validation

    Design and implementation of Angular:

    Re-Imagining the Browser with AngularJS
    • Talk by Miško Hevery, creator of Angular
    • Discusses the high-level goals of Angular
    Bringing Angular Apps to Life with Animation by Miško Hevery
    Google I/O 2013 - Design Decisions in AngularJS
    "Writing Directives" talk by Misko Hevery




    my thanks to: https://www.youtube.com/watch?v=TRrL5j3MIvo
    https://github.com/curran/screencasts/tree/gh-pages/introToAngular