Pages

Sunday, April 24, 2022

c# async/await

 Async/Await for c#. 

Two benefits:

  • UI is not locked up because control is returned to the calling method.
  • If the async calls do not depend on each other, then they can be run in parallel.

Parallel example:

Use a foreach and add Task to a List of Tasks. 

var tasks = new List<Task<string>>();

foreach (string site in listOfWebsites)
{
    tasks.Add(Task.Run( () => DownloadWebsite(site)));
}

var results = await Task.WhenAll(tasks);

Thursday, December 31, 2020

c# Delegates

Delegates are methods that are passed in as a parameter. Now, you can change the implementation of the method that is passed in from a different part of the code. For instance, "mentionSubTotal" can be implemented differently (discount is applied differently) from another location. 

Delegates are pointers to functions. But what is the purpose of calling functions indirectly (passing them in) via delegates versus calling that same function directly? 

Delegates are used to communicate between two parties. The main use of delegates are callbacks, callbacks, callbacks ...  

public class ShoppingCartModel

    {

        public delegate void MentionDiscount(decimal subTotal);

        public List<ProductModel> Items { get; set; } = new List<ProductModel>();

        

        // These are the 3 types of delegates.

        // 1) MentionDiscount is the "raw" delegate

        // 2) Func takes params (up to 16) and returns a value. No out params allowed.

        // 3) Action takes params (up to 15) and returns void. 


// Here is example using all 3 forms. Generally, you would only use one delegate, not 3). 

        public decimal GenerateTotal(MentionDiscount mentionSubtotal,

            Func<List<ProductModel>, decimal, decimal> calculateDiscountedTotal,

            Action<string> tellUserWeAreDiscounting)

        {

            decimal subTotal = Items.Sum(x => x.Price);


            mentionSubtotal(subTotal);


            tellUserWeAreDiscounting("We are applying your discount.");


            return calculateDiscountedTotal(Items, subTotal);  // returns decimal

        }

    }


From the calling method side, there are 2 ways to do.

1) You can create the method and pass in the method name:

Console.WriteLine($"Shopping cart subtotal: {cart.GenerateTotal(SubTotalAlert, CalculateLeveledDiscount, AlertUser):C2}");

All 3 methods will be defined in the class. For example, SubTotalAlert is defined here and passed as a parameter above.

private static void SubTotalAlert(decimal subTotal)

        {

            Console.WriteLine($"The subtotal is {subTotal:C2}");

        }


2) Instead of defining methods, you can write anonymous functions inline. All 3 methods are written as inline parameters and passed as parameters. 

decimal total = cart.GenerateTotal((subTotal) => Console.WriteLine($"The subtotal for cart 2 is {subTotal:C2}"),

                (products, subTotal) => {

                    if(products.Count > 3)

                    {

                        return subTotal * 0.5M;

                    }

                    else

                    {

                        return subTotal;

                    }

                },

                (message) => Console.WriteLine($"Cart 2 Alert: { message }"));

Wednesday, December 30, 2020

c# events

1) Create the event in Customer class. The <TYPE> can be string, decimal, bool, class, etc. 

public event EventHandler<decimal> OverdraftEvent; 


2) Place code to trigger the event.

public void MakePayment (decimal amount)

{ 

    if (amount < accountFunds)   // Not enough. Create event trigger. 

           OverdraftEvent?.Invoke(this, amount);

}


3) Create listeners for the event. Attached methods to run when event is triggered. You can place the event listeners in different classes/places as needed. 

private void WireUpForm()

{

    customer.Checking.OverdraftEvent += CheckingAccount_OverdraftEvent;

}


4) Create method that is run when event is triggered. 

private void CheckingAccount_OverdraftEvent(object sender, decimal e)

{

    // do something to handle event ... for example:

    errorMessage.Text = $"Not enough funds available for your {string.Format("{0:C2}", e)} transaction";

}


5) Remove listeners when app is closing. Else, the app may not fully close and get stuck in memory with no garbage collect. This leads to memory leaks !

customer.Checking.OverdraftEvent -= CheckingAccount_OverdraftEvent;

Friday, August 14, 2020

