MVC Architecture

MVC architecture has been in place since past 4 decades or so when GUI (Graphical Use Interfaces) started to be used widely. The idea is simple – to implement separation of concerns.  Plainly put, to separate 1) presentation (UI) 2) user interactions and 3) underlying data and logic/behavior. It might be easy to build a web application or any enterprise level application by putting all of these components together – making it difficult to separate – meaning increasing the risk of breaking the whole system when something changes or need to be modified for testing that does not necessarily need to change all three components. Lets say you have a need to change the UI to fit to various themes and for mobile devices. If your application is not designed well using a well versed architectural pattern where you have already separated out the basic three components of an information system, then you are probably in trouble!

Do not confuse MVC as a design pattern. MVC is not a design pattern. Examples of design pattern are the widely categorized software design patterns such as Structural (adapter, bridge, composite, decorator, facade, flyweight, proxy), Behavioral (chain of responsibility, command, interpreter, iterator, mediator, memento, observer, state, strategy, template method, visitor) and Creational (singleton, factory, abstract factory, builder, prototype).

Also, do not confuse MVC with 3-tier architecture. MVC is not 3-tier architecture. 3 tier architecture deals with actual physical separation of presentation layer, business logic layer and data layer – i.e the three layers lies on three different physical machines and runs on different processes. For eg: A UI lying on a web server, a J2EE instance running on a app. server and DB2 database lying on a database server.

MVC is an architectural pattern. It is an architectural pattern since it deals with designing a system / application in a specific way that it is architecturally separated into 3 distinct components which are not interdependent. Thus, in MVC, we separate the system into presentation/UI or Views, Controllers and Model. Views represent part of the system/application that deals with the presentation or the UI – which is basically the HTML mark up that we display to the user in a web based system. Model represent the system/application data (entities in the domain model) and its logic/behavior. Controller accepts HTTP requests from the browser/UI controls and loads appropriate data from the related model/s and put it in the respective view and return the view to the browser. In most MVC implementations, there is also a fourth component called router that determines which controller to call based on the HTTP URL.

The advantage of MVC is that we can make changes to the 3 distinct components without any impact to the other components. For example we can easily switch the system to a mobile specific view without changing the controller or model – which really means we can use different views as we need for the same business logic without touching the programs/classes that deal with business logic. Also we can write web services to replace the views to pump the data out without any changes to the model or controller. Similarly we can change the DB and make necessary changes to the DAOs and no change is needed on views or controller. Another great advantage is that it facilitates easy unit testing of the UI without having to worry about controller or model and vice-versa.

05. April 2017 by admin
Categories: Application Architecture, Architecture, ASP.NET, C#, MVC, Object Oriented Modeling and Design, Programming | Leave a comment

C# Program to find Age

Below is a C# program to find Age from a Date of Birth. Enjoy!

public class Person
   {
       public string Name { getset; }
 
       public Person(DateTime birthdate)
       {
           BirthDate = birthdate;
       }
       public DateTime BirthDate { getprivate set; }
 
       public int Age{
           
           get { 
 
               var timeSpan = DateTime.Today - BirthDate;
               var years = timeSpan.Days / 365;
 
               return years;                
           
           }
       }
 
   }
 
   public class Program
   {
       public static void Main(string[] argvs)
       {
           var person = new Person(new DateTime(1998,2,14));
           
           Console.WriteLine(person.Age);
       }
   }

30. March 2017 by admin
Categories: C#, Programming | Leave a comment

Usage of params modifier in C#

Lets see how to use params modifier in C#. The perfect example is Calculator implementation. ‘params’ access modifier when used on a method argument, allows it to accept multiple argument values. Lets see the simple Calculator implementation below. As you can see, method argument ‘numbers’ is defined as integer array and being called out by ‘params’ modified that allows it to accept more than one value.

class Calculator
   {
       public int Add(params int[] numbers)
       {
           var sum = 0;
 
           foreach (var i in numbers)
           {
               sum += i;
           }
           return sum;        
       }
   }

