Using GenFu to fill your database with dummy data

When you deliver a training or present a session or even start a new project, you want some test data pre-filled in your application instead of having to start with a fresh empty database.

Sometimes you don’t even need a database, you just want to display a list of customers in a grid to show your audience something, so, lets assume you have a Customer class that has the following definition

public class Customer
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Genger { get; set; }
        public string PhoneNumber { get; set; }
        public string Address { get; set; }
        public DateTime BirthDate { get; set; }
    }

You would normally do the following in your code:

 public ActionResult Index()
        {
            var listOfCustomers = new List<Customer>();

            listOfCustomers.Add(new Customer { Id = 1, FirstName = "John", LastName = "Smith", Address = "Someaddress", BirthDate = DateTime.Now.Subtract(TimeSpan.FromDays(9000)) });
            listOfCustomers.Add(new Customer { Id = 1, FirstName = "Mark", LastName = "Johnson", Address = "Someaddress", BirthDate = DateTime.Now.Subtract(TimeSpan.FromDays(9000)) });
            listOfCustomers.Add(new Customer { Id = 1, FirstName = "Jackson", LastName = "Clark", Address = "Someaddress", BirthDate = DateTime.Now.Subtract(TimeSpan.FromDays(9000)) });
            listOfCustomers.Add(new Customer { Id = 1, FirstName = "Emillia", LastName = "Smith", Address = "Someaddress", BirthDate = DateTime.Now.Subtract(TimeSpan.FromDays(9000)) });

            return View(listOfCustomers);
        }

And the results would be:

list of customers

Seems good but not very satisfying and requires a lot of work specially if you want to show a lot of records to have paging for example.

GenFu is a very exciting library that can save you all this time, it uses code to generate real-time person information including names, address, birth date  and a lot more.

To use GenFu, all you have to do is to install its package using NuGet package manager, so  from VS, select tools -> NuGet Package Manager -> Package Manager Console and type the following command

install-package GenFu

Then replace the code written above to create list of customers with the following code:

  public ActionResult Index()
        {
            var listOfCustomers = A.ListOf<Customer>(20);

            return View(listOfCustomers);
        }

With just one line of code, it will create a 20 records with real data, and the results will be like this:

list of customers with genfu.PNG

 

To use GenFu to pre fill your database with some records, you can add the same line of code inside the Seed method in your Migration class, just like below

 
 internal sealed class Configuration : DbMigrationsConfiguration<GenFuDemo.Models.CustomersContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(GenFuDemo.Models.CustomersContext context)
        {
            context.Customers.AddOrUpdate(c => c.FirstName, A.ListOf<Customer>(20).ToArray());
        }
    }

This method will run when you run the update-database command and the data will be inserted into the Customer table

To read more about GenFu, you can visit its GitHub repository, it offers more features like customizing the way it generates or giving hints about some properties that it may not understand, for ex: if you have a property named NightNumber, which is a phone number, in this case you can instruct GenFu using its Fluent APIs to generate phone numbers for the property NightNumber

Advertisements

Building a LOB application with MVC 5 – Part 5 – Views

This is the sixth part of building line of business application using MVC 5, you can read the previous parts through the following links

  1. Building a LOB application with MVC 5 – Part 0
  2. Building a LOB application with MVC 5 – Part 1
  3. Building a LOB application with MVC 5 – Part 2 – Models and Generic Repository
  4. Building a LOB application with MVC 5 – Part 3 – EntityFramework
  5. Building a LOB application with MVC 5 – Part 4 – Controllers, Routes and Areas

In the previous part, we introduced controllers, routes and areas and we created the needed controllers and areas.

In this part, we will introduce views, so by the end of this post, we will finally have something that we can see.

What are Views?

We talked about the M and C, so we have the V from MVC remaining, in web forms, we mainly have the logic and view in one place (aspx), but in MVC, the presentation of the your data is the responsibility of the View, your controller intercept the request, call the business logic, and select how it wants to display the data.