Rebase steps

 Terminal > 

git rebase -i HEAD~3

> GIT window comes up to make changes

[[[ > If I want to cancel, without changes, use # to comment out all lines and "wq!". No changes will be made.

> OR another way is to use "q!" to quit. Then use "git rebase --abort". ]]]

replace "pick" with s or f

ESC > : > wq! > press ENTER

git push -f origin feature/test-9999_sampleBranch    (force push will completely overwrite the origin branch)

Thursday, September 5, 2019

Resolve merge conflicts

SourceTree > rebase branch on top of Develop > Merge Conflicts !


Go to Visual Studio > Team Explorer > Changes > Conflicts

Click each conflict and click MERGE button.
Resolve (left side) by adding both changes.
Click "Accept Merge" top left.


Conflicts are resolved.


Go to SourceTree. Will not be on a branch. Stage all changes.
> Terminal > git rebase --continue






This will finish rebase and go to correct branch. If all looks good, then do a final push:
> Terminal > git push -f origin feature/3100_NewFeatureBranch

Saturday, January 12, 2019

React JS notes

- ES7 to generate quick template

In VS Code, go to 1) Extensions tab  2) Install ES7



This makes creating new JS files easy.

Create new file:  TestFile.js
Type "rce" and press Tab (rcf for function template)
It auto creates this template code:




- UUID (unique id generator)

> CNTL - C to stop dev server
> npm i uuid  (to install package)
> npm start (restart dev server)

import uuid from 'uuid';

id: uuid.v4();   < this will generate the ID


- React Router

> npm i react-router-dom


- HTTP API library (Axios) - can use instead of jQuery or fetch

> npm i axios





Saturday, December 22, 2018

SOLID - Liskov Substitution Principle

If S is a subtype of T, then objects of type T can be substituted by objects of type S without breaking the program.

public class Employee {
    public string Firstname {get; set;}
    public string Lastname { get; set;}

    public virtual void AssignManager (Employee Manager)
    {
          // set manager for employee
    }
}


Employee emp = new Employee();
emp.AssignManager();


Above, Employee type is T.


public class Staff : Employee {
    public string Dept {get; set;}
    public string Manager {get; set;}
}

Above, Staff (S) is a subtype of T (Employee). Liskov says that since S is a subtype of T, then this should work:


Employee emp = new Staff();
emp.AssignManager();


Let's create another subtype of Employee (T).

public class CEO : Employee{
       public string Rating {get; set;}
       public override void AssignManager(Employee manager)
       {
               throw new Exception("CEO does not have a manager");
       }
}


Above, CEO is subtype of Employee. However, this does not work and thus, it violates the Liskov Principle:

Employee emp = new CEO();
emp.AssignManager();

This code throws an exception because 1) CEO does not have a manager  2) code is set to throw error for invalid method.

Liskov Sub Principle states that Staff() should be a TRUE Employee().
CEO should be a TRUE Employee(), but it is not. So LSP is violated.

How to fix so that even CEO (subtype object of T) can be substituted for the objects of T? So that above code works?

Wednesday, December 19, 2018

Agile Methodology

2 week sprints.

Weekly PAR review. Small group reviews new defects.

BACKLOG GROOMING (every 2 weeks):
- Stories: discuss story and using pointingPoker.com to point. Goal is to create a score to help estimate relative complexity. Stories are items that add value for customer (e.g., product feature, performance improvements, etc.)
- Tasks do not get pointed. Tasks are items good things to do, but does not correlate directly to a benefit for a customer.
- Review defects (high level)
- Move priority items to top of backlog

SPRINT PLANNING (every 2 weeks):
- Occurs at the start of a sprint. 4 hrs allocated and then we officially start the sprint.
- Assess total team hours available
- Add items to sprint and check team hours remaining
- For stories, create sub-tasks
- For defects, set hours

START SPRINT
- Tickets are prioritized
- Tickets are not assigned so anyone can take
- If a bug is found during a story, create a BUG subtask and take hours from the story's time bank.

SPRINT RETROSPECTIVE (when sprint ends):
- Discuss good and bad points
- Action items (past and future)

