INTERVIEW JOB CODING TASKS – Calculate permutations

Today we are going to continue with interview coding tasks.

I really do hope this, solved, coding task is going to help you during your interview.

Task: Depending on input value i.e. (123) create all permutations i.e:(123,213,231,132,312,321)

Solution:


private static void Main(string[] args)
{
	WritePermutations();
        Console.ReadLine();
}
public static void WritePermutations()
{
	var permutations = GetPermutations("123");

	foreach (var permutation in permutations)
	{
		Console.WriteLine(permutation);
	}
}
public static List<string> GetPermutations(string inputString)
{
	return IsPermutated(inputString, out var permutations, out var list) ? list : ListOfPermutations(inputString, permutations);
}
private static bool IsPermutated(string inputString, out List<string> permutations, out List<string> list)
{
            permutations = new List<string>();
            list = null;

            if (inputString == null) return true;
            if (inputString.Length != 0) return false;
            
            permutations.Add("");
            {
                list = permutations;
                return true;
            }
}

private static List<string> ListOfPermutations(string inputString, List<string> permutations)
{
	var firstCharacter = inputString[0];
	var remainder = inputString.Substring(1);
	var words = GetPermutations(remainder);
	foreach (var word in words)
	{
		for (var i = 0; i <= word.Length; i++)
		{
			permutations.Add(InsertCharacterAt(word, firstCharacter, i));
		}
	}

	return permutations;
}
public static string InsertCharacterAt(string word, char character, int i)
{
  var start = word.Substring(0, i);
  var end = word.Substring(i);
   return $"{start}{character}{end}";
}

Cheers

How-To setup global exception handler in .NET Core?

Today I’ll try to be precise and straight to the point as possible.
If you want to simplify your code by removing unnecessary try {} catch {} blocks of your code inside API Controllers, then you probably want to use some kind of global hook in which you are going to handle global exceptions.

The way we utilize global exception handler in .NET Core API is like this:

Startup.cs -> Configure method:

app.UseExceptionHandler(builder => { builder.Run(async context =>
{
     context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
​
     var exceptionHandler = context.Features.Get<IExceptionHandlerFeature>();
​
     if (exceptionHandler != null)
     {
          await context.Response.WriteAsync(exceptionHandler.Error.Message);
     }
​
}); });

But this way we did not set up our CORS headers we only set our error message.

Add IHttpResponse extension

So to fix our CORS headers we need to add an extension which is going to do just that, set our CORS headers. We will also add the possibility to set our custom error message as well.

The way we do it, is like this:

public static class Extensions
{
    public static void AddApplicationExceptionHandlerCorsHeaderWithMessage(this HttpResponse httpResponse, string customErrorMessage)
    {
        httpResponse.Headers.Add("Application-Error", customErrorMessage);
        httpResponse.Headers.Add("Access-Control-Expose-Headers", "Application-Error");
        httpResponse.Headers.Add("Access-Control-Allow-Origin", "*");
    }
}

And now we have proper global exception handler set up with CORS and header error message.

FINAL RESULT:

app.UseExceptionHandler(builder => { builder.Run(async context =>
{
     context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
​
     var exceptionHandler = context.Features.Get<IExceptionHandlerFeature>();
​
     if (exceptionHandler != null)
     {
          var errorMessage = exceptionHandler.Error.Message;
 
 context.Response.AddApplicationExceptionHandlerCorsHeaderWithMessage(errorMessage);
     await context.Response.WriteAsync(errorMessage);
    }
​}); });

INTERVIEW JOB CODING TASKS – Calculate Tree depth and a number of leaves

Season 1 – Prologue

So… You want to get that developer job, right?

You are preparing (or not) yourself and You pass all the “theory” questions. And then You are assigned more stuff to do…You get a bunch of coding tasks to complete. It seems so exhausting and daunting to do. It takes time and You are probably working somewhere and have a life of course. But the future employer doesn’t care and wants You to complete these tasks so You can be evaluated.

Well, to make your future interviews a little bit less stressful, I’ll share some of the most common interview coding tasks with You!

So You can, yes – You guessed it, have a life also and not just worry about some XYZ employer results. Which, if you are lucky, will give you some feedback after the whole process and will not behave like a black hole in a universe (like, thanks for the input, but completely lacks the output / their response).

