Fun with Javascript Functions

A maintainable code means having recurring themes that allows it to have a predictable format thereby making it maintainable. In the past design patterns were regarded as “a thing” only for Server-Side codes: But as web applications become more modern, the more we need Javascript and the more we need to keep our codes pretty.

In this post, we’ll discuss some very basic patterns that we can use for Javascript functions

  • Functions as Abstractions
  • Functions to build modules
  • Functions to avoid Global variables

About the Codes

You can find the codes in https://github.com/johnconraddomingo/Javascript.Patterns. It might come as confusing if you try to run the codes and nothing’s happening. Everything that’s happening is happening in the Console, so to see them in action you would want to hit F12 on your browser to see the Developer Tools. The main page index.html is just there to have somewhere to run the scripts on.

image

You can choose not to run certain scripts from the project by disabling the script tags that you’re not interested in.

Functions as Abstractions

I want to do some work and I want to wrap it all up in a function and assign it to a variable

var work = function () {
     console.log(
“Doing Work.”);
};
work();

We did just that then we called work() … That’s with a parenthesis because it’s a function. That’s cool. Now what I want to do is to add another level of abstraction. I want to add another function. This time I’ll call it doWork and it will accept a function as a parameter.

var work = function () {
     console.log(
”    Doing Work.”);
};

var
doWork = function (f) {

     console.log(
“Calling Work…”);
    
f();
    
console.log(“Work Called.”);
};

doWork(work);

So now I’ll run doWork and pass in the work function and it’s all good. Take note as well that we’re not passing work() with a parenthesis, because if we do that, it will pass in the result of the function. That’s going to throw an error because work() is not returning anything and we will ultimately be passing an undefined to doWork.

Functions to build Modules

Now, sometimes I need more than just a function. Sometimes I need an object that contains data and has methods attached to it. Let’s see this sample below.

var createWorkerInline = function () {
    
return {
         inlineJob:
function () {
             console.log(
“Performing Inline Job “);
        
}
      
// Another inline job can go here
    
}
}
;

var workerInLine = createWorkerInline();
workerInLine.inlineJob();

I created an object named workerInLine and I want it to return an inlineJob which is a function. But here’s a more common approach: Instead of declaring it inline, what I want to do is structure it in a way that gives more focus on my implementation. So I’m going to break it all down.

var createWorker = function () {
    
var workCounter = 0;
     var
job1 = function () {
         workCounter++
;
        
console.log(“Performing Job 1. Count ” + workCounter);
    
};
     var
job2 = function () {
         workCounter++
;
        
console.log(“Performing Job 2. Count ” + workCounter);
    
};
     return
{
         task1: job1,
         task2: job2
     }
}
;

var worker = createWorker();
worker.task1();
worker.task2();
worker.task2();
worker.workCounter++; // This will not work: Undefined
worker.task1()

Here is what’s happening:

  • I have separated the definitions from the return statement: And in the return statement, I told Javascript that task1 will return the function that is assigned to the variable job1 and that task 2 will return the function that is assigned to the variable job2.
  • I can create a variable within createWorker that can be shared within the scope. You’ll notice that I created a counter. I increment this counter everytime the job is called. I display the current value evertime on the console
  • Because the counter (much like job1 and job2) is not part of the return statement, it will remain private. Accessing it from outside the scope will not work. Funny enough, it doesn’t throw an error either.

Also referred to as the Revealing Module Pattern. We encapsulate some codes inside a function which is the definition of a module in a general sense in Computer Science. We’re creating a module in Javascript by creating a function and inside of that function we’re building up some things that we can expose to the outside world

Functions to Avoid Global Variables

If you know a little bit about programming, you’ll know that global variables are bad. They easily become a source of confusion and bugs. Because Javascript is a dynamically-typed language,  heavily typed language, it’s very easy for me to override a global variable and now we’re lost of who accessed what.

All the activities we have done thus far has been on a global scope. Here’s a way to not have any globals at all: Using a self-executing function or otherwise known as an Immediately Invoked Function Expression (IIFE, pronounced as “iffy”) which is an anonymous function that gets invoked as soon as the page loads.

(function() {
    
// Perform Tasks here
})();

It may look confusing but all it is is an anonymous function surrounded by a parenthesis and then we end it with an open/close parenthesis thereby telling Javascript to invoke this now.

Node.js for .NET Developers

Introduction