Monday, December 17, 2018

GIT Cheat sheet

REBASE:

git rebase -i HEAD~3     > pulls up the latest 3 commits

[INSERT] Edit the interactive screen
[ESC]
[Shift :]
wq!         > saves and exits

git log    view new rebased log

git push -f origin bug/sample-1000   > pushes latest changes to origin



RESET:

git reset --hard HEAD~1    > undo prior commit and delete it
git reset --soft HEAD~1     > undo prior commit and keep changes

Tuesday, August 9, 2016

c# Dependency Injection

Dependency Injection is a way to implement the Inversion of Control (IOC) principle. 

Start of app, need to configure container. One option is to create a class to configure (register interfaces to implementations). 

Benefits of Dependency Injection.

A) Unit testing. Can now mock implementations for interfaces. So instead of actually Saving data, it mocks a successful save. Instead of reading data, it mocks returned data. In the unit test, you can Verify that each call is done. Can check logged messages. 

B) Able to change code implementations later. Without changing the "internal" code. Just change the container to register the interface to the new implementation (new class) ... existing code should work as is. This decoupling of code makes large applications very modular and flexible. It is now plug and play. 

Types of DI:

1) Constructor Injection (most popular)

public class InjectedClass
{
    private IDepInterface _iDependInterface;

    public InjectedClass(IDepInterface myInterface)
    {
        _iDependInterface = myInterface;
    }
}


2) Property Injection (applied at the property level)
 
private IDepInterface _myProp;

public IDepInterface MyDependencyProperty
{
     get { return ths._myProp;  }
    set { this.myProp = value;  }
}