I really don’t know if anyone of you were “victims” of a bad future wannabe employer, in a sense that they disrespected your precious time. Like having a marathon 5+ hours interview and then looping it for a few days and finally when this exhausting marathon is over, they don’t give you any response. Or worse, they say like: “Oooh, great! Everything looks fine and perfect, we think you are a match! We will give you an offer for sure.” and then nothing. Days passed, weeks passed, months passed and still nothing! And You are like wtf!?

I know for sure these things happen. It happened not just to me, but also to a bunch of guys I know!

So to spare your precious time I’ll be sharing coding tasks with you.

Please feel free to send me your coding tasks and I will gladly solve them for you.

Let’s make together a solid base of possible interview coding tasks so we can ease life for future developer interviews.

Task 1: Find the depth of a tree and the number of leaves for a defined “path” in an existing tree.

We have an already defined tree like this one:

Text Box

Each element of this string array is representing a node. Parent node is defined as a element in a row, followed by other node which is parent node of the next node. Root element is defined by “-1”.

So, root element is 5, and it is a parent to 6, 2 and 0 nodes. Node 2 is parent to 1 and 3. Node 1 is parent to 4.

If you enter in command prompt: “your_compiled_app.exe 5 2 5 2 1 -1 5 0” result is going to be:

Tree height: 3 Number of leaves: 4

Let’s get to the business – show me the code

Model:

public class TreeNode<T>
{
    public T Data { get; set; }
    public TreeNode<T> Parent { get; set; }
    public List<TreeNode<T>> Children { get; } = new List<TreeNode<T>>();
}

Extensions:

public static class StringArrayExtensions
{
    public static List<int> ConvertArrayOfStringsToListOfIntegers(this string[] array)
    {
        return Array.ConvertAll(array, int.Parse).ToList();
    }
}
public static class TreeNodeExtension
{
    public static int TreeHeight<T>(this TreeNode<T> root, int depth)
    {
        var result = depth;
​
        foreach (var node in root.Children)
        {
            result = Math.Max(result, TreeHeight(node, depth + 1));
        }
​
        return result;
    }
​
    public static int LeafCount<T>(this T rootNode, Func<T, IEnumerable<T>> childrenF)
    {
​
        return EnumerateLeaves(rootNode, childrenF).ToList().Count;
    }
​
    private static IEnumerable<T> EnumerateLeaves<T>(this T rootNode, Func<T, IEnumerable<T>> childrenF)
    {
        var children = childrenF(rootNode);
​
        var hasChildren = children != null && children.Any();
​
        if (!hasChildren)
        {
            yield return rootNode;
        }
        else
        {
            foreach (var node in childrenF(rootNode))
            {
                foreach (var child in EnumerateLeaves(node, childrenF))
                {
                    children = childrenF(child);
                    hasChildren = childrenF(child) != null && children.Any();
                    if (!hasChildren)
                    {
                        yield return child;
                    }
                }
            }
        }
    }
}

Main program:

static void Main(string[] args)
    {
        if (args.Length <= 0) return;
​
        var indexList = args.ConvertArrayOfStringsToListOfIntegers();
​
        var unLinkedTreeNodes = new List<TreeNode<int>>();
​
        for (var i = 0; i < indexList.Count; i++)
        {
            unLinkedTreeNodes.Add(new TreeNode<int>(){ Data = i });
        }
        
        TreeNode<int> rootNode = null;
        var linkedTreeNodes = new List<TreeNode<int>>();
​
        linkedTreeNodes = unLinkedTreeNodes;
​
        for (var index = 0; index < indexList.Count; index++)
        {
            var nodeName = indexList[index];
​
            var isRootNode = (nodeName == -1);
​
            if (isRootNode)
            {
                var parent = unLinkedTreeNodes[index];
                rootNode = parent;
            }
            else
            {
                var unlinkedNode = unLinkedTreeNodes[index];
                unlinkedNode.Parent = linkedTreeNodes.FirstOrDefault(n => n.Data == nodeName);
​
                linkedTreeNodes.FirstOrDefault( n => n.Data == nodeName)?.Children.Add(unlinkedNode);
            }
        }
​
        var treeHeight = rootNode.TreeHeight(0);
        var leafCount = rootNode.LeafCount(root => root.Children);
​
        Console.WriteLine($"Tree height: {treeHeight}");
        Console.WriteLine($"Tree number of leaves: {leafCount}");
​
        Console.ReadLine();
    }