You can display it as a text, Image, Chart, HTML or a downloadable file, in web forms you would have to create a separate web form for each view, but in MVC, you only have to duplicate the view part.

So, for now, lets just say that Views are this pieces that we see the system through it, it used to display the  information passed to it from the controller to the users and capture information from the users and forward it to the controller for updates

What is View Engine?

When MVC was released, the views were aspx pages and you had to write these annoying opening and closing tags from web forms era, but later you had the option to either use web forms rendering or the new views engine called Razor.

Razor is much more clean way of writing your views, basically it is all HTML unless you started with @ symbol, this is where the compiler assumes that you want to have a server side code

The View Engine is responsible for translating the written code either in aspx or Razor syntax and produce the final HTML, you can access the list of installed view engines by calling the  ViewEngines.Engines property, you can also add a new custom engine to this list by implementing the interface IViewEngine.

As you can see below, MVC 5 is shipped with 2 view engines

  1. WebFormViewEngine which renders the ASPX pages into HTML
  2. RazorViewEngine which renders the .cshtml files used in razor to HTML

view engines.PNG

When you expand the RazorViewEngine, you will see the following:

razor view engine details.PNG

As you can see above and as we stated in previous posts, MVC uses conventions over configuration, so by default the controller action will search for a view with the same action name inside a folder with the same controller name without the word Controller inside the Views folder, you can change these conventions by editing the corresponding property in the view engine and make sure to add this code in the Global.asax to make sure it is executed first thing when the application starts.

Layout Page (Master Page)

MVC has the same concept of Master page in web forms, only it is called Layout page here, by default the layout is set for any view unless you set the property Layout to null as below

layout null

if you didn’t do that, then the view will inherit the default Layout which is by convention again resides in Views\Shared\_Layout.cshtml

You can have more than one layout in your project, and you can set the layout for the view by setting the Layout property to the custom layout path, ex:


Layout = "~/Views/Shared/_CustomLayoutPage.cshtml";

Razor Syntax

Razor syntax is very similar to normal HTML unless when it starts with @ symbol, to have more details about it, please read more from microsoft site Razor Syntax

Passing data from Controllers to views

Since the view will be displaying data to the end users, we nee to pass this data from the controllers into the view, this happens in 2 ways

Strongly Typed Views

With strongly typed views, the view knows what is the data type of the model and you can reference the properties of the model inside your view code by using the Model property, visual studio supports  intellisense for this.

you can set the model type for the view by adding the following lines at the begenning of the view

@model AppointmentManager.Web.Models.AddPhoneNumberViewModel

To see it in action, you can open the file \Views\Manage\AddPhoneNumber.cshtml and examine the code

You can pass the data from your action to the view by adding the model object into the View method as below, if you used View() without any value and tried to access the Model  object inside the view, it will throw a null exception

pass model to view.PNG

Weakly Typed Views

In this type, you don’t specify the type of the model, you just pass the data you need to the view using 3 predefined properties:

  1. ViewBag, this is a dynamic object, so you can simply write ViewBag.Message = “Hello” in your action and in the view you can read it by adding @ViewBag.Message, the ViewBag variables are available only for the current view, so if you have an action called Index and you set a message variable inside it, you can access it only in the Index view, if you navigated to another action, then you can’t access it from there
  2. ViewData, this is the same as the ViewBag except it is a dictionay, so to add a key to it from your controller you either use ViewData.Add(“Key”,”Value”), or you can simply write ViewData[“Key”]=”value” and in your view just write @ViewData[“Key”]
  3. TempData, this is the same as teh ViewBag except that its lifecycle is a little bit longer, you can access it from the next action, so if you set the value of a variable called Message in your Create action that is called when the user post a form then you redirected to the Index action, you can then call teh Message variable from the Index action, this can be used to show a confirmation message when the user is redirected fom a page to another, note that after the redirection, the variable will be lost, so you can’t use it again.

Create Views

To create a view, you can go select the folder inside the Views folder where you want to add your view, right click and select Add -> View