You can pick up the solution from https://github.com/johnconraddomingo/NodeJs.AspnetNodejs

This whole post is a good introduction to Node.js from a .NET Developer’s perspective. By the end of this document, you should

  • Be familiar with Node.js
  • Get your hands wet with Node.js JavaScript
  • Be abel to build a very basic HTML Hello World website
  • Be able to build an API

We will not build anything too pretty because as i’d like to limit the scope of this post, but we will be able to create a HTML Website and a WebAPI.

It is assumed that

  • You know your way around Visual Studio
  • You know the basics of a website
  • You have an idea what MVC is

What is it?

The official definition is Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. To explain that further:

  • You write Server-side codes that run on Chrome’s V8 engine. That said, js codes are actually compiled, and only expressed as Javascript. This is in contrast to the Javascript that you would write in a browser, which is interpreted script.
  • You most likely write Client-Side scripts on Javascript, and so you will most likely be dealing with Javascript and JSON both Server-Side and Client-Side
  • Non-blocking IO simply means Asynchronous operations, that is, when you make a request to the server, it doesn’t block any other incoming requests.
  • V8 provides a predictable environment for developers. Unlike Javascript that you write on a browser, Node.js runs on a platform with not much variables that will affect its dependencies.

I am primarily a .NET Developer, and so majority of what will be discussed here is (a) how Node.js compares with ASP.NET and (b) using Visual Studio to code.

Comparing Node.js and ASP.NET

