Pages

Thursday, December 17, 2015

c# extension methods

C# EXTENSION METHODS – add methods, that currently do not exist, to a class . Example, can add methods to the String class. Must be declared in a static class with static methods. This example extends the DateTime class. 


EXTENSION METHOD CREATED

Add caption






EXTENSION METHOD USAGE

Sunday, October 25, 2015

Delegates and events

A delegate in c# are variables that hold a reference to a function. It can reference more than one function (multicast). When the delegate is called, it will invoke all functions assigned. If return values are given, the return value of the delegate will be from the last function invoked.

Example:

public delegate string MyDelegate();

MyDelegate myDel = SomeFunction;   // this is short hand. Might see "new MyDelegate(SomeFunction)"

myDel += AnotherFunction;  // multicasting. Adding additional functions. 


var return = myDel();  // both functions will be invoked but return will hold "another"


public string SomeFunction()
{
    return "some";
}

public string AnotherFunction()
{
    return "another";
}


Rules can bend for delegate signature matches. It is a result of inheritance,

The delegate return value must match the return type of the function assigned to the delegate except in cases of covariance. Covariance is when the return type (Dog) of the function is derived from the return type (Animal) of the delegate. 

COVARIANCE:

delegate Animal MyCovarDelegate();     

MyCovarDelegate myCovDel = FindDog;

public Dog FindDog();  // Dog (function return type) is derived from Animal (delegate return type)

public class Animal
{
    public string type;
    public boolean mammal;
}

public class Dog : Animal
{
    public string breed;
}


The delegate parameter type must match the parameter type of the function except in cases of contravariance. Contravariance is when the param type (Dog) of the delegate is derived from the param type (Animal) of the function. It is reverse/contra of covariance. 

CONTRAVARIANCE:

delegate void MyContraDelegate(Dog d); // Dog (delegate param type) is derived from Animal (function return type)

MyContraDelegate myConDel = ViewDog;

public void ViewDog(Animal a); 


Why Delegates?

1) Is used to handle events (shown below).
2) Allows programs to run methods at run time without knowing the methods at compile time.
2a) Objects can be decoupled between publishers and subscribers. Publisher has no idea who is subscribing nor what the subscriber is doing. It simply creates an event, when the event is raised, it checks to see if there are any subscribers. If subscribers, then it runs the EventHandler (which contains a list of methods (points to methods) that are set to run).
2b) By creating a new class and simply subscribing to the existing event that is published, you can add new classes and attach to events without modifying the original code. Hence, less chance of code breakage. 
3) Achieves Inversion of Control (IOC) when a framework/library wants to call you.
4) Can pass delegates as a parameter to a function.


public class Person
{
     public delegate void MyEventHandler();
     public event MyEventHandler cashEvent;

     public void AddCash()
    {
        If (cash > 5 )    // some event occurs
                   {
                      If (cashEvet != null)   // check for subscribers
                                           {
                                                cashEvent();   // fire event
                                           }
                   }
    }
}

public class Hello
{
     Person p = new Person();
     p.cashEvent += p_cashEvent;      // subscribe to event and assign function(s) to invoke
    
    public void p_cashEvent()
    {
      // do something
    }
}


*****

Func <T> and Action <T> are .net built in delegates

Tuesday, September 15, 2015

Value vs Reference Types in c#

VALUE types are stored in one location in stack memory.

Primitive types such as int, bool, float, char are value types.

Structs are value types. Structs are cut down classes. Must use Struct keyword instead of class. Structs do not support inheritance. They reside in stack memory which can run faster than things stored in heap.

Runtime deals with the actual data so it is more efficient.


Reference types are stored in heap memory. The object is created in memory and then handled through a reference, similar to a pointer.

Classes are reference types. They are less efficient. Classes support inheritance.


Example value types:

int i = 1;
int j = i;
i++;

what is the value of j?

when you assign the value of i to j, it makes an actual copy of the value so j = 1; so when i is incremented, it doesn't affect the value of j; therefore, j = 1 and j does not = 2.


Example reference types:

class Form()
{
   string Text;
}

Form myForm = new Form();   // this creates two stores of memory: 1) ref to object  2) the object itself  