Conclusion

This is only the beginning. More to come soon. If you have any questions regarding this, feel free to message me, mail me etc..

As stated before, feel free to send me your coding tasks and I will gladly solve them for you.

Let’s make together a solid base of possible interview coding tasks so we can ease life for future developer interviews.

Asynchronous Programming

Have you ever been irritated by unresponsiveness of GUI? Clicking something and then waiting for GUI to get responsive again? If so, you have probably been a victim of synchronous programming. 🙂

So let’s scrape synchronous programming and say “Hi!” to asynchronous programming in C#.

Why use Asynchronous programing?

  • To implement better GUI usability.
  • To make our code easier to understand and write.

Aren’t there already ways to do asynchronous development? Well try using callbacks or threads. I guess you want be that much satisfied while writing your code, trying to figure it out and debugging.

When to use Asynchronous programing?

If you want to do any cost operations like accessing database or doing any kind I/O operations on files etc.

Luckily, .NET provides us with a bunch of async methods, which we can use easily inside our own methods.

How do we code?

Easy. By using these keywords:

  • async
  • await

and these methods which we combine with above keywords:

  • Task
  • Task<T>

So each method has to have async and Task/Task<T> as footprint and await inside body method. If you don’t have await it will simply pop you an error and your code won’t compile.

Show me the code!

public async Task<int> RetrieveNumberOfHoursAsync(){
   return await SomeExternalMethod.GetHoursAsync();
}

In above example, when we trigger our RetrieveNumberOfHoursAsync() method, our inbody function will fire up but won’t block the main thread. When all hours from SomeExternalMethod are retrieved, only then will our method trigger up the results back.

Let’s make it more clear:

public async Task<int> RetrieveNumberOfHoursAsync(){
    int hours = await SomeExternalMethod.GetHoursAsync(); // line 1
    Console.WriteLine("I won't execute until I get the results from SomeExternalMethod()"); // line 2
    return hours;
}

So what the above code does is, it triggers SomeExternalMethod() and stops from further executing.

So at first RetrieveNumberOfHoursAsync() call, only line 1 will execute. Then, only when SomeExternalMethod() is able to complete retrieving all hours, will line 2 be executed.

Let’s make it even more clear:

public async Task<int> RetrieveNumberOfHoursAsync(){
   Task<int> getHoursTask = SomeExternalMethod.GetHoursAsync(); // line 1
   Console.WriteLine("I will execute immediately"); // line 2
   int hours = await getHoursTask; // line 3
   Console.WriteLine("I won't execute until I get the results from SomeExternalMethod()"); // line 4
   return hours;
}

Triggering our method RetrieveNumberOfHoursAsync() we are going to create a Task<int> getHoursTask, (line 1) but we won’t execute it right away. Instead, we still want to do some additional stuff (line 2) before executing our newly created task (line 3). Only when our getHoursTask is finished with retrieving hours, will our message be written to console (line 4) and return number of hours.

Conclusion

Using async/await operators we make our code easier to read and maintain. It’s pretty easy to use and code with async/await. Anyways, there is a lot more to Task class than written here. Since you can use built in methods of Task class to do a bunch of manipulations with async methods. But I will leave this as homework for you. Go figure it out and make code cleaner and apps more user friendly!

All about Task class

In case you want to read little more about Task class itself, please visit it here: https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task?view=netframework-4.8

IAsyncEnumerable in .NET C# 8.0

OOOOPS…I DID IT AGAIN!?

I want to apologize for not respecting and failing my deadlines, with writing a new post every two weeks. I received a bunch of e-mails from you guys asking me when will my next post be published.
So I feel responsible to point out to you that I’m currently very, very busy working on a bunch of projects. I am also preparing some cool new digital content for you which is going to enhance the overall learning experience of a vast .NET world.

I also want to seize this opportunity and say big THANK YOU for supporting me and giving me the reason to publish more and more content.

Now let’s dive into today’s topic.

In my previous post, I wrote about collections in C#. It was an intro to today’s post, as I stumbled upon some cool new feature inside C# 8.0.

Maybe some of you are already aware of this new cool feature, but I guess most of the people are not.

WHAT’S THAT?

It’s the new addition to C# 8.0 which is also called *async streams* (more about it at https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/async-streams?WT.mc_id=devto-blog-antchu). If you are not aware of this, let’s dive a little deeper of what it does and why it’s useful.