For starters, they both have a dot in their names… Does that count?

  • Asynchronous Operations: Although ASP.NET allows for this, Node.js provides this functionality out of the box
  • Language used: ASP.NET can be expressed using C# or VB, and whatever language is available for .NET, including F#. On the other hand, Node.js is expressed in Javascript.
  • Compilation: Just because Node.js is expressed in Javascript, it means that it’s not compiled and that it’s slower compared to ASP.NET which is compiled into assemblies. Node.js is compiled. Javascript is merely the language used.
  • Power: Node.js, by definition is fast and efficient. However, it is not used for more intensive stuff that require much processing power.
  • Package Manager: While .NET as a whole has Nuget (https://www.nuget.org/), Node has NPM (https://www.npmjs.com/) or Node Package Manager.
  • Engine: ASP.NET uses the .NET Framework as the engine while Node.js uses V8.
  • Views: ASP.NET Provides View Engines with either ASPX or Razor available out of the box. They’re pretty much the same with very little difference in syntax. In Node.js, we work with View Engines that we can get from NPM. Since you’re reading a blog for .NET Developers, it’s best to use Vash, being a Razor clone.

Let’s start!

Starting Node.js

Getting Node.js

Downloading for Usage

We can download Node.js from https://nodejs.org/en. It will detect your machine for you. You can go ahead and download what link is available, or go to https://nodejs.org/en/download/ for more options.

Preparing your development from Visual Studio

From Visual Studio, create a New Project and you’ll find Node.js Web Application from the Templates list under JavaScript. This should get you started with a Web Server running.

NodeNewProject

Note: Please make sure you download the package from https://nodejs.org/en, otherwise Visual Studio will hang up when you create a new Project.

What you’re getting

Now, let’s see what Visual Studio created for you.

‘use strict’;
var
http = require(‘http’);
var
port = process.env.PORT || 1337;
http.createServer(function (req, res) {
res.writeHead(
200, { ‘Content-Type’: ‘text/plain’ });
   
res.end(‘Hello World\n’);
}).listen(port);

You get a port that Nodejs opens for you and a createServer method that accepts self-executing method.

It writes Hello World in the Response as a plain text, which you can easily replace with an application/json if you’re doing a WebAPI.

Let’s go through them in the next sub sections

Running from the Console

You’ll notice that a console is running everything: It’s just opening a port an accepting a request and returning something. If you’re running on production , there are a few solutions out there that will allow you to install it as a service, like os-service (https://www.npmjs.com/package/os-service) and node-windows (https://github.com/coreybutler/node-windows)

You’ll also notice that it’s starting up from server.js: You can find that this file is set in the package.json file located in the root folder of your project

“name”: “node-js.aspnet-nodejs”,
“version”: “0.0.0”,
“description”: “NodeJs.AspnetNodejs”,
“main”: “server.js”,
“author”: {
   
“name”: “John”
}

Dependencies

Now, dependencies. In .NET (and most other frameworks out there), it is the framework that handles the dependencies by looking at the folder structure and going through each file and looking at the classes available.

Node.js is quite different in that it expects you to point to it where the dependencies are, sort of like how C++ works. Here, it’s via the require keyword and in the sample above it’s using the http module.

How to Point to your Dependencies

Here’s an introduction on how to use the require/exports keyword to link them all up. Here’s what my project looks like

NodeJsProject

I created a folder named modules. That’s where I want to put all my custom methods. I can group files that are relevant to each other based on what they do, and even put them in the root folder. But for the purpose of this blog, I used a straightforward name.

Under it, I created a numberSquared and a personInfo file. They’re javascript files, as opposed to cs or vb if you’re coming from .NET. We will call these exposed objects from our server.js.

Fields

I want my personInfo to return a static value, and so I’m going to use the exports keyword and return an anonymous class to a named field that i’m going to call person.

module.exports.person = { id: 0, firstName: “John Conrad”, lastName: “Domingo” };

Back at server.js, I say

// Require: Field
var staticPersonInfo = require(‘./modules/personInfo.js’);
console.log(‘Test >> Default Person is ‘ + JSON.stringify(staticPersonInfo.person));

Where I just call .person like a normal field.

Method

It’s pretty much the same concept for methods, but this time I’m going to tell the exports keyword to take a self-executing anonymous method and say that squared will return the number * number.

module.exports = function (number) {
   
return { squared: function () {
      
return number * number;
      
}
    }
;
}

Back at server.js I do the same thing by requiring a numberSquared and this time, I will get 25 by calling the squared() method.

// Require: Method
var simpleMath = require(‘./modules/numberSquared.js’);
console.log(‘Test >> The square of 5 is ‘ + simpleMath(5).squared());

Method Structure

You will find that the default method structure of self-executing methods come in the form of request/response: And that’s because of the asynchronous nature of Node.js. It doesn’t hang around to wait for things to finish. It lets go of control and executes the callback once it does its job.

Packages

This section will use the package express (https://www.npmjs.com/package/express) as an example. Express is a web framework that we will be using later on.

Getting Packages

You can pick up Packages from npm where the command options get installed along with Node.js. You can visit the site on https://www.npmjs.com/. You can easily access the Package Manager from the command prompt. This is the .NET equivalent of Nuget where you can download Packages via Powershell.

To install from Visual Studio using the Command Prompt, Right-click on your project and choose Open Command Prompt here. Or you can just go to the Command Prompt yourself and manually go your project folder. and type

npm install express –save

where express is the name of the package that you want to install and –save says that you want to add express as a dependency to the package.json file, allowing it to automatically be downloaded.

You can also do it via Visual Studio. From the npm node in Solution Explorer, right-click and choose Install New npm Packages.

Either method you choose, you will find that a folder named node_modules will be populated by the package that you installed as well as its dependencies.

Using Packages

To use a package, simply refer to it via the require keyword. Easy! Node.js should already know all about your dependencies since it’s already in your package.json file. Visual Studio even lists your packages from the NPM package properties under Solution Explorer.

var express = require(‘express’);

At this point, even Visual Studio offered express to me via Intellisense

Web API

Now, we’re going to make an API. You know that an API is merely a Controller and that if we want to build a website out of that, we’ll basically reuse this method and chuck in a View and Controllers

Refer to the codes below. I once again used the require keyword and pulled in express. Express has functions that corresponds to HTTP verbs, like get, post and delete. And from there, we add in self-executing methods that returns either a HTML string for a website or json (plus xml, potentially).

This set how your calls to the server is routed. You should be very familiar with this as we have it either in RouteConfig in MVC or as attribute on top of the HTTP methods inside your controller.

var http = require(‘http’);
var
express = require(‘express’);
var
app = express();

// Default
app.get(‘/’, function (req, res) {
    res.send(
‘<html><head></head><body><h1>Hello World</h1></body></html>’);
});

// Api
app.get(‘/api/defaultPerson’, function (req, res) {
   
var staticPersonInfo = require(‘./modules/personInfo.js’);
   
res.set(“Content-Type”, “application/json”);
   
res.send(staticPersonInfo.person);
});

var server = http.createServer(app);
server.listen(1337, function () {
    console.log(
“Express is running on port 1337”);
});

you will notice that from the default get, I passed in HTML. You can in theory build a website out of this, although things would just get silly if you do anything more than a hello world. What you want to do is get a View Engine later on.

NodejsEdge

Now let’s look at the API. I go to api/default and it’s giving me back a json with the person object I pulled in from personInfo.js. Have a look at the header that I added in.

NodejsPostman

If we have a look at the header, it is indeed giving us an application/json as we have defined.

nodejsPostman2

There isn’t much parsing either, because Node.js is already talking json in the backend!

Conclusion

That folks, has been your introduction to Node.js. If you are a .NET developer, this post should be very straightforward to you. If you would like to learn more, it would really help if you do further reading on

  • How Node.js handles the MVC pattern
  • How View Engines get integrated (see: Vash)
  • How Node.js links to static resources
  • How Node.js handles data management (see: MongoDB)

IoC with Autofac and Controllers

 

Our Goal

What I’d like to do now is to use an IoC container for our MVC application. Our goal is to be able to create a concrete object: We want to instantiate the object once in code and pass it along: Instead of going through all the Controllers and manually going

image

What we have above would generally work: the downside is that

  • We need a reference to all the dependencies of the Concrete Object on compile time instead of on runtime.
  • If we want our Controllers to be fully testable and more easily extendable, we need to type the same *if null, then instantiate* on all the Controllers. This may not sound too bad, but having to do them with a million objects in a million Controllers would just be all messy. We can rid of this problem if we instantiate by code only in one area

Using Autofac

Pick up the sample in https://github.com/johnconraddomingo/Autofac.AutofacMvc

We’re using Autofac. I prefer to use it because

  • It has excellent support
  • Very easy to use compared to others
  • Many people use it which equates to a bigger community

Other folks might be put off with Autofac because of not having much control as opposed to, say, Ninject where you get to change most of the action in your project… As long as you know what you’re doing.

On the flip side, keep in mind that Autofac is Open Source, so you can pick up the source codes in modify it if it does something that you’re not happy with.

Get the Necessary References

Pick up your References from Nuget. For our sample, you’re going to need Autofac.Mvc. If you’re picking it up from within Visual Studio it will also get the main Autofac package for you

image

Integrate

Create the Interfaces and concrete objects that need to be passed around. We’ll pick up the Webserver from our Web.Config. This is just to show you that you can instantiate and do whatever you want from the startup of your application.

public interface IWebConfiguration
{
   
string WebServer { get; set; }
}

public class ConcreteObjectConfiguration : IWebConfiguration
{
  
public string WebServer { get; set; }
}

Create your Data Module. This module allows you to create your concrete objects and then register them as an implementation of your interface. What Autofac will do then is pass on the object you create here to the constructors that contains your defined interface.

This is a good idea to use for configurations and repositories.

 public class DataModule : Module
    {
       
private readonly string _webServer;
        public
DataModule(string webServer)
        {
            _webServer
= webServer;
       
}
       
protected override void Load(ContainerBuilder builder)
        {
           
// Create the Concrete Object
           
builder.Register(c => new ConcreteObjectConfiguration { WebServer = _webServer}).As<IWebConfiguration>();
            base
.Load(builder);
       
}
    }

Create a call to configure the Container. See that we pass on the WebServer value to the DataModule that we created above.

public class AutofacConfig
{
   
public static void ConfigureContainer()
    {
        var builder
= new ContainerBuilder();

        builder.RegisterControllers(typeof(MvcApplication).Assembly);
       
builder.RegisterFilterProvider();
       
builder.RegisterSource(new ViewRegistrationSource());
       
builder.RegisterModule(new DataModule(ConfigurationManager.AppSettings[“WebServer”]));
       
var container = builder.Build();

        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
   
}
}

Now, call AutofacConfig from Global.asax

protected void Application_Start()
{
   
// Call Here.
   
AutofacConfig.ConfigureContainer();

    AreaRegistration.RegisterAllAreas();
   
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
   
RouteConfig.RegisterRoutes(RouteTable.Routes);
   
BundleConfig.RegisterBundles(BundleTable.Bundles);
}

And you’re all set. From here, you can now use ConcreteObjectConfiguration on all your controllers. Notice below that we don’t even have an empty constructor. Without an IOC container, you can’t do that as it will throw you an error saying you need a parameter-less constructor

public class HomeController : Controller
{
   
public IWebConfiguration InjectedConfiguration { get; set; }
   
public HomeController(IWebConfiguration injectedConfiguration)
    {
        InjectedConfiguration
= injectedConfiguration;
   
}
        
   
public ActionResult Index()
    {
        ViewBag.Message
= $“The Webserver is in {InjectedConfiguration.WebServer}”;
        return
View();
   
}     
}

The object we created earlier will be passed to your constructor, and therefore we can do whatever we want with it. I chose to assign it to a public property so that

  • We can create a Unit Test for the Controller
  • We can use the concrete object for all of the Actions.

Here’s what it looks like now

image

Scheduling SSRS with Dynamic Dates

You can schedule SSRS Reports, via Subscriptions, but the issue is that you can easily set custom parameters except the date.

This became a problem for me because:

  • I want the users to pick a Start Date and End Date when they open the report. I don’t want it to default to anything because it minimises the reusability
  • I want to schedule the reports to automatically generate for the previous month. SSRS doesn’t allow me to do that from the My Subscriptions page

From the SSRS Home Page, look at the upper-right corner and click on My Subscriptions. This will open up your scheduled reports. In the screenshot below, you’ll notice that you can choose from a list: Any list, that is, including dynamically-loaded ones. This limitation forces you to type in a static date, which defeats the purpose of scheduling if you want your users to always pick a date when they run the same report themselves.

image

Here’s how I went around the limitation:

Steps

  • Create the Dynamic Dates: I created date parameters that will hold the actual date and time used by the report. Make sure they’re hidden, so the user won’t see them.

image

  • Create the parameter that will tell the report whether to use the Dates entered by the user, or the one that we want to override it with. It will make more sense on the next bullet point.

image

Make sure it’s an integer and that it’s hidden, so the user won’t see it.

image

Set the default value to 0

image

  • Create a new Shared Dataset with this Query. In my project, i named it dsDateRange

  DECLARE @mStartDate DATETIME = @StartDate
  DECLARE @mEndDate DATETIME = @EndDate

  if @DateRange = 1
  BEGIN
    —
    — Last Month
    —

    SET @mStartDate = DATEADD(m,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()), 0))
    SET @mEndDate = DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
  END
  SELECT @mStartDate AS StartDate, @mEndDate AS EndDate

We set the default value of @mStartDate and @mEndDate to what the users selected by default. Now, let’s look at @DateRange: If the date range is 0, then do nothing. If the @DateRange is 1, then we set @mStartDate and @mEndDate for the first and last date of last month respectively. Now, you can do whatever you want with what the @DateRange corresponds with.

  • Set @mStartDate and @mEndDate with the values from the Dataset.

image

@mStartDate and mEndDate will always get a value depending on @DateRange. If it is opened by the user, it will all be invisible to them and it will have a default value of 0.

Looking at Subscriptions

Now, if you’ll go to My Subscriptions, you will find that you have the Date Range, mStartDate and mEndDate. Set Date Range to 1, indicating that we want to use our custom Data Set code. Also set mStartDate and mEndDate to Default.

image

Now you’re good to go.

  • Use @mStartDate in your Datasets and text fields instead of @StartDate.

image

Optional

You can make scheduling prettier by instead of making the Date Range an integer, make it a selection from a list. Make another Dataset. This will consist of a Value and a Label.

image

Keep the @DateRange an integer, but on the Available Values, choose the Dataset that we just created.

image

Getting Started with ASP.NET Core

What is it?

ASP.NET Core is an open source web framework for building modern web applications that can be developed and run on Windows, Linux and the Mac. It includes the MVC framework, which now combines the features of MVC and Web API into a single web programming framework.

What You Need

Creating from the Visual Studio Template

From File > New > Project, you will see the .NET Core template. For this quick blog, i chose the Web Application. MVC pattern is obviously a default.

image

If you instead go to the Web Section, you will have these templates

  • NET Web Application – the ASP.NET application templates you’ve known and used
  • NET Core Web Application (.NET Core) – This will start you with a cross-platform compatible project that runs on the .NET Core framework
  • NET Core Web Application (.NET Framework) – This starts a new project that runs on the standard .NET Framework on Windows

What You’ll Notice

  • Restructure: Core is supposed to be a much smaller and modular: And so you’ll notice
  • Lightweight: Web Applications, whether it be the legacy Webforms, or MVC has been a hog in the last few releases as Microsoft likes to showcase what you can do out of the box. That’s all good, except that if you don’t do a lot of cleanup, you’ll end up with deploying a lot of stuff to production that you don’t really need
  • Initial Download of Packages: Yes, it’s modular and that’s probably the first thing you’ll notice as you create a project. It will pick up the necessary Nuget packages for you. That tells you that these packages aren’t tightly integrated with the framework much like System.Web is.
  • Change in Visual Studio files: You’ll notice that .csproj has been replaced by project.json. It was done this way to make development in Mac a first class citizen. It also makes it easier to modify the project options because it’s json. The same is true with every other files that used to be exclusively associated with Visual Studio

My first ASP.NET Core Application

https://github.com/johnconraddomingo/AspNetCore.FirstAspNetCore

Sources:

https://blogs.msdn.microsoft.com/webdev/2016/06/27/announcing-asp-net-core-1-0/
https://www.microsoft.com/net/core#windows
https://dusted.codes/understanding-aspnet-core-10-aka-aspnet-5-and-why-it-will-replace-classic-aspnet

Entity Framework Code First

What is it?

Entity Framework is a relational mapper that allows you to create your database schema by starting with your models and telling the ORM how each component should be created as well as how they’re related to each other. It is primarily used as a facilitator of Domain-Driven Design, but more on that later. Maybe.

Why use Code First?

Based on my experience, it allows for

  • More control over your database and models: You can practically create your database in a very few lines
  • Not having to worry about creating your database. You just have to know where the server is and which rights you should give your solution. In the end it all comes down to ease of deployment
  • Not having to worry about your SQL Statements. You will mostly be using LINQ, which (I  hope) you’re already using anyway. Saving your changes is as easy as calling SaveChanges();

Why it’s not for you

  • Starting out can be a bit of a pain, as there’s a steep learning curve.  Like really, especially when creating your database. It throws out error messages that doesn’t even match what the issue is. You just have to overcome that initial struggle, then it’s smooth sailing.
  • Although it’s a good thing to not having to worry about SQL Statements, it can also work against you depending on your habits as a programmer but if you have proper unit tests, you should be fine.

Getting Started

We’re using a Patient Management System for a sample. All it does is take the name and time on a table with a constraint and display the same data just to prove that we can insert and read. Grab my sample code here: https://github.com/johnconraddomingo/EfCodeFirst.PatientManagement

This sample uses Entity Framework  6.1.3

Basic Components

Entities: The coded representation of database tables

We’re using Patient and Appointment.

public class Patient
{
  public Patient()
  {
       PatientAppointments = new List<Appointment>();
   }
   public int PatientId {get;set; }
   public string PatientName { get;set; }

   public virtual ICollection<Appointment> PatientAppointments{ get;set; }
}

Each patient can potentially contain multiple Appointments. And this relationship is defined by the ICollection in the parent. Notice the PatientAppointments in the Patient class.

public class Appointment
{
    public int AppointmentId { get; set; }
    public DateTime AppointmentDateTime { get; set; }
}

You’ll notice that the table looks like a regular class: And that’s the beauty of it all. We isolate the database part and just focus on our object. Now here’s where we

Entity Mapping

Now here’s where we tell EF the attributes of the fields such as

  • The Primary Keys
  • If they’re mandatory or optional fields
  • Max Length
public class PatientMap : EntityTypeConfiguration<Patient>
{
    public PatientMap()
    {
        // Key
        HasKey(k => k.PatientId);

        // Properties
        Property(p => p.PatientId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        Property(p => p.PatientName).IsRequired().HasMaxLength(50);

        // To Table
        ToTable("Patients");
    }
}

  • The table name that they correspond to
public class AppointmentMap : EntityTypeConfiguration<Appointment>
    {
        public AppointmentMap()
        {
            // Key

            HasKey(k => k.AppointmentId);

            // Properties
            Property(p => p.AppointmentId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            Property(p => p.AppointmentDateTime).IsRequired();

            // To Table
            ToTable("Appointments");
        }
    }

The DB Context

This is our representation of the Database. Here we define

  • The Database name
  • Which tables we want to include in our database
  • The mapping classes that we defined earlier
  • Other configs
public class PatientManagementDatabase : DbContext
{
    public PatientManagementDatabase() : base("PatientManagementContext")
    {
        Configuration.LazyLoadingEnabled = true;
        Configuration.ProxyCreationEnabled = false;
    }

    public DbSet<Patient> Patient { get; set; }
    public DbSet<Appointment> Appointment { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new AppointmentMap());
        modelBuilder.Configurations.Add(new PatientMap());
    }
}

Create Datasource

This is where we put everything together: We tell EF how to create the database. You decide where to call this method: Beginning of your application? App_Start?  Either way, it should be safe to call it anytime because within the initialiser you tell the framework when to create.

private static void CreateDatasource()
{
    Database.SetInitializer(new CreateDatabaseIfNotExists<PatientManagementDatabase>());

    var context = new PatientManagementDatabase();
    context.Patient.Create();
    context.Appointment.Create();

    context.SaveChanges();
}

That’s it! Now, we just play around with it by LINQ. This is a very simple example that you can build your more complex applications from.

You can download the sample from https://github.com/johnconraddomingo/EfCodeFirst.PatientManagement

Responsive Web Design Basics

Definition

Quick and Dirty definition: Responsive Web Design allows your website to look good on whatever device you’re viewing it from whether it be your computer, tablet or phone. It is usually done using (but not limited to) HTML and CSS.

3 Useful Tricks

We’ll refer to the sample below

<meta name="viewport" 
 content="width=device-width, initial-scale=1.0">
<html>
  <style>
    #divHello{ font-size:20vh;}
    #divWorld{ font-size:25px;} 
      
    @media only screen and (max-width: 600px){
    /* For phones */
    
    #divWorld{
      text-align:center;
      width: 100%
     }
   }
  </style>
  <body>
   <div id="divHello">Hello</div>
   <div id="divWorld">World</div>
  </body>
</html>

Here are some useful tricks that you can do, obviously on top of the usual width = 100%, min-width, max-width and strategically placing your components.

The Viewport meta tag

Viewport tells the browser how to control the page’s dimensions. 10px looks much much smaller on your phone than on your computer. The Viewport tag tells your browser to scale the page based on how wide your device is.

  • A <meta> viewport element gives the browser instructions on how to control the page’s dimensions and scaling.
  • The width=device-width part sets the width of the page to follow the screen-width of the device (which will vary depending on the device).
  • The initial-scale=1.0 part sets the initial zoom level when the page is first loaded by the browser.

Vh, Vw and Vmin and Vmax

These units scale to the size of your viewport.

  • vw: 1/100th viewport width
  • vh: 1/100th viewport height
  • vmin: 1/100th of the smallest side
  • vmax: 1/100th of the largest side

Looking at the sample above, line divHello tells you to scale to the height. Running this HTML and resizing your browser height will resize the font size on the fly. Resizing your browser’s width will do nothing.

If you choose vmin, it will choose the smaller of the viewport width and height. Vmax will choose the larger.

Media Queries

CSS3 Media Queries defines which CSS to change or add when the device falls on the defined min-width or max-with. In the sample above, you’ll notice that making the browser’s width smaller forces divWorld to 100% width.

Take note that you can add in multiple queries. For instance, you can have a CSS based on a specific device in mind. Here’s a reference

/* Smartphones (portrait and landscape) ----------- */
@media only screen
and (min-width : 320px)
and (max-width : 480px) {
/* Styles */
}
 
/* Smartphones (landscape) ----------- */
@media only screen
and (min-width : 321px) {
/* Styles */
}
 
/* Smartphones (portrait) ----------- */
@media only screen
and (max-width : 320px) {
/* Styles */
}
 
/* iPads (portrait and landscape) ----------- */
@media only screen
and (min-width : 768px)
and (max-width : 1024px) {
/* Styles */
}
 
/* iPads (landscape) ----------- */
@media only screen
and (min-width : 768px)
and (max-width : 1024px)
and (orientation : landscape) {
/* Styles */
}
 
/* iPads (portrait) ----------- */
@media only screen
and (min-width : 768px)
and (max-width : 1024px)
and (orientation : portrait) {
/* Styles */
}
 
/* Desktops and laptops ----------- */
@media only screen
and (min-width : 1224px) {
/* Styles */
}
 
/* Large screens ----------- */
@media only screen
and (min-width : 1824px) {
/* Styles */
}
 
/* iPhone 4 ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}

 

Added References:

https://en.wikipedia.org/wiki/Responsive_web_design
http://www.w3schools.com/css/css_rwd_viewport.asp
https://paulund.co.uk/understanding-the-viewport-meta-tag