Form myForm;              // this breaks down the above to see clearer  1) reference to object is created
myForm = new Form();    // object is created in memory

Test (myForm);

void Test (Form f)
{
    f.Text = "hello";      // myForm's caption changes because myForm and f point to the same object
    f = null;   // myForm is intact because only a copy of the reference has been nullified/erased; myForm still holds its original reference to the object
}



http://www.albahari.com/valuevsreftypes.aspx

Monday, September 7, 2015

Object Oriented Programming

Object Oriented Programming (OOP) is a software development methodology that breaks up code into modules for greater reuse and maintainability. Prior to OOP, code was written in procedural format that led to large, monolithic pieces of code that was difficult to maintain (update and make changes). OOP breaks up the code into chunks for better maintainability which allows the code base to scale.

Class allows you to create custom types by grouping together variables, methods, and events. The class acts a blueprint or a template.

There are 3 pillars of OOP.

1) Inheritance - this deals with code reuse. If there are multiple classes that share the same properties, fields, methods, and events, you can create a base class that contains all of the shared members. Any child class that inherits from the base class is automatically exposed to all the members of the base class. The child class can be extended to add its own members to make it unique. If a method in the base class is defined as virtual, then the child class can override the method creating a new method implementation.

An abstract class is a base class that can contain abstract methods. Abstract methods are only defined and do not have any code implementation. Abstract classes cannot be instantiated. They can only be inherited. When a class inherits from an abstract class, it must implement all the abstract methods. An interface is a special form of an abstract class where ALL the methods are abstract. A class can only inherit from one abstract class. A class can inherit from multiple interfaces.

2) Encapsulation - this describes hiding the internal state (data) of a class. The common technique is to use private fields that can only be accessed by public properties. The advantage is that you have more control over the behavior of the data you can protect the data. For example, if you define a public field as int, it is exposed (can be changed) by all the code in the application. Also, it has a valid range of +/- 2.1 billion. By using encapsulation, you can implement code in the SET part of the public property that limits the valid values from 0 - 10.

Encapsulation helps to reduce coupling between objects and increases code maintainability.

3) Polymorphism - allows an object of one type to behave like a different type.

Example is the use of interfaces. You can have multiple classes inheriting the same interface, however, each class can implement different methods, thereby achieving different behaviors.

Another example is the use of overrides. If a base class defines a method as virtual, then child classes that inherit from the base class can override/change the virtual method implementation. The result is that multiple classes can inherit from the same base class, but because of different code implementations (overrides), they can all behave differently.

Method overloading IS NOT polymorphism.

*****

Interface - collection of properties and public methods grouped together to encapsulate functionality. The methods are abstract meaning that they are only defined. Any class that inherits from an interface must implement code for all the methods. In this sense, an interface is like a contract that guarantees the availability of all the methods defined. An interface is a special form of an abstract class whereby, all the methods are abstract. As such, it cannot be instantiated and must be inherited.

Static member - are shared between instances of a class. Think of them as global variables. Don't have to instantiate to use. Example:  Console.WriteLine() is a static method.

Struct - is like a cut down version of a class. Use Struct keyword instead of class. Structs are value types and resides in one place in memory. Classes are reference types so it holds a reference to a location in memory where the content is stored. Struct resides in the stack memory and the actual object is affected so it runs faster than classes that reside in the heap. Structs do not support inheritance.

Saturday, February 7, 2015

SQL Server database migration to Azure SQL

1) To migrate a SQL DB to a DB on an Azure VM. In SSMS, rt click DB > Tasks > Deploy to Azure VM.


2) This is easy method to migrate databases from SQL Server to the Azure SQL database (not Azure VM). Note: This is for website, not VM.

DOWNLOAD: http://sqlazuremw.codeplex.com/

VIDEO that shows how to use the migration tool (pretty easy to use).

http://channel9.msdn.com/posts/SQL-Azure-Migration-Wizard-Part-2-Using-the-SQL-Azure-Migration-Wizard

Key points:

- during wizard steps, click Advanced to choose "schema with data" to generate a script that includes the data
- in the connection string, for user, need to add user@servername