IN SHORT

It is intended to replace Task<IEnumerable>.

WHY?

To retrieve data asynchronously from our DB or API and stream those results back as they become available.

SHOW ME THE CODE!

If it’s still unclear what it does, it’s okay! We will take a look at an example.
Let’s imagine we are building some DAL and need to create a function which queries data or some kind of API. Probably you will end up with using Task<IEnumerable<T>> and create something like this:

public async Task<IEnumerable<Project>> GetAllProjects()

And in GetAllProjects() method you will probably have something like this:

public async Task<IEnumerable<Project>> GetAllProjects()
{
    ...
    var iterator = ...;
    var projects = new List<Project>();
    while (iterator.HasMoreResults)
    {
        foreach (var project in await iterator.ReadNextAsync())
        {
            projects.Add(project);
        }
    }
    return projects
}

Using this way our code will work but it will work inefficiently!
Just imagine working with a large amount of data.

Hint: Sloooooow…

If you are about to tweak this a little bit, you are probably going to end up with returning IEnumerable< Task<IEnumerable<Project>>>.

But this is a counterintuitive way because it’s not obvious how do we invoke this method and work with resulting data.

Oh, now what!?

You are probably thinking on how to bypass all this fuss and you came up with this, great, great idea!!!

AHAAA moment!

Iterator has a ReadNextAsync method, let’s use it Luke!!

public IEnumerable<Project> GetAllProjects()
{
    ...
    while (iterator.HasMoreResults)
    {
        foreach (var project in iterator.ReadNextAsync().Result)
        {
            yield return project;
        }
    }
}

Again, if you are about to solve the issue by using above mentioned code, think twice! Don’t go that way. You will eventually end up blocking your code.

IAsyncEnumerable<T>

So here is where the new feature really shines up!

We create our method like this:

public async IAsyncEnumerable<Project> GetAllProjects()
{
    ...
    while (iterator.HasMoreResults)
    {
        foreach (var project in await iterator.ReadNextAsync())
        {
            yield return project;
        }
    }
}

And we consume it like this:

await foreach (var project in projectRepo.GetAllProjects())
{
	// do whatever you want with "project" object...
}

CONCLUSION

As you can see, this new feature gives us much cleaner and efficient code.
So please use it as it’s really,really,really great feature.

Thanks for reading and stay tuned for some more cool content to come!

Collections in C#

Today I’ll be writing about collections in C# and eventually in my next blog post I’ll be writing about some new cool feature in .NET Core 3.0.

But let’s first focus on collection basics in C#.

What is a collection?

It’s a container which can hold some items.

Types of collections

In case you don’t know, there are several types of collections in C#:

  • IEnumerable
  • IQueryable
  • ICollection
  • IList

Although they are basically the same, each of them has specific characteristics and is used in certain scenarios.

Collections in C#

As you can see in a picture above, IEnumerable is the starting class.
All other classes derive from it.

You might ask yourself, why IQueryable is moved left in the picture.
Why isn’t it located, as the rest of the collections, directly under the IEnumerable!?

Well mostly because, this way it’s easier to show you that IQueryable is located in a different namespace.

While IEnumerable, ICollection and IList is located in System.Collections, IQueryable is located inside System.Linq namespace.
I will explain later why!

System.Collections

IEnumerable

So as defined above, IEnumerable is a base class which represents a container. It’s located under System.Collections namespace.
Using this type of a collection you can not add, edit, delete or count items after initial load of items. This way we prevent any modification to our items. We use this container just to contain a list of items and nothing more. In order to count our elements inside this type of a collection, we need to implement IEnumerator.

i.e.:

public class BankAccount: IEnumerator 

{  

   public object Current 

   { 
​    get { throw new NotImplementedException(); } 

   } 

    public bool MoveNext() 

   { 

​    throw new NotImplementedException(); 

   } 

    public void Reset() 

   { 
​    throw new NotImplementedException(); 
   } 

} 

ICollection

This is a IEnumerable derived class with a little bit more functionalities added in it. Using this class we are able to add, edit, delete and count elements in the container.

You will mostly see this kind of collection when dealing with Entity Framework. Since it doesn’t have so much overhead.

IList

This type of collection derives from ICollection. Said that, it means, it has all specifics of IEnumerable and ICollection plus some additional functionalities like insert or delete of an element in the middle of a list. It’s the easiest collection and probably the most used type of a collection. But it’s overhead makes it not performance king.