Or you can go to your controller, put the cursor inside the action that you wants to generate view for it, and right click then select Add View.

Lets do that together.

Expand Areas, then Admin, right click Controllers and add an Empty Controller named ServiceTypes, this will be used to administer service types.

Add a project reference to the following projects inside the web project

  1. AppointmentManager.Models
  2. AppointmentManager.Repository
  3. AppointmentManager.Repository.EntityFramework

Right Click inside the Index action and choose Add View, leave the view name as is to avoid writing the name explicitly inside the action, choose the template as List, this will create a listing page, you can find the rest of templates for CRUD operations, select the model class that VS will use to generate the view using scaffolding technique, you can choose the Layout page then click Add

create view
Once done, the generated view file will be opened in VS and you can inspect the code, the first thing you will notice is the word @Html is mentioned a lot

HTML Helpers

If you have a form that accepts a username and password, you can write it as below

<input type="text" name="username" id="username" value="" />
<input type="password" name="password" id="password" value="" />

And if the model property was changed then you have to revist your HTML and update it to be the same as your model, also this is a lot of code to be written, so MVC offrers HTML helpers to save your time, the above code can be replaced by:

 @Html.TextBoxFor(m => m.Email)
 @Html.LabelFor(m => m.Password)

The above code will generate the same code and you can add more properties like css classes and other attributes.

To read more about HTML helpers and how you can create your own helpers, please visit this link

 

Model Binding

Now, the user browsed to your application, clicked register, and he is redirected now to the /Account/Register which means the account controller and register action, we have a register view which draws some input fields to capture the user information, the user adds the required information and clicked Submit.

In web forms, we used to do a lot of person.Name = txtName.Text

But in MVC, we don’t have to do that as MVC does it for us using something called Model Binding

When your action accepts a parameter and the user submit an request to this action, MVC automatically create an instance of this object and start to fill its properties from the request body, query string, route values, all these sources called Value Providers, you can add a custom value provider by going through the following post

MVC fill the object properties with request parameters that has the same name, so, if you have a class called Customer, and inside it you have FirstName and LastName, then MVC inspect the request for a query string or form values with the same names.

If the default model binder doesn’t meet your expectations, you can create your own, to read more please see MVC Model Binders

Scaffolding

Remember when we added a view and chose the template type as List and the model type as ServiceType and suddenly we have a listing screen? this is called Scaffolding and it happens using T4 Templates that visual studio runs.

To customize these templates, you have to do the following:

  1. Open C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Microsoft\Web\Mvc\Scaffolding\Templates
  2. Create a folder called CodeTemplates in the web project root directory
  3. Copy the template you want into this folder and customize it, ex: MvcControllerEmpty, open it and customize it the way you want.

After that, create a new item from this template by following the same normal procedure, Right Click the project file-> Add -> New

You will see the updates you made applied to the newly created file, VS is smart enough to override the template with the one in your project.

Annotations and Validations

HTML Helpers can use any annotation attributes defined for each class property and it will use it generate the correct input control and add the right validation.

Ex: When we add the Required, MaxLength and Display attribute to the Name property inside the Country class, it will generate an extra validation for the textbox generated in the view, it will make the field required and has a max length of 50 charactres, it will also change the label from Name to Country Name

annotation

Not only this, but it will also impact the EntityFramework code first, when you run the application, EF will compare the model with the database and finds that the Name property has been changed and ti will ask you to add another migration in order to mark the Name column as Required and has a max length of 50

The same will apply when the ViewState.IsValid property is called in the Controller Action, this will make your validation consistent from the UI layer up to the data access layer.

Imagine if you followed the first way of adding just plain HTML code like the example above, you would have to add all the validation yourself, but now HTML helpers removed all this burden

You can now go ahead and generate views and add annotations for all the entities and controllers, if you have any questions, please leave a commant

 

You can get the full source code from GitHub Repository https://github.com/haitham-shaddad/AppointmentManager

Building a LOB application with MVC 5 – Part 0