3) Method Injection (when entire class doesn't need dependency, but just that one method)

public class InjectedClass
{
     readonly IDepInterface _iDependencyInterface;
  
    public MyMethod(IDepInterface myInterface)
    {
        // use myInterface
    }
}

SOLID


https://www.youtube.com/watch?v=gwIS9cZlrhk


Single Responsibility Principle - a function should only have one reason to change

OC Principle - a class should be open for extension but closed for modification. Once a class is done, it is done (unless there is a bug).

Meyer: Derives from requirements for the code. If requirements change, instead of changing the class, make a new class that inherits from the old class. Make the changes in the new class instead and leave the old class untouched. If you make the method in the old class "virtual", then you can "override" the method in the new class.

Massive question: how much of the class do you make "virtual". Very difficult to answer because once its coded, you are not supposed to go back and change from "virtual" to not "virtual" and vice versa.

Also, sometimes its hard to determine if its a bug or feature change.

Upside: if you code something and build a bunch of unit tests, if the code requirements change and you recode the logic, then the unit tests need to be redone. However, using OCP, because you don't change the original class, there is no need to redo existing tests. Instead, create a new class (which inherits from the old class) and therefore, you only need to create a new unit test of the new class.

Polymorphic: instead of Meyer method, create an abstract base class or an Interface and build new implementations as needed and plug in.

How to get it to work with abstract classes (AC) or interface? Since you are not inheriting, you have to really know what your AC or interface is supposed to be doing.

Both Meyer and Polymorphic hold that the original class should not need to be modified (unless there is a bug) to implement changes or to extend the original requirements.

BENEFIT: you don't change code once it works. Then you don't break code that is working.

Liskov Principle (about 29 min)

Tuesday, April 26, 2016

c# try and catch

DO NOT DO THIS. If an exception is thrown in CallMethod() and it gets bubbled up to this try/catch, you must use “throw;” to rethrow the exception. “throw;” will preserve the stack trace while “throw ex;” will make it look like the exception originated here. This can cause much confusion when trying to debug exception statements.

try
{
    CallMethod();                         
}
catch (Exception ex)
{
    SMXLog.LogException(ex);
    throw ex;
}



 If all that is happening in the catch block is a re-throw, then you do not need this Try/Catch at all. The try/catch is redundant and does nothing extra. In the above example, it is ok to use a try/catch with “throw;” because the catch block is Logging (doing something).

try
{
   CallMethod();                      
}
catch (Exception ex)
{
    // If the only thing being done in the Catch block is a re-throw,
    // then the entire try/catch block is redundant/not needed.
    throw;  
}


     https://stackoverflow.com/questions/881473/why-catch-and-rethrow-an-exception-in-c (good overview)

http://stackoverflow.com/questions/22623/throwing-exceptions-best-practices

using just "throw" will only bubble up a message that an exception occurred at the "throw" line rather than the actual line where exception occurred.

using "throw new exception" will preserve the stack trace with exact line of fault. but need to use parameters that allow the details to bubble up.

both examples work. first is if you want to include some extra detail but not necessary as each displays a very detailed message.



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

Tuesday, September 24, 2013

SSIS package, C#, delete files greater than 10 days old

public void Main()
        {
            try
            {

                // Check the files on the folder. Delete any daily files greater than 10 days old.
                string filePath = Dts.Variables["User::DestinationFolder"].Value.ToString();
                int currentDay = DateTime.Now.DayOfYear;
                int fileCreateDay;                              

                DirectoryInfo info = new DirectoryInfo(filePath);
                FileInfo[] files = info.GetFiles();

                foreach (FileInfo file in files)
                {
                    fileCreateDay = file.CreationTime.DayOfYear;
               
                    if ((currentDay - fileCreateDay) > 10)
                    {
                        try
                        {
                            //MessageBox.Show("greater than 5 days: " + file.FullName);
                            File.Delete(file.FullName);
                        }
                        catch
                        {
                            Dts.Variables["User::WarningMessage"].Value = "Point Daily: failed trying to delete old files.";
                            Dts.Variables["User::WarningOccurred"].Value = true;
                            Dts.TaskResult = (int)ScriptResults.Failure;
                        }
                    }
                }

                Dts.TaskResult = (int)ScriptResults.Success;
            }
            catch
            {
                Dts.Variables["User::WarningMessage"].Value = "Point Daily: error in Delete Old Files section";
                Dts.Variables["User::WarningOccurred"].Value = true;
                Dts.TaskResult = (int)ScriptResults.Failure;
            }          
        }

Friday, August 30, 2013

knockout stuff

<p>Enter first name: <input data-bind="value:firstName, valueUpdate:'afterkeydown'"></input></p>

- auto updates the binding when a key is pressed in this field

Saturday, June 29, 2013

Asp.net MVC 4 - use Database First > Entity Data Model

Asp.net mvc 4, all the tutorials show simple membership being utilized with Code First (latest trend in database setup/usage). This is how to utilize simple membership with Database First using Entity Data Model.

This was discovered via a StackOverFlow.com answer: http://stackoverflow.com/questions/15112214/using-mvc-4-simplemembership-with-an-existing-database-first-ef-model

1) Create MVC 4 app and run it to create the default membership database and tables (mvc does this automatically).

2) Change .../Filters/InitializeSimpleMembershipAttribute.cs as follows:

private class SimpleMembershipInitializer
        {
            public SimpleMembershipInitializer()
            {
                //Database.SetInitializer<UsersContext>(null);

                try
                {
                    //using (var context = new UsersContext())
                    //{
                    //    if (!context.Database.Exists())
                    //    {
                    //        // Create the SimpleMembership database without Entity Framework migration schema
                    //        ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                    //    }
                    //}

                    if (!WebSecurity.Initialized)
                    {
                        WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
        }

3) Comment out sections in /Models/AccountModels.cs:

public class UsersContext : DbContext
    {
        public UsersContext()
            : base("DefaultConnection")
        {
        }

        //public DbSet<UserProfile> UserProfiles { get; set; }
        public DbSet<ExternalUserInfo> ExternalUsers { get; set; }
    }

    //[Table("UserProfile")]
    //public class UserProfile
    //{
    //    [Key]
    //    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    //    public int UserId { get; set; }
    //    public string UserName { get; set; }
    //}

4) Create an entity data model (*.edmx file) as normal.

5) In /Controllers/AccountController.cs and anywhere else where DB interaction is needed, replace as follows:

//using (UsersContext db = new UsersContext())

using (evEntities ent = new evEntities())
{
      // code to access database
}