IQueryable

And finally we have this kind of a collection. And the main difference between this collection and the other is that when accessing database it generates LINQ to SQL expression which is executed over the database layer.

Final verdict: IEnumerable vs IQueryable

There are some key differences between these two types of collections. I will sum-up them in a table below.

But one of the biggest differences which is necessary to grasp is the way each of the two queries data.

While IEnumrable is suitable for querying in-memory collections like arrays,lists etc, IQueryable is suitable for querying out-memory colelctions like some service,remote databases etc.

Why?

When using IEnumerable to query database, we execute “select query” on the server side then load that data into in-memory on the client side and only then we filter data.

On the other side, when using IQueryable we execute “select query” with all the filters on the server side and return already filtered data.

As you can see it’s much performance-wise to use IQueryable when retrieving filtered data from a database.

IEnumerableIQueryable
Namespace: System.CollectionsNamespace: System.Linq
Queries: IN-MEMORYQueries: OUT-MEMORY
DB: “Select query” on the server, filters on the client side DB: “Select query” and filters on the server side
Beneficial: LINQ to OBJECT or LINQ to XMLBeneficial: LINQ to SQL

Entity framework strategies when loading data

There are several types of loading data using Entity Framework.
Those are:

  • Lazy Loading
  • Eager Loading
  • Explicit Loading

You will also come across one problem when using one of EF strategies.
That is N+1 problem.

But more on that later. Let’s talk about types of loading in EF!

Lazy loading

It’s used to retrieve data which is needed on demand.
This makes loading a data less heavy for our app.

But there is always a but. Skip to When to use lazy loading if you want to know asap!

First, let’s take a look at our example.

I.e.: imagine we have a class like this one:

class Company {

​	public virtual ICollection<Project> Projects {get;set;}

}

As you can see, to enable lazy loading for our property we used virtual keyword.

In our app logic we have something like this:

var context = new AppContext();

var company = context.Company.Single(c=>c.Id == 13);

foreach(var project in company.Projects){

​	Console.WriteLing(project.Name);

}

Whenever we use Single, SingleOrDefault, First, FirstOrDefault, Max or Count we immediately cause query execution.

But in our case, company doesn’t have Projects initialized.

So in our foreach block, EF will send additional query to the DB to get what we need, in this case Projects is what we need.

As you can see, we use here Lazy Loading. Since Projects are not loaded immediately but loaded when we need to access them.

When to use lazy loading

We use lazy loading only when we expect to have a big number of data which would potentially slow down our app when retrieving data.

Use it only in desktop applications since in web apps we don’t have context object living in the memory while we are requesting data over rest services.


Thus said, using lazy loading would decrease our web app performance due to unnecessary round trips.

Disabling lazy loading

  1. By not using virtual keyword for property.
    1. which is complicated while we need to take care for each navigation property to follow this rule
  2. By configuration
    1. In AppContext() constructor we add this line of code:
this.Configuration.LazyLoadingEnabled = false; 

Eager Loading

It’s of course, the opposite thing from Lazy Loading. Which means that data is prefetched from the DB.

In our example we want to prefetch data for Project Manager. And there are two ways to achieve this.

The good way and the bad way!

The bad way:

var context = new AppContext();

var projects = context.Projects.Include("Manager").ToList();

foreach(var project in projects){

​	Console.WriteLing(project.Name, project.Manager.Name);

}

Why is this the bad way?

Well, it’s obvious we use magic string here. So typo might happen or perhaps our property isn’t named that way and our code would break!

So to avoid this kind of mistakes we will use System.Data.Entity namespace and use lambda expression.

The good way:

var context = new AppContext();

var projects = context.Projects.Include( p => p.Manager).ToList();

foreach(var project in projects){

​	Console.WriteLing(project.Name, project.Manager.Name);

}

Why is this the good way?

If for some reason our property changes we would be given an compile error. So it’s much easier to debug and fix the problem!
Additionally when using refactor inside Visual Studio, we could easily rename it (which is not the case with magic string).

The negatives

If using too many Includes a lot’s of data would eventually end up in memory. And perhaps we don’t need all that data.

Explicit Loading

We use it when using Eager Loading are becoming more and more complex!

So this way we manually preload data which we need.

Main differences between Eager Loading and Explicit Loading:

