Why you shouldn’t use a static variable in your MVC Controller

I recently came across an interesting situation where I used a static variable in a controller and it caused some issues.  The problem with statics variables is that they are not thread safe meaning that they could potentially be executed by multiple threads.

This is an issue because different users could access other users information if it is stored in a static variable.

How to build Reactive Forms in Angular2

When building forms using the Reactive approach the component class is in charge.

In order to implement this we have to:

  1. Create a property for the root FormGroup.
  2. Create the FormGroup instance.
  3. Pass in each FormControl instance.

Here is an example of how to implement this using typescript:

ngOnInit():  void(){

this.contactForm = new FormGroup({

firstName: new FormControl(),

lastName: new FormControl(),

email: new FormControl(),

sendCatalog: new FormControl(true),

});

}

The above code is not very efficient.  We can optimize it using the FormBuilder.

In order to use the FormBuilder, we have to do the following:

  1. Import FormBuilder.
  2. Inject the FormBuilder Instance.
  3. Use the FormBuilder instance.

ngOnInit():  void(){

this.contactForm = this.fb.group({

firstName: ”,

lastName: ”,

email: ”,

sendCatalog: true,

});

}

Before we can use the FormBuilder, we have to pull them into our Angular Module.

We have to do the following:

  1. Import the ReactiveFormsModule
  2. Add ReactiveFormsModule to the imports array.

@ngModule({

imports: [

BrowserModule,

ReactiveFormsModule

],

declaraions:[

AppComponent,

ContactComponent

],

bootstrap: [AppComponent]

})

export class AppModule  {}

The next step would be to bind the form element to the FormGroup property.

<form class=’form-horizon’ (ngSubmit)=”save()” [formGroup] = “ccontactForm”>

The second step is to bind each input element to its associated FormControl:

<input class=”form-control” id=”firstNameId” type=”text” placeholder=”First Name (required)” formControlName=”firstName” />

After doing all of this we now have a fully functioning reactive control!

 

 

How to setup Angular2 and ASP.NET Core from the command line

Setting up Asp.Net Core and Angular2 is actually very easy!  There are several ways to setup a project.

Before we can start using the command line, we need to install the following:

Step 1:

From the command line install the JavaScript Services generator:

npm install -g yo generator-aspnetcore-spa

Step 2:
Run the generator using the yo aspnetcore-spa command and choose Angular 2 from the list of templates.

Once the generator has completed, it will generate a complete app using asp.net core and angular2.  

You can get the app running using dotnet run.

What is the difference between Optimistic Concurrency versus Pessimistic Concurrency

Optimistic Locking is a way of versioning your record by add either a date, timestamp or hash.  If there are multiple users updating that record, the software will know if the record has changed based on the hash.  The reason for this is that you have to make sure the version is atomic.  This means that the record hasn’t been updated by another user while you were editing the value.

If the record’s version number has changed, then we can assume it is dirty and you would then abort the transaction and the user can restart the process.

Why would you use Optimistic Locking?

You would use this strategy if you application has a lot of users updating the same records at the same time or if you are using a three-tiered architecture.   If you are using a three tiered architecture then you would not be a maintaining a connection to the database for your session.  Using this architecture, the client cannot maintain a database lock because the connections are taken from a pool.

Pessimistic Locking is when the client can maintain a database lock on the record and you can lock the record exclusively for yourself until you have finished updating the record.  It has better integrity than optimistic locking; however there is major issue with Deadlocks.  In order to use pessimistic locking, you need a direct connection to the database or an externally available transaction ID than can be used independently of the connection.  You would see this design in a two-tierd client server architecture.

How to execute code from an iFrame to the parent page

I recently came across a unique situation where I had to execute code from the child iframe on the parent page.  The problem was that the iframe was calling a page from another domain.  A few years ago, this would have been easy to implement because all browsers allows cross site scripts to execute code; however, this was huge security problem.  Hackers could execute code on a remote website and steal peoples information so they blocked cross site script execution.

The only way around this is to use the Cross Document Messaging API.  This api uses the publisher-subscriber design pattern.

The first step is setting up the parent page that has the code you wish to execute from the child page:

Below is the code to place onto the parent page:

<script>
var eventMethod = window.addEventListener ? “addEventListener” :“attachEvent”;
var eventer = window[eventMethod];
var messageEvent = eventMethod == “attachEvent” ? “onmessage” :“message”;

// Listen to message from child window
eventer(messageEvent,function(e) {
if(e.data == “changeParentBackgroundToBlue”)
{
document.body.style.backgroundColor = “blue”;
}
},false);
//This will allow you to change the background color of the child page
window.document.getElementById(“myIFrame”).contentWindow.postMessage(“changeChildBackgroundToRed”,“*”);
/*postMessage second parameter represents the domain name to which this message can be sent to, if the child domain name doesn’t match then this message will not be sent. Here * means any domain */
</script>