class PointProgram
    {
        public static void Main(string[] argvs)
        {
 
            var Calculator = new Calculator();
 
            Console.WriteLine("Sum is {0}", Calculator.Add(24344512));
 
 
        }
    }

30. March 2017 by admin
Categories: C#, Programming | Leave a comment

Constructor overloading in C#

Constructors need to be overloaded depending on what extend of data/properties need to be initialized in order to set the object to a particular state. Below a good example using a Customer / Orders example. Note that Customer constructor is overloaded in 3 different ways based on what data need to be initialized. Here we use the third implementation so we set the desired id and name for the Customer. Note how we use the this operator to recursively invoke the other constructors.

public class Order
   {
       public int OrderId;
   }

class Customer
    {
        public int ID;
        public string Name;
        public List<Order> Orders;
 
        public Customer()
        {
            this.ID = 2131;
            this.Name = "John Smith";
            this.Orders = new List<Order>();
        }
 
        public Customer(int id)
            : this()
        {
            this.ID = id;
        }
 
        public Customer(int id, string name)
            : this(id)
        {
            this.Name = name;
        }
    }
 
    class Program
    {
        public static void Main(string[] argvs)
        {
            var Cust = new Customer(45345"James");
            
            Cust.Orders.Add(new Order() { OrderId = 123 });
            Cust.Orders.Add(new Order() { OrderId = 456 });
            Cust.Orders.Add(new Order() { OrderId = 789 });
            Console.WriteLine("Customer " + Cust.Name + " (" + Cust.ID + ") has below
 orders >\n");
            foreach (var i in Cust.Orders)
            {
                Console.WriteLine(i.OrderId + "\n");
            } 
 
        }
 
    }


30. March 2017 by admin
Categories: C#, Programming | Leave a comment

Using LINQ in C#

LINQ or Language
Integrated Query
gives the capability to query objects and C# allows two distinctive ways to achieve this – You can either use LINQ query operators model or LINQ extension methods model with Lamba expressions on Func<> delegate.
We have – 

LINQ to Objects – Objects in memory eg:
Collections
·      
LINQ to Entities – eg: Databases
·      
LINQ to XML – eg: XML
·      
LINQ to Data sets – ADO.NET data sets

Example

We have a Book class and a Book repository that will hold a
list of Books. In the main program we will use LINQ to so some operations on
the Book list.
Book
public class Book
    {
        public string Title { getset; }
        public float Price { getset; }
    }
BookRepository –
returns a list of predefined Books
public class BookRepository
    {
        public IEnumerable<Book> GetBooks()
        {
            return new List<Book>
            {
                new Book() { Title = "ABC", Price = 20.50f },
                new Book() { Title = "DE", Price = 30},
                new Book() { Title = "RE", Price = 20},
                new Book() { Title = "YE", Price = 50},
                new Book() { Title = "WEE", Price = 34},
                new Book() { Title = "SDE", Price = 40}
            };
        }
    }
Main program
class Program
    {
        static void Main(string[] args)
        {
            var books = new BookRepository().GetBooks();
 
            //LINQ Query Operators
 
            var cheapBooks =
                from b in books
                where b.Price > 30
                orderby b.Title
                select b.Title;
 
            //LINQ Extension methods
            var cheaperBooks = books
                                .Where(b => b.Price > 30)
                                .OrderBy(b => b.Title)
                                .Select(b => b.Price);
            //returns one or 0 items.Single returns 1 and 
only1 item
            var singleBook = books.
                   SingleOrDefault(b => b.Title 
== "WEE");
 
            //returns first item from the match
            var firstItem = books.
                        FirstOrDefault(b => b.Price > 30);
 
            //returns last item from the match
            var lastItem = books.
                      LastOrDefault(b => b.Price > 30);
 
            //return skip some and next few
            var skipItems = books.
                                Skip(2).Take(3);
 
            //Count items
            var cnt = books.Count();
 
            //Max, Min, Sum
 
            var max = books.
                            Skip(2).Take(4).Max(b => b.Price);
 
           //var item = books.Aggregate(b => b.Price);
 
            foreach (var i in cheapBooks)
            {
                Console.WriteLine(i);
                //Console.WriteLine(i.Title);
            }
 
            foreach (var i in cheaperBooks)
            {
                Console.WriteLine(i);
                //Console.WriteLine(i.Title);
            }
 
            Console.WriteLine(singleBook.Title);
            Console.WriteLine(firstItem.Title);
            Console.WriteLine(lastItem.Title);
 
            foreach (var i in skipItems)
            {
                Console.WriteLine(i.Title);
                //Console.WriteLine(i.Title);
            }
 
            Console.WriteLine(cnt);
            Console.WriteLine(max);
        }

30. March 2017 by admin
Categories: C#, Programming | Leave a comment

Using DateTime in C#

Below is very simple usage of DateTime –

class DateTimePr
    {
        static void Main(string[] args)
        {
            var datetime = new DateTime();
            var now = DateTime.Now;
            var today = DateTime.Today;
 
            Console.WriteLine(now);
            Console.WriteLine(today);
 
            Console.WriteLine(now.Hour);
            Console.WriteLine(now.ToLongDateString());
            Console.WriteLine(now.ToString());
        }
    }

30. March 2017 by admin
Categories: C#, Programming | Leave a comment

Reading a file in C#

Below is a simple program in C# that reads a file and outputs the longest word in it. Enjoy!

using System;
using System.IO;
using System.Collections.Generic;
 
namespace <yourNS>
{
    class FilesNDirs
    {
 
        public static void Main(string[] argvs)
        {
            var path = @"C:\Users\deepesh\Desktop\Test\test.txt";
 
            var textFile = File.ReadAllText(path);
            var words = textFile.Split(' ');
            var wordlenpt = new string[100];
            var wordlenarr = new List<int>();
            foreach (var i in words)
            {
                if (i.Length > 0)
                {
                    wordlenarr.Add(i.Length);
                    wordlenpt[i.Length] = i;
                    Console.WriteLine(i);
                }
            }
            wordlenarr.Sort();
            foreach (var i in wordlenarr)
            {
                Console.WriteLine(i);
            }
            Console.WriteLine("\n\nLargest word in the file is >>" + 
wordlenpt[wordlenarr[wordlenarr.Count - 1]]);
        }
    }
}

30. March 2017 by admin
Categories: C#, Programming | Leave a comment

Finding Lowest number from a List in C#

Below is a simple program to find the lowest number from a list of numbers –

using System;
using System.Collections.Generic;
 
namespace GroundCSApp
{
    class GetSmallest
    {
        public static void Main(string[] argvs)
        {
            var numlist = new List<int> { 123456 };
 
            var finallst = GetSmallests(numlist, 3);
            foreach (var i in finallst)
            {
                Console.WriteLine(i);
            }
        }
 
        public static List<int> GetSmallests(List<int> lst, int cnt)
        {
            if (cnt > lst.Count)
            {
                throw new ArgumentOutOfRangeException("cnt""Count of numbers is 
greater than the list count");
            }
            var buff = lst;
 
 
            var smalllst = new List<int>();
 
            while (buff.Count > cnt)
            {
                var min = GetiSmallest(buff);
 
                smalllst.Add(min);
                buff.Remove(min);
            }
            return smalllst;
        }
 
        public static int GetiSmallest(List<int> lsti)
        {
            var min = lsti[0];
 
            for (var j = 1; j < lsti.Count; j++)
            {
                if (lsti[j] < min)
                {
                    min = lsti[j];
                }
            }
            return min;
 
        }
 
    }
}

30. March 2017 by admin
Categories: C#, Programming | Leave a comment

Simple C# Programs

Here is some basic, simple, handy C# programs for you to enjoy and refresh your memory –

using GroundCSApp;
using System;
using System.Collections.Generic;
using System.Linq;
 
namespace GroundCSApp
{
    public enum ShippingMethod
    {
        Regular = 1,
        Priority = 2,
        Snail = 3
    }
    class Program
    {
        static void Main(string[] args)
        {
 
            //-------------------------------------------------------
            //non -primitive/reference type eg: number 
            //array creation and assignment
            
            var numbers = new int[3];
            numbers[0= 23;
 
            var numbers2 = numbers;
 
            numbers[0= 24;
 
            Console.WriteLine("Value of variable numbers is changed 
and it is >>" + numbers[0]);
            //--------------------------------------------------------
 
 
            //--------------------------------------------------------
            //non-primitive, immutable, string array creation assignment
            var names = new string[3] { "John""Luke""Mark" };
 
            //String Join example
            var joinedName = string.Join(",", names);
            Console.WriteLine("\n\n" + joinedName);
 
            var strArray = new string[] { "Text""Book""Light" };
 
            var strArray2 = strArray;
 
            //example for reference type where
            //original value is modified
            strArray2[0= "Candle";
 
            var comb = string.Join(",", strArray);
 
            Console.WriteLine(comb);
            //--------------------------------------------------------
 
 
            //--------------------------------------------------------
            //simple object creation and method call
            //Example::1
            var John = new Person();
 
            John.FirstName = "John";
            John.LastName = "Jiss";
 
            John.Introduce();
 
            //Example::2
            var cal = new Calculator();
            Console.WriteLine(cal.Add(2334+ "" + numbers[0]);
            //--------------------------------------------------------
 
 
            //--------------------------------------------------------
            //Using Enums
            var method = ShippingMethod.Priority;
            Console.WriteLine((int)method);
 
            var methodExt = 3;
            Console.WriteLine((ShippingMethod)methodExt);
 
            var shippingstr = "Snail";
            var shippingM = (ShippingMethod)Enum.Parse
(typeof(ShippingMethod), shippingstr);
 
            Console.WriteLine(shippingM);
            //--------------------------------------------------------
 
 
            //--------------------------------------------------------
            //Simple Console Read and output
            while (true)
            {
                Console.WriteLine("\n\nEnter your name, we will 
display it 🙂 >>");
 
                var input = Console.ReadLine();
 
                if (!string.IsNullOrWhiteSpace(input))
                {
                    Console.WriteLine("Your name is>>" + input);
                    break;
 
                }
 
                continue;
 
            }
            //--------------------------------------------------------
 
 
            //--------------------------------------------------------
            //Simple program snippet to Find Mode
            var cnt3 = 0;
 
            for (var i = 1; i <= 100; i++)
            {
                if (i % 3 == 0)
                {
                    cnt3++;
                }
            }
            
            Console.WriteLine("\nCount of mod 3s in 100 is>>" + cnt3);
            //--------------------------------------------------------
 
 
            //--------------------------------------------------------
            //Simple Console program snippet to find sum of numbers
            Console.WriteLine("\n\nEnter your numbers with new line 
to find the sum. Press 'ok' to exit>>");
            var numsum = 0;
 
            while (true)
            {
                var s = Console.ReadLine();
 
                if (s == "ok")
                {
                    Console.WriteLine("\n\nYour sum is>> " + numsum);
                    break;
                }
                else
                {
                    numsum += Convert.ToInt32(s);
                }
 
            }
            //--------------------------------------------------------
 
 
            //--------------------------------------------------------
            //Simple Console program snippet to find factorial
            Console.WriteLine("\n\nEnter number to find factorial>>");
            var factorial = Convert.ToInt32(Console.ReadLine());
            var factans = 1;
            for (var i = factorial; i >= 1; i--)
            {
                factans = factans * i;
            }
 
            Console.WriteLine("\n  " + factorial + "! = " + factans);
            //--------------------------------------------------------
 
 
            //--------------------------------------------------------
            //Simple program snippet for array sort
            var numar = new[] { 234521 };
 
            Array.Sort(numar);
            foreach (var i in numar)
            {
                Console.WriteLine(i);
            }
            Console.WriteLine("\n\n");
            //--------------------------------------------------------
 
 
            //--------------------------------------------------------
            //Simple program snippet for list operartions
            var numberslst = new List<int>() { 12345 };
 
            numberslst.Add(1);
 
            numberslst.AddRange(new int[3] { 678 });
 
            foreach (var numb in numberslst)
            {
                Console.WriteLine(numb);
            }
 
            Console.WriteLine(numberslst.IndexOf(1));
            Console.WriteLine(numberslst.LastIndexOf(1));
 
            for (var i = 0; i < numberslst.Count; i++)
            {
                if (numberslst[i] == 1)
                {
                    numberslst.Remove(numberslst[i]);
                }
            }
 
            Console.WriteLine("\n\n");
            foreach (var num in numberslst)
            {
                Console.WriteLine(num);
            }
            //End list operations
            //--------------------------------------------------------
 
 
            //--------------------------------------------------------
            //Simple implementation of Facebook style Like status
 
            Console.WriteLine("\n\nPlease enter unique names to find 
your like status. Press ok to exit>>");
 
            var namlst = new List<string>();
            while (true)
            {
                var namelst = Console.ReadLine();
 
 
                if (namlst.Count > 0 && namlst.Contains(namelst))
                {
                    Console.WriteLine("\nPlease enter unique names>>");
                }
                else if (namelst != "ok")
                {
                    namlst.Add(namelst);
                }
                else
                {
                    if (namlst.Count > 0)
                    {
                        Console.WriteLine("******************\n\n");
                        for (var i = 0; i < namlst.Count; i++)
                        {
                            if (i == 0)
                            {
                                Console.WriteLine("You have likes from > ");
                            }
                            Console.WriteLine("[" + namlst[i] + (i + 1+ "] ");
                        }
                    }
                    else
                    {
                        Console.WriteLine("\nYou have no likes!");
                    }
                    break;
                }
 
            }
 
            //--------------------------------------------------------
 
 
            //--------------------------------------------------------
            //Simple program snippet to Reverse String
            Console.WriteLine("\n\nEnter your name\n\n>>");
 
            var namarre = Console.ReadLine();
 
            var namarry = new string[namarre.Length];
 
            for (var i = 0; i < namarre.Length; i++)
            {
                namarry[i] = namarre[i].ToString();
            }
 
            Array.Reverse(namarry);
            Console.WriteLine("\nString reversed is as below>>\n\n");
            foreach (var nami in namarry)
            {
                Console.WriteLine(nami);
 
            }
            //--------------------------------------------------------
 
 
            //--------------------------------------------------------
            //Simple program snippet to capture first 5 numbers, 
            //sort it and display it
            var numplLst = new List<int>();
            Console.WriteLine("\n\nEnter numbers, we will capture first 
5 numbers and will sort and display it >>\n");
            while (true)
            {
                var innum = Console.ReadLine();
 
                int numval = 0;
 
                try
                {
                    numval = Convert.ToInt32(innum);
                }
                catch (FormatException e)
                {
                    Console.WriteLine("\nThe input need to be a number");
                }
                catch (OverflowException e)
                {
                    Console.WriteLine("\nThe input cannot be fit in as a number");
                }
 
                if (numplLst.Count == 5)
                {
                    numplLst.Sort();
                    Console.WriteLine("\nHurray you have entered 5 numbers 
and here it is sorted>>\n\n");
                    foreach (var i in numplLst)
                    {
                        Console.WriteLine(i);
                    }
                    break;
                }
                else
                {
                    if (numplLst.Contains(numval))
                    {
                        Console.WriteLine("\nNumber already exist in the 
list, please enter unique value>>");
                    }
                    else
                    {
                        numplLst.Add(numval);
                    }
                }
            }
            //--------------------------------------------------------
 
 
            //--------------------------------------------------------
            //Simple console program snippet to 
            //accept numbers and display unique numbers
            var innums = new List<int>();
 
            Console.WriteLine("\n\nEnter any numbers until 'Quit', we will 
display unique numbers>>");
 
            while (true)
            {
 
                var inm = Console.ReadLine();
 
 
                var ret = 0;
                try
                {
                    ret = Convert.ToInt32(inm);
                }
                catch (FormatException e)
                {
                    Console.WriteLine("\nPlease enter a number!");
                }
                catch (OverflowException e)
                {
                    Console.WriteLine("\nNumber cannot be fit into the stack!");
                }
 
                if (inm == "Quit")
                {
                    var reslst = innums.Distinct().ToList();
                    Console.WriteLine("\nYour unique list is>>\n\n");
                    foreach (var ls in reslst)
                    {
                        Console.WriteLine(ls);
                    }
                    break;
                }
 
                innums.Add(ret);
            }
            //--------------------------------------------------------
 
 
            //--------------------------------------------------------
            //Simple console program snippet to get numbers and then display 
            //first 3 lowest numbers
            Console.WriteLine("\\nEnter a list of numbers separated by comma, 
we will display the first 3 lowest numbers>>");
 
            while (true)
            {
                var intls = Console.ReadLine();
 
                var inlst = new string[] { };
                var inlstint = new int[5];
 
                inlst = intls.Split(',');
                var trybrk = false;
                var j = 0;
                foreach (var i in inlst)
                {
                    //Console.WriteLine(i);
                    try
                    {
                        var con = Convert.ToInt32(i);
                    }
                    catch (FormatException e)
                    {
                        trybrk = true;
                    }
                    Console.WriteLine(i);
                    inlstint[j++= Convert.ToInt32(i);
                }
                if (trybrk)
                {
                    Console.WriteLine("\nList can only contain numbers! 
Please re-enter the list>");
                }
                else
                {
                    if (inlst.Length == 5)
                    {
                        Array.Sort(inlstint);
 
                        Console.WriteLine("\n\nFirst 3 smallest numbers are>>\n");
                        for (var i = 0; i < inlstint.Length; i++)
                        {
                            if (i < 3)
                            {
                                Console.WriteLine(inlstint[i]);
                            }
                            else
                            {
                                break;
                            }
                        }
                        break;
                    }
                    else
                    {
                        Console.WriteLine("\nPlease have 5 numbers in the list. 
Try again>>");
                        Console.WriteLine("\\nEnter a list numbers separated 
by comma>>");
                    }
                }
            }
        }
    }
}

30. March 2017 by admin
Categories: C#, Programming | Leave a comment

Code Reuse via Composition in C#

Composition is a common object oriented concept that enables us to implement loose coupling as well as code-reuse. Lot of times we recommend our developers to use more composition and less inheritance due this very fact. Inheritance supports code-reuse, but makes application tightly coupled and creates long inheritance hierarchies that creates inter-dependencies. Inheritance implements a IS-A relationship where composition implements a HAS-A relationship – kind of a House has-a door. Below is a working example to demonstrate how composition is implemented in C# and how it leads to code reuse and loosely coupled architecture. Logger is a common class that is being reused between two different scenarios and without the need to inherit anything from it that eliminates any dependency between the classes.

Class that is re-used:

using System;
 
namespace Composition
{
    public class Logger
    {
        public void LogCommand(string logcommand)
        {
            Console.WriteLine(logcommand);
        }
    }
}

Class 1 that re-uses by Composition: 

namespace Composition
{
    public class RoboInstall
    {
        private readonly Logger _logger;
 
        public RoboInstall(Logger logger)
        {
            _logger = logger;
        }
 
        public void InstallRobo()
        {
            _logger.LogCommand("We are Installing our new Robot!!!");
        }
    }
}

Class 2 that re-uses by Composition: 

namespace Composition
{
    public class RoboMigrator
    {
        private readonly Logger _logger;
 
        public RoboMigrator(Logger logger)
        {
            _logger = logger;
        }
 
        public void MigrateRobo()
        {
            _logger.LogCommand("We are migrating Robot!!");
        }
    }
}

Note that we use the private read only field to define the re-used object which is instantiated and created via the constructor.

Main program:

namespace Composition
{
    class Program
    {
        static void Main(string[] args)
        {
            var migrate = new RoboMigrator(new Logger());
 
            var install = new RoboInstall(new Logger());
 
            migrate.MigrateRobo();
 
            install.InstallRobo();
        }
    }
}

 As you can see in the main program, both RoboInstall and RoboMigrator injects the Logger object which is then available within migrate and install objects to the reused. Good thing to note is neither migrate nor install classes need to be recompiled if Logger class is changed and any changes will be instantaneously effected in both classes at the same time.

30. March 2017 by admin
Categories: C#, Programming, Uncategorized | Leave a comment

← Older posts