Eager LoadingExplicit Loading
uses joinsmultiple queries
one round tripmultiple round trips

Here is an example:

var context = new AppContext();

var manager = context.Manager.Single( m => m.Id = 3);

context.Projects.Where( p => p.ManagerId == manager.Id).Load(); // hence using LOAD() method

foreach (var project in manager.Projects){

​	Console.WriteLing(project.Name);

}

Benefits

We get much simpler query since we avoid using bunch of joins inside our query.

We can apply filters.

Negatives

Multiple round trips to the database. Which maybe in some cases might be more efficient than one query with multiple joins.

N+1 problem

Is a common problem when using lazy loading and getting N entities with their related entities. Since we will end up with N+1 queries.

I.e.:

var context = new AppContext();

var projects = context.Projects.ToList(); // this is query number 1

foreach (var project in projects){ // foreach each project we will get additional query (lazy loading) to retrieve Manager and his name

// this means if we have N projects we will end up with N queries for projects and that above +1 query to retrieve all projects

​	Console.WriteLing(project.Name , project.Manager.Name);

}

Negatives

Using lazy loading and causing this kind of problem means we will end up with bunch of unnecessary queries which will overload our database and cause performance issues.

Final words

Which strategy to use and when depends solely on a specific situation and a developer. So each developer should be aware of a potential performance issues when choosing appropriate strategy.

EXPRESSION TREES – What, When and How ?

Hi there!

Due to the lack of time and a bunch of projects I’m working on in parallel, I’ve decided to publish every two weeks a new post.

In my last post I was writing about generic filter in which I used expression trees.

So let’s clarify what expression tree is!?

What is it all about?

It’s all about data which represents our code in a tree like structure.

Expression tree ( Expression<>) is a not-compiled data which represents our code. It’s a blueprint of what we want to achieve using LINQ.

So what the compiler does is, it takes Expression type(which is btw strongly typed lambda expression) and compiles it into Expression tree instead of executable code.

This way we can build our own code and later execute it when we want to!

When should we use it?

Good example of usage is described in my previous post, creating generic filter.

Since we want to build our filter based on dynamic number of properties, we should firstly create our filter and then compile it and execute it.

We can easily break down our code in multiple LINQ queries and glue it all together to get our final result.

Building blocks of Expression Tree