The second step is to call the method from the Child page:

<script>

//The sets up the event listener on the client page.

var eventMethod = window.addEventListener ? “addEventListener” :“attachEvent”;
var eventer = window[eventMethod];
var messageEvent = eventMethod == “attachEvent” ? “onmessage” :“message”;

// Listen to message from child window
eventer(messageEvent,function(e) {
if(e.data == “changeChildBackgroundToRed”)
{
document.body.style.backgroundColor = “red”;
}
},false);
//This is the code that call the parent page function
window.parent.postMessage(“changeParentBackgroundToBlue”,“*”);

</script>

 

Check the number of occurrences in two Integer variables

I was recently asked to create a program that checks the number of occurrences within 2 separate integer variables.   I wrote a program using pseudo-code that uses the .Contains method.  It is possible to use the method if you import the System.Linq library.

The first way to check an integer array is Array.indexOf() method and the second way is using the .Contains() method.

Below is an example of how to do this:

There other way to check the integer array is to use the .Contains method.

Below is an example that use the .Contains method:

The third way to check is to use a Lambda expression. This is probably the most complex way to check but it definitely the coolest!

How to check if a variable is a Palindrome

What is a Palindrome?
Google defines a Palindrome as:

pal·in·drome
ˈpalənˌdrōm/
noun
  1. a word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run.

I was recently asked to write a program that checks whether a particular variable is a palindrome or not.

Below is a little console app that displays where the variable is a palindrome:

Understanding what happens during a complex LAMBDA query.

LAMBDA expressions were introduced in C# 3.0 (.NET 3.5) along with LINQ.  The LAMBDA expression is a shorter way of representing anonymous methods using special syntax.

For example, the following anonymous method checks if the customers balance is over $1000:

Anonymous method in C#:


The above anonymous method can be rewritten using the following:

Lambda Expression in C#:

c => c.Balance > 1000

Below is a more complex LAMBDA expression:

Whats the difference between Expression> and Func<>?

The key differences between the two are following:

Expression<Func<…>> is an expression tree which represents the original source code (it is stored in a tree-like data structure that is very close to the original C# code). In this form, you can analyze the source code and tools like LINQ to SQL can translate the expression tree (source code) to other languages (e.g. SQL in case of LINQ to SQL, but you could also target e.g. JavaScript).
Func<…> is an ordinary delegate that you can execute. In this case, the compiler compiles the body of the function to intermediate language (IL) just like when compiling standard method.

Func<T> creates an executable function.

Expression<Func<T>> creates an expression tree that allows you to work with the code in the function as data.

Expression Trees allow you to do things like LINQ to SQL and LINQ to XML by generating the underlying calls from your .NET code.

Whats the difference between IEnumerable and IQueryable?

The main difference between the 2 is that of efficiency:

  • IEnumerable will return all the records at once.
  • IQueryable will return only records that you want based on a filter that executes on the server.

How does each work?

Let’s assume that you have a customer table with all your customer’s information with about 10000 clients.

  • If you use IEnumerable to get the first 10 customers you end up loading all 10000 and then selecting the first 10.
  • With IQueryable you only select the first 10

Below is an example on the 2 main differences using C#:

static void Main(string[] args)
{
    using (var db = new Context())
    {
        IEnumerable<Customer> customers = db.Customers.Take(10).ToList();
        // ToList() executes the query straight away
        // All the list of customers are loaded into memory (10000 customers )
        // After that, only the first 6 are selected
        IQueryable<Customer> _customers = db.Customers.Take(10).ToList();
        // ToList() executes the query straight away
        // The first 6 customers are loaded into memory
    }            
}

What is the use of IEnumerator in C#?

IEnumerable is an interface that defines one method GetEnumerator which returns an IEnumerator interface, this in turn allows readonly access to a collection.  A collection that implements IEnumerable can be used with a foreach statement.

What is IQueryable in C#?

IQueryable is an interface that implements IEnumerable (and because it implements IEnumerable it means that it allows you to iterate over a collection plus some more) IQueryable takes Expression objects instead of delegates (which is what IEnumerable takes)

When can I use IEnumerable?

  • When you want to iterate over a collection (List, Arrays, etc.)
  • When you want to get all the results from your query and apply any further filtering once your collection has been loaded in memory.
  • When you are using LINQ to XML or LINQ to Object.

When can I use IQueryable?

  • When you want to iterate over a collection (same as IEnumerable)
  • When you want to work with data from out-memory, such as a database, a web service etc
  • When you want to apply a filter to your query BEFORE the query is executed (this can save you heaps of resources)
  • When Lazy loading is needed (you only get what you need, not the entire list of records)