There are a lot of tutorials and blog posts about MVC, Web API and other Asp.Net technologies, but it has been always a problem getting all these parts together in once place and utilize it to build something bigger.

In this post, I will start a series where we will introduce and build a complete functioning lin of business web application using Asp.Net MVC 5, I will start with introducing the business behind the application, and in each part, we will introduce a new feature of MVC and use it to build a new feature in our LOB application, this will allow us to know how to use MVC in practical example and we will also go deep dive in each feature to build more advanced features.

Introduction to the LOB Application

The application we are going to build together is called Appointment Manager, it will be a flexible application that allows users to register either as service provider or consumer, below are the list of features for each role

  1. Service providers. ex:doctors, mechanics, carpenters
    1.  Check his Calendar
    2. View appointment details
    3. View ratings for his work
    4. Select which services he provides
    5. Manage his available time slots for each service
  2. Service consumers
    1. Browse service categories
    2. Browse service providers in a specific category
    3. View specific service provider details, history and rating
    4. Book an appointment
    5. Check his Calendar
    6. Rate a service Provider
  3. Admin
    1. Manage Service Categories
    2. Manage Attribute for each service category, ex: Mechanic category will have Car model, Year and his services will include Oil change, A/C, …
  4. Shared Features
    1. Register
    2. Login, Logout
    3. Edit Profile

By the end of this series we will have the application built and we will have full knowledge of MVC 5 framework

Introdction to the Technical Part

In each part, we will introduce a key component in MVC and use it to build another feature in the application, below are the features we are going to discuss in MVC

  1. Introduction to MVC
  2. Models
  3. View
  4. Controllers
  5. Routing
  6. Localization
  7. Bootstrap
  8. EntityFramework
  9. Identity and Security
  10. Bootstrap
  11. SignalR

Setting up ALM

Since this will be a real business application, we want to apply everything we do in the real life, and the first thing is to decide about how are we going to manage the application life-cycle management, fortunately, Microsoft offers a full platform for that;TFS, In our series, I will use Team services or TFS Online with GitHub as our source code repository, You can also use TFS on premise, Microsoft offers TFS express for free, you can download and install it and use it through the series

I will start by creating the project and then enter the list of features into a user stories.

Since TFS online support Git, I will use it as our source code control and I will link it later to GitHub

Create the project on TFS Online

In order to be able to use TFS online, you have to have a visual studio account, if you don’t already have one,go to VisualStudio.com and register using your MS Account, it is free

  1. Open your browser and navigate to https://[your account].visualstudio.com
  2. Under “Recent Projects & Teams” Click New TFS New
  3. Enter the Project name, description, Process Template and Version control as Git, TFS support different process templates such as Scrum and CMMI, if you have different needs, you can create a new template and customize it, we won’t go deeper here but you can read more about TFS templates from this link https://msdn.microsoft.com/en-us/library/ms243782.aspxNew Project
  4. Once the project is created, clink on “Navigate to the project” button
  5. Once the page is loaded, you will see a dashboard from where you can see everything about your project, ex: Code, Sprint burn down chart and user stories
  6. Click on Backlog link in the Work widget to start editing the user storiesTFS dashboard
  7. Once the page is loaded, you can add the story by typing the story title in title field and press enter or click Add button, if you can’t see the title field, just click the New link as shown in the screenshot belowbacklog

After the story is added, you can double click it to open the edit dialog which will enable you to add all the details, once this is done, click the Save icon on the top rightedit story

  1. TFS offers you the ability to categorize your user stories into something called Features, think of it as sub-modules to group the related features together, You can click Features from the left menu and add the needed features, then go to the backlog  by clicking the Stories link and Click the Mapping icon and make sure it is On, this will open a panel on the right with the list of features defined, drag the user stories from the left and drop it over the feature

So far, we talked about the application we want to build, we configured its source control and added its requirement.

In the next part we will introduce MVC 5, Create the project structure and build the home page for the application.

You can get the full source code from GitHub Repository https://github.com/haitham-shaddad/AppointmentManager