Expression tree consists of:

  1. Parameters
  2. Body
  3. NodeType
    1. Lambda
    2. Constant
    3. Parameter
    4. Equal
    5. AndAlso
    6. GreaterThan
    7. MemberAccess
    8. … (complete list is here: https://docs.microsoft.com/en-us/dotnet/api/system.linq.expressions.expression.accept?view=netframework-4.8)
  4. Return Type

Example

So, to build an expression tree we need to:

  1. pass parameters
  2. create a body expression
  3. create nodetype and pass body expression with parameters
  4. define return type
  5. compile() our expression tree
  6. execute

Simplified example

// 1. create parameters
ParameterExpression param1 = Expression.Parameter(typeof(int), "param1");
ParameterExpression param2 = Expression.Parameter(typeof(int), "param2");
  
// 1. create parameters
ParameterExpression[] parameters = new ParameterExpression[] { param1, param2 };
  
// 2. create body expression
BinaryExpression bodyExpression = Expression.Subtract(param1, param2);
  
// 3. create the nodetype and pass body expression 
Expression<Func<int, int, int>> expression = Expression.Lambda<Func<int, int, int>>(bodyExpression, parameters);
  
// 4. defining return type and 5. compile the expression
Func<int, int, int> compiledExpression = expression.Compile();
  
// 6. execute  
int result = compiledExpression(10, 3); //returns 7

Final thoughts

The example above is simplified, so you could get the clear picture how does it work. Expression trees can get a bit more complex but this is the way they work.

In case you read my previous article, you might have a question what ExpressionVisitor is!?

To learn more, please read ahead.

P.S. ExpressionVisitor

What’s that?

It’s a special class used inside Expression trees to modify tree structure, based on Visitor pattern.

Why should I try to modify immutable tree structure?

In some cases you want to operate with different types inside .Where() clause. To achieve this you will need to use ExpressionVisitor to make some modifications.

I.e. no.1

If your database has some fields containing (0,1) and you want to operate with flag which is of type bool. You will implement ExpressionVisitor to change property and be able to use it inside .Where() clause.

I.e. no.2

Switching from one database to another MS SQL -> SQLite. Some things are different inside database and if you don’t want to change your DAL, you just add some ExpressionVisitor and do the modifications you need to completely switch to SQLite.

What is MVVM and how to implement it?!

Hi there! It’s been a while since I wrote my last article due to summertime madness. Little digression, if you are into summertime and jazz, listen to this great jazz performance by Ella Fitzgerald.

What I really needed was some offline time to regenerate and prepare some great new content. So by starting from today, I’ll be back at posting regularly.

Okay, let’s had back to our today’s topic. What is MVVM and how do we implement it?

MVVM in a nutshell

It’s an architectural pattern for implementing user interfaces (UIs) and stands for “Model View ViewModel” (hence capital letters MVVM).

For more on how to implement MVVM in Xamarin apps please read: Part1 and Part2 of building Xamarin apps with Prism.

M or Model

Encapsulates business objects, domain models or data models.

V or View:

Represents something that user sees (page or form).

VM or ViewModel

Is a model specifically tied to a view.
In a nutshell it’s a POCO class with properties which holds everything represented on a view (state, data, methods…)

It really is similar to code behind (if you ask yourself that question) but unlike code behind, is not tightly coupled and is unit testable.

So as you can see, some similarity does exist but fundamentally they are completely different.

When to use MVVM?

Only if you want your application to be unit tested regarding presentation logic and if you are creating a complex application.

How to implement MVVM with C#?

I will show you how to implement MVVM in Xamarin by using C#.
There are 3 ways to implement it.

  1. By writing a bunch of code by yourself (least interesting)
  2. By using Alexandre Chofi BaseViewModel class
  3. *By using Nuget library Fody PropertyChanged

As you might have seen * in 3rd bulletin, this is my favorite type of MVVM implementation, thus far!

Why?
I like simple things, period.

Everything that is providing simplification (without sacrificing any usefulness) I will gladly embrace!

Traditional MVVM by using INotifyPropertyChanged

public class PersonFormViewModel : INotifyPropertyChanged  
    {  
        public event PropertyChangedEventHandler PropertyChanged;  
     
        private string _name;  
        public string Name
        {  
            get  
            {  
                return _name;  
            }  
            set  
            {  
                if (_name!= value)  
                {  
                    _name= value;  
                    NotifyPropertyChanged();  
                }  
            }  
        }  
   
        private int _age;  
        public int Age  
        {  
            get  
            {  
                return _age;  
            }  
            set  
            {  
                if (_age!= value)  
                {  
                    _age= value;  
                    NotifyPropertyChanged();  
                }  
            }  
        }  
		
	protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = "")  
        {  
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));  
        }  
    }  

MVVM by using Alexandre Chofi created base class

public class AlexandreChofiPersonFormViewModel : BaseViewModel  
    {  
        private string _name;  
        public string Name
        {  
            get  
            {  
                return _name;  
            }  
            set  
            {  
                SetProperty(ref _name, value);  
            }  
        }  
   
        private int _age;  
        public int Age  
        {  
            get  
            {  
                return _age;  
            }  
            set  
            {  
                SetProperty(ref _age, value);  
            }  
        }  
    }  

His BaseViewModel class:

public class BaseViewModel : INotifyPropertyChanged  
    {  
        public event PropertyChangedEventHandler PropertyChanged;  
   
        protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)  
        {  
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs((propertyName)));  
        }  
   
        protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)  
        {  
            if (EqualityComparer<T>.Default.Equals(storage, value))  
            {  
                return false;  
            }  
            storage = value;  
            OnPropertyChanged(propertyName);  
   
            return true;  
        }  
    }

MVVM by using Nuget library FodyPropertyChanged (my favorite way of implementing MVVM)

[ImplementPropertyChanged]  
    public class FodyPersonFormViewModel  
    {  
        public string Name { get; set; }  
        public int Age { get; set; }  
    }  

CONCLUSION

I hope you see why the latter is by far my favorite way of implementing MVVM.
You just need to annotate your ViewModel class and voila!

MVVM is really useful but not in all cases (i.e. quick prototyping).
By using some of the above mentioned ways, you could really use it anytime and anywhere though.

Just don’t repeat yourself and use what others already implemented and tested in real case scenarios. So I highly recommend using the 3rd way.

As always, if you have any doubts or questions, don’t hesitate to contact me via any of the listed social networks or email!

Cheers!