Angular 2! Why did you invent a beautiful slow and useless code? – for(var key in response.json())

this.http.get(url, this.options).subscribe(
    response => {
        for (var key in response.json()) {
            if (response.json().hasOwnProperty(key)) {
               // code here
            }
        }
);

Angular 2!  Why did you invent the code above?  Pretty to look at but very slow and useless!  Is it just because for the show! or is it, that we novice, didn’t know how to use it.  Regardless,  it is 1,000 x slower than a standard JQuery AJAX call.  Do not use it guys!  Instead follow the code below, which is an alternative code provided by my colleague.

this.http.get(url, this.options).subscribe(
    response => {
        var newResponse = new wijmo.collections.ObservableArray(response.json());
        for (var i = 0; i < newResponse.length; i++) {
               // code here
        }
);

The above code transfers the response values to a new array, in the code, we used premium controls, e.g., wijmo, but you can use any array objects for your projects.  This code is so much faster than the first one, which most of the Internet Angular 2 examples on services is based upon.  Below is the sample complete code on real application.

untitled

And if you find this blog helpful, you can make the donation by clicking the Paypal button below.



									
Posted in Uncategorized

Having problem with Pre-flight CORS request with your Angular 2 App and Web API 2?

There are many solutions posted regarding Pre-Flight CORS error at the client application when accessing your ASP.Net Web API 2 server application.  The problem is caused by CORS security implementation at the browser level, the solution is very simple though, just enable the CORS response at the server application, in our case, we should enable CORS in our ASP.Net Web API 2 application.  But it is easier said than done, because there are two issues to consider:

  1. Token authentication via /Token – asking for authorization by authentication.
  2. Api Bearer authorization access via /Api – asking for resources using authorized bearer token.

To solve the first issue, you just need to modify the Web.config file of your ASP.Net Web API 2 server application by adding the following entries inside the <configuration> …</configuration> tag.

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>
</system.webServer>

To solve the second issue just insert the following code in the Register method at the App_Start\WebApiConfig.cs file.

public static void Register(HttpConfiguration config)
{
     var cors = new EnableCorsAttribute("*", "*", "*");
     config.EnableCors(cors);

     config.SuppressDefaultHostAuthentication();
     config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

     config.MapHttpAttributeRoutes();
     config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
}

But you cannot do both!  what I mean is, if you fix the first issue, the second issue will not work and vice versa.  It’s a f$%k’n nightmare!  And to add to the injury, fixing the second issue requires you to add new references to your project that may conflict to the current version.

The real solution to the problem is to disregard both the solutions posted above and just use the OWIN.CORS package (Install-Package Microsoft.Owin.Cors), then modify the the ConfigureAuth method in the App_Start\Startup.Auth.cs file with the following code:

public void ConfigureAuth(IAppBuilder app)
{
     app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
     app.UseCookieAuthentication(new CookieAuthenticationOptions());
     app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
     app.UseOAuthBearerTokens(OAuthOptions);
{

The above solution enables CORS at startup, thus, this will include both the /Token and /Api routes to the CORS Pre-flight.

Here are the codes and screen-shots of the UI at the client side (I’m using Angular 2 Typescript by the way), just google for the jQuery equivalent.  My goal in life is not to write anymore Javascript code! :p

Authorization Token:

let url = "http://localhost:9000/Token";
let body = "username=" + username + "&password=" + password + "&grant_type=password";
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });        

this._http.post(url, body, options).subscribe(
    response => {
        localStorage.setItem('access_token', response.json().access_token);
        localStorage.setItem('expires_in', response.json().expires_in);
        localStorage.setItem('token_type', response.json().token_type);
        localStorage.setItem('userName', response.json().userName);

        window.location.replace('/dashboard');
    },
    error => {
        console.log(error.json().error_description);
    }
);

u1

Resources API:

let url = "http://localhost:9000/Api/TableGroups";
let headers = new Headers({ 'Authorization': 'Bearer ' + localStorage.getItem('access_token') });
let options = new RequestOptions({ headers: headers }); 

this.http.get(url, options)
    .subscribe(
        response => {
            for (var key in response.json()) {
                if (response.json().hasOwnProperty(key)) {
                    data.push({
                        id: response.json()[key].Id,
                        tableCode: response.json()[key].TableCode,
                        tableGroupId: response.json()[key].TableGroupId,
                        tableGroup: response.json()[key].TableGroup,
                        topLocation: response.json()[key].TopLocation,
                        leftLocation: response.json()[key].LeftLocation
                    });
                }
            }
        },
        error => {

        }
    );

u2

Thats it!  If you are using Innosoft POS, the screen shots looks familiar!  Yes! we are modifying the POS using pure HTML 5 and sad to say I will be using Google technology!

And if you find this blog helpful, you can make the donation by clicking the Paypal button below.



									
Posted in ASP.NET

Hosting Angular 2 in Windows Azure Error “The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.”

You will definitely encounter an error “The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.” when your Angular 2 application is hosted in Windows Azure Web App Service.  This error happens when the URL is feed directly by the user in the browser URL address or if you use window.location.replace to redirect page.

To remedy the problem, you need to provide a web.config file into your Angular 2 application.  Put the web.config file at the root of the application folder.  The content in the web.config file are just redirect rules as seen below:

<?xml version="1.0" encoding="UTF-8"?>

<configuration>
    <system.webServer>
        <rewrite>
        <rules>
        <clear />

        <!-- ignore static files -->
        <rule name="AngularJS Conditions" stopProcessing="true">
        <match url="(app/.*|css/.*|fonts/.*|images/.*|js/.*|node_modules/.*)" />
        <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
        <action type="None" />
        </rule>

        <!-- check if its root url and navigate to default page -->
        <rule name="Index Request" enabled="true" stopProcessing="true">
        <match url="^$" />
        <action type="Redirect" url="/home" logRewrittenUrl="true" />
        </rule>

        <!--remaining all other url's point to index.html file -->
        <rule name="AngularJS Wildcard" enabled="true">
        <match url="(.*)" />
        <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
        <action type="Rewrite" url="index.html" />
        </rule>

        </rules>
        </rewrite>
    </system.webServer>
</configuration>

The first rule is to by pass all static files, so just enumerate all the static files directory.  The second rule is to redirect root URL to your Angular 2 virtual route, as in my example it’s /home.  And the rest has to be redirected to your index.html file.

It is paramount that your index.html file contains <base href=”/” /> in the <head> tag to enable routing.

Thats it! happy Coding! and if you find this blog helpful, you can make the donation by clicking the Paypal button below.

Posted in ASP.NET

Angular 2 and ASP.Net Web API Authentication

Building real word application needs security.  If you have a decoupled application like Angular 2 with ASP.Net Web API data provider, securing your components, pages and API is not as easy as providing method annotations and saving to cookies.  It needs token for every access.  Here are the steps in making this awesome application happens:

First you must enable CORS settings in your Web API application by providing these entries in to your web.config file:

  <system.webServer>
   <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Content-Type" />
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
  </httpProtocol> 
  </system.webServer>

Note: Web API security is beyond the scope of this blog.  Our main focus is Angular 2 client security.

Now lets build our Angular 2 application.  Just make a directory and named it: angular2-auth-sample.  Our editor is Visual Studio Code, to launch we type in code .

Untitled

The first file that we will create is the package.json (Node/Angular dependency packages).

{
  "name": "angular2-quickstart",
  "version": "1.0.0",
  "scripts": {
    "start": "concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "typings": "typings",
    "postinstall": "typings install"
  },
  "license": "HGM",
  "dependencies": {
    "angular2": "2.0.0-beta.9",
    "angular2-jwt": "0.1.8",
    "systemjs": "0.19.24",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "reflect-metadata": "0.1.2",
    "jwt-decode": "^1.5.1",
    "rxjs": "5.0.0-beta.2",
    "zone.js": "0.5.15"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.1.0",
    "typescript": "^1.8.7",
    "typings":"^0.7.5"
  }
}

The second file that needs to be ctreated is the  tsconfig.json (Typescript settings).  Angular 2 is written in Typescript, these settings enables Visual Studio Code to transpile Typescript code to Javascript.

{
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}

The third and final file that needs to be created is the typings.json.

{
  "ambientDependencies": {
    "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#4de74cb527395c13ba20b438c3a7a419ad931f1c",
    "jasmine": "github:DefinitelyTyped/DefinitelyTyped/jasmine/jasmine.d.ts#d594ef506d1efe2fea15f8f39099d19b39436b71"
  }
}

Now that we’ve created the three files, our Visual Studio Code editor will look like this (see image below):

Untitled1

Now run npm install to install the packages.  Installing the packages may take more than a minute depending on your Internet connection.

Untitled3

Once done, its time to write the code!

The first code that we are going to write is the index.html file.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    
    <title>angular2-auth-sample</title>
    
    <!-- Base href routing -->
    <script>document.write('<base href="' + document.location + '" />');</script>
   
    <!-- Standard Angular 2 Modules + Routing + Http -->
    <script src="node_modules/es6-shim/es6-shim.min.js"></script>
    <script src="node_modules/systemjs/dist/system-polyfills.js"></script>
    <script src="node_modules/angular2/es6/dev/src/testing/shims_for_IE.js"></script>   

    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>

    <script src="node_modules/angular2/bundles/router.dev.js"></script>
    
    <script src="node_modules/angular2/bundles/http.dev.js"></script>
    
    <!-- Configure SystemJS -->
    <script>
      System.config({
        packages: {        
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('app/main').then(null, console.error.bind(console));
    </script>     
</head>

<body>
    
    <app>Loading...</app>

</body>

</html>

Now that our Index.html file is ready!  It’s time to write the real Angular 2 codes.  But first we must create a directory structure.  For the structure see the image below:

Untitled4

At the root of our app folder we will create our main.ts component. The main.ts component boots the entire Angular 2 application:

import { bootstrap } from 'angular2/platform/browser';
import { App } from './app/app';

bootstrap(App);

As you can see the main.ts component just calls on the app.ts component in the app folder, which leads us to our next code:

import { Component } from 'angular2/core';
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router';
import { Http } from 'angular2/http';

import { HomeComponent } from '../home/home';
import { LoginComponent } from '../login/login';
import { DashboardComponent } from '../dashboard/dashboard';

@Component({
  selector: 'app',
  template: `
        <h3>{{title}}</h3>
        <br/>
        <a [routerLink]="['Home']">Home</a>
        <a [routerLink]="['Login']">Login</a>
        <a [routerLink]="['Dashboard']">Dashboard</a> 
        <br/>
        <router-outlet></router-outlet>
  `,
  directives: [ROUTER_DIRECTIVES],
  providers: [
    ROUTER_PROVIDERS
  ]
})
@RouteConfig([
  {
    path: '/home',
    name: 'Home',
    component: HomeComponent,
    useAsDefault: true
  },
  {
    path: '/login',
    name: 'Login',
    component: LoginComponent
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: DashboardComponent
  }
])
export class App {
    private title = 'App';
}

In the above code, we import the Router and Http Angular 2 components.  Then we configure our Route. Very Important! take note of the template, you should put in a tag named router-outlet. This tag will provide outlet for all subsequent Angular 2 components.

Our home.ts component is a public component, meaning, anyone can access it.  Aside from that I made it to display the Token information.  So if the user is not logged-in, there are no information, otherwise you’ll see the entire token information.  Warning!  token information may differ from provider to provider, we are using ASP.Net Web API Membership Authentication Token.

import {Component} from 'angular2/core';

@Component({
    selector: 'home',
    template: `
        <h4>Home</h4>
        <br/>
        <p>Token:<b>{{access_token}}</b></p>
        <p>Expires In:<b>{{expires_in}}</b></p>
        <p>Token Type:<b>{{token_type}}</b></p>
        <p>Username:<b>{{userName}}</b></p>    
    `
})
export class HomeComponent {
    private access_token = localStorage.getItem('access_token');
    private expires_in = localStorage.getItem('expires_in');
    private token_type = localStorage.getItem('token_type');
    private userName = localStorage.getItem('userName');     
}

The next component is the login.ts component.  This is where you let your user type in the username and password and get authenticated through your API.

import {Component} from 'angular2/core';
import {Http, Headers, RequestOptions, HTTP_PROVIDERS} from 'angular2/http';
import {Router} from 'angular2/router';

@Component({
    selector: 'login',
    template: `
        <h4>Login</h4>
        <br/>
        <form role="form" (submit)="login($event, username.value, password.value)">
            <input type="text" #username id="username" required="required" placeholder="Username"> <br/>
            <input type="password" #password id="password" required="required" placeholder="Password"> <br/>
            <button type="submit">Login</button> <br/>
        </form>
    `,
    providers: [
        HTTP_PROVIDERS
    ]    
})
export class LoginComponent {
    private title = 'Login';

    constructor(private _router: Router,  private _http: Http) {
    }   
      
    login(event, username, password) {
        event.preventDefault();
        
        let url = "http://[Your URL]";
        let body = "username=" + username + "&password=" + password + "&grant_type=password";
        let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
        let options = new RequestOptions({ headers: headers });        
        
        this._http.post(url, body, options).subscribe(
            response => {
                localStorage.setItem('access_token', response.json().access_token);
                localStorage.setItem('expires_in', response.json().expires_in);
                localStorage.setItem('token_type', response.json().token_type);
                localStorage.setItem('userName', response.json().userName);
                this._router.navigate(['Dashboard']);
            },
            error => {
                alert(error.text());
                console.log(error.text());
            }
        );
    }    
}

Very important to include HTTP_PROVIDERS in the class annotation and a constructor with two parameters, the router and http variables. Take note also of the template, it is just an ordinary HTML form entry except for the (submit) tag that calls on the method login in our login.ts component.  In the method login we execute the http.post function, to post entries of our login form to our API for authentication.  If successful, we saved the token in our localStorage.  Thats how simple to logged in users using Angular 2.

The dashboard.ts component is a private component, meaning you need to logged in before you could open this component.

import {Component, OnInit} from 'angular2/core';
import {Router} from 'angular2/router';

@Component({
    selector: 'dashboard',
    template: `
<h4>Dashboard</h4>
<form role="form" (submit)="logout()">
            <button type="submit" class="btn btn-danger btn-lg">Logout</button>
        </form>

    `
})
export class DashboardComponent implements OnInit {
    constructor(private _router: Router) {
    }
    ngOnInit() {
        if (!localStorage.getItem('access_token')) {
            this._router.navigate(['Login']);
        }
    }
    logout() {
        localStorage.removeItem('access_token');
        localStorage.removeItem('expires_in');
        localStorage.removeItem('token_type');
        localStorage.removeItem('userName');

        this._router.navigate(['Login']);
    }
}

The above code is easy to read.  What is important here is the implementation of the ngOnInit method, which we just check for the localStorage access_token and if empty we route the component back to login.ts component.

Thats it!  To summarize, we have three basic components; home.ts (public component), login.ts (public component) and dashboard.ts (private/secure component).  To secure the component we just need to implement the ngOnInit method.  Very Simple!

A pinch of CSS and Twitter Bootstrap template you could have this:

Happy Coding! And if you find this blog helpful, you can make the donation by clicking the Paypal button below.



									
Posted in ASP.NET

Part 2: Angular 2 + MVC ASP.NET using Visual Studio Code.

Now that our ASP.NET Visual Studio Code project is wired with Angular 2 and Typescript (see previous post), its time to write our cool “Hello World!” Angular 2 code.

For me, in order for you to write a simple SPA application using Angular 2, you just need the following: (very simple isn’t it! easy :))

  • HTML Landing Page
  • Angular 2 codes (wwwroot/app/*.ts)

To create an HTML Landing Page with ASP.NET you need to create a Controller and a View.  Below is the Controller named /Controller/SoftwareController.cs:

using Microsoft.AspNet.Mvc;

namespace rymage.Controllers
{
    public class SoftwareController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

Then create a view /View/Software/Index.cshtml:

<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.33.3/es6-shim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.16/system-polyfills.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.7/angular2-polyfills.js"></script>
<script src="https://code.angularjs.org/tools/system.js"></script>

<!-- configure system loader first -->
<script>
    System.config({
        defaultJSExtensions: true,
        paths: {
            'angular2/*': 'node_modules/angular2/*',
            'rxjs/*': 'node_modules/rxjs/*'
        }
    });
</script>

<script src="https://code.angularjs.org/2.0.0-beta.7/Rx.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.7/angular2.dev.js"></script>

<script>
      System.import('app/boot')
            .then(null, console.error.bind(console));
</script>

<my-app>Loading...</my-app>

Notice that the file structure, naming and location of the two files follows ASP.NET MVC rules, the only difference is that the razor CSHTML file (View) contains wierd Javascript libraries and customised html tag <my-app>.  These modifications can be found in the Google Angular IO page.

Now its time for our Angular 2 codes!  All codes can be stored in your wwwroot directory.  In my case I created a sub directory wwwroot/app.  In this directory I will put in all my codes.

The first code is the boot.ts code, you can associate this code as your main() function for your Angular 2 application, which is called in your landing page (see the CSHTML above System.import code) and will run our appComponent.ts code.  See the code below:

import {bootstrap} from 'angular2/platform/browser'
import {AppComponent} from './appComponent'
bootstrap(AppComponent);

The second code is the appComponent.ts code, this is my first application component. It will just modify the  CSHTML page and print “Hello World”.

import {Component} from 'angular2/core';
@Component({
    selector: 'my-app',
    template: '
Hello World
'
})
export class AppComponent { }

Take note that these codes are in Typescript (ts), you need to compile it to Javascript (js) by pressing “Command+Shift+B” or “Ctrl+Shift+B” for windows.  If it doesn’t compile please check the version and Typescript configuration as shown in my previous post.

Below is the screenshot of the project with all files created.

Screen Shot 2016-02-24 at 8.13.22 AM

Thats it!  To understand how it works let me give you the step by step flow when you execute the application:

  1. http://localhost:5000  – open the url
  2. http://localhost:5000/Software – call the controller->landing page
  3. “<script https…>” – Loads the Javascript libraries needed by Angular 2
  4. “System.import…” – Imports the boot.js file
  5. “bootstrap(…” – Imports the appComponent.js file to modify the customised tag <my-app>

After all the hassle, you should get this hello world output.

Screen Shot 2016-02-24 at 8.06.45 AM

And if you find this blog helpful, you can make the donation by clicking the Paypal button below.



									
Posted in ASP.NET

Part 1: Angular 2 + MVC ASP.NET using Visual Studio Code.

Hate to admit it but “if you can’t beat them, join them”.  Google’s Angular 2 is to sexy for me to ignore, especially now that it is dressed up with Typescript.   So here’s how you add a SPA page using Angular 2 in a full-blown MVC ASP.NET application using Visual Studio Code Part 1.  (This guide was created using a MACOSX, the command might be different, just take note of the version)

  • dnvm: 1.0.0-rc2-15546
  • tsc: 1.7.5
  • yo: 1.6.0
  • npm: 3.6.0

Please see my previous post on how to install an ASP.NET project in Visual Studio Code.

First is to modify the package.json file as shown below:

{
    "name": "rymage",
    "version": "0.0.0",
    "dependencies": {
        "angular2": "2.0.0-beta.3",
        "systemjs": "0.19.6",
        "es6-promise": "^3.0.2",
        "es6-shim": "^0.33.3",
        "reflect-metadata": "0.1.2",
        "rxjs": "5.0.0-beta.0",
        "zone.js": "0.5.10"
    },
    "devDependencies": {
        "gulp": "^3.9.0",
        "gulp-concat": "2.5.2",
        "gulp-cssmin": "0.1.7",
        "gulp-uglify": "1.2.0",
        "rimraf": "2.2.8"
    }
}

Just disregard the devDependencies, because we don’t use them, it was provided by default when we created our ASP.NET project via Yoeman scaffolding.  Now download the packages using npm by executing this command.

npm install

The next step is to install Typescript.  Typescript enables you to write C# like code and compiles it to Javascript so that your client browser can execute it.  Waa..new language! don’t you worry, Microsoft and Google are endorsing it simultaneously on both the Visual Studio Code and Angular IO sites respectively.  Learning Typescript will be a good investment in the long run! I hope! 🙂

To install Typescript just type in the following command:

npm install -g typescript

Next is to configure Typescript.  To configure you just need a file called, tsconfig.json.  See below the content:

{
  "compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "module": "commonjs",
    "noEmitOnError": true,
    "noImplicitAny": false,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5"
  },
  "exclude": [
    "node_modules"
  ]
}

Now lets wire our Typescript to Visual Studio Code, so that when be save or ts (Typescript file) Visual Studio Code will compile it to js (Javascript file).  To wire, open your Visual Studio Code and press “Command+Shift+P” or “Ctrl+Shift+P” for windows and type “Configure Task Runner”.  Visual Studio Code will automatically create a tasks.json file and then put in the following content:

{
    "version": "0.1.0",
    "command": "tsc",
    "isShellCommand": true,
    "showOutput": "silent",
    "args": [],
    "problemMatcher": "$tsc"
}

Thats it!  now we are ready to write our cool Angular 2 codes using Typescript in Visual Studio Code.  But first let me show you a screenshot of the project!

Screen Shot 2016-02-23 at 6.38.18 PM

Next: Part 2: Angular 2 + MVC ASP.NET using Visual Studio Code

And if you find this blog helpful, you can make the donation by clicking the Paypal button below.



									
Posted in ASP.NET

How to connect your ASP.NET MVC 5 Project to an external SQL Server using Visual Studio Code?

Connecting your new ASP.NET MVC 5 Project using Visual Studio Code is very simple.  First and foremost you must create your project by following my previous post.

Then modify the Startup.cs class file.  There are two modifications, one is the constructor and the other one is the ConfigureServices method:

Constructor modification – Basically what we did was to modify the entry of  Data:DefaultConnection:ConnectionString.  You can, by the way, named the connection to any way you want or you can have multiple connections.

        public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
        {
            // Set up configuration sources.
            var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

            if (env.IsDevelopment())
            {
                // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
                builder.AddUserSecrets();
            }

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
            Configuration["Data:DefaultConnection:ConnectionString"] =
                $@"Data Source=localhost;Initial Catalog=[DATABASENAME];Persist Security Info=True;User ID=[USER];Password=[PASSWORD]";
            //Configuration["Data:DefaultConnection:ConnectionString"] = $@"Data Source={appEnv.ApplicationBasePath}/rymage.db";
        }

ConfigureService Method modification – Now for this modification you are to change your EntityFramework driver from Sqlite to SqlServer and use the default connection string you just modified at the constructor.

        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            // services.AddEntityFramework()
            //    .AddSqlite()
            //    .AddDbContext<ApplicationDbContext>(options =>
            //        options.UseSqlite(Configuration["Data:DefaultConnection:ConnectionString"]));

            services.AddEntityFramework()
                    .AddSqlServer()
                    .AddDbContext<ApplicationDbContext>(options =>
                         options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc();

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();
        }

Now compile and run your application (dnx: Run Command->dnx web).  You should be able to see your ASP.NET membership in your database, like the image below:

b1

That’s it!  And if you find this blog helpful, you can make the donation by clicking the Paypal button below.



									
Posted in ASP.NET

How to setup an ASP.NET MVC 5 with Entity Framework and Membership using Visual Studio Code?

This is my first post for this year, it is a pretty delayed update (ごめんなさい), been busy (忙しい), but I can’t wait to share to you guys one of the coolest feature of the new ASP.NET.  The ability to run ASP.NET on any operating system using Visual Studio Code, how cool is that!  Microsoft totally overhauled the entire product and a paradigm shift is absolutely necessary for old developers like me.  Wow!  so lets get started, shall we!

First download Visual Studio Code (the new IDE) using this link: https://code.visualstudio.com/Download

Since the new IDE is only an editor, you will need to install a package manager.  The package manager that you should install is npm.  npm is a package manager associated with nodejs, so just download nodejs using this link (https://nodejs.org/en/) and install.  Boom!

The next to be installed is the ASP.NET execution environment, the new execution environment is ASP.NET 5/DNX.  The new execution environment can run on any operating system, e.g., Windows, MAC, Linux, etc.  I am using a Windows machine so I’ll be using a command line and sample image below:

@powershell -NoProfile -ExecutionPolicy unrestricted -Command "&{$Branch='dev';iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.ps1'))}"

b5

After the installation make sure you type in the following command:

dnvm upgrade

So now we have our IDE Editor (Visual Studio Code),  Package Manager (npm) and Execution Environment (dnvm).  We are ready to build our first application!

To create your first application just type in the following commands:

npm install -g yo grunt-cli generator-aspnet bower
yo aspnet
cd <NAMEOFYOURAPP>
dnu restore
code

The first command,”npm..”, installs all packages necessary to build your first application.  The second command “yo…” creates your application directory and ASP.NET base code scaffolding.  By the way, choose “Web Application” from the list provided by the second command so that Entity Framework and Membership are included in the scaffolding.

Go inside to your application directory by typing “cd” command, once inside the directory type “dnu…”.   This step enables you to download all the necessary bin packages for your project, e.g., Entity Framework, ASP.NET Core, etc.  via NUGET!  The reason why you need this command is that the scaffolding you just downloaded does not contain any references, this will download those references for you.

The last command is “code”, this will execute and run Visual Studio Code.  And now you will see this:

b1

To test if you can run your application, just press Ctrl+Shift+P, then type dnx: Run Command: See image below: (DO THIS TWICE, to remove the Omnisharp error)

b2

Actually when your doing the dnx: Run Command you are already compiling and executing your application.  And take note of URL http://localhost:<PORT> as shown in the image below.  Open a browser and type that URL.

b3

Now you have a running ASP.NET 5 Application with Entity Framework and Membership!

b4

That’s it!  The next blog will be configuring your data, till then! and if you find this blog helpful, you can make the donation by clicking the Paypal button below.



									
Posted in ASP.NET

How to create a customizable Javascript calendar using Wijmo 5 FlexGrid control.

Lately I’ve been converting to premium controls for all my UI needs, one of my favorite is Wijmo 5.  I’m not selling the controls :), I just use it, and so far I really like it.  In this post I will share with you one of its control, that is powerful enough, that you could make a calendar out of it.  The controls are expensive by the way at $495 per developer but its really worth it.

Before we begin creating the calendar, you must first download Wijmo using this link.  We shall be using only the evaluation version.  Once downloaded, import it in your project as shown in the image below:

b1

To use the control you need the following Javascript and CSS file below.  To change the theme of the control you just need to change the CSS file, right now we are using the standard theme.

<script src="/Scripts/jquery-1.10.2.min.js"></script>

<script src="/wijmo/controls/wijmo.min.js" type="text/javascript"></script>
<script src="/wijmo/controls/wijmo.input.min.js"></script>
<script src="/wijmo/controls/wijmo.grid.min.js" type="text/javascript"></script>
<script src="/wijmo/controls/wijmo.chart.min.js"></script>

<link href="/wijmo/styles/wijmo.min.css" rel="stylesheet" />

Now everything is set, its time to put in the HTML code for the UI.  As you can see below it is just a simple Twitter Bootstrap DIV layout, it is compose of two standard controls, Select and Button.

<div class="row">
    <div class="col-lg-2">
        <select id="WebinarMonth" class="form-control">
            <option value="0">January</option>
            <option value="1">February</option>
            <option value="2">March</option>
            <option value="3">April</option>
            <option value="4">May</option>
            <option value="5">June</option>
            <option value="6">July</option>
            <option value="7">August</option>
            <option value="8">September</option>
            <option value="9">October</option>
            <option value="10">November</option>
            <option value="11">December</option>
        </select>
    </div>
    <div class="col-lg-2">
        <select id="WebinarYear" class="form-control">
            <option value="2015">2015</option>
            <option value="2016">2016</option>
            <option value="2016">2017</option>
            <option value="2016">2018</option>
            <option value="2016">2019</option>
        </select>
    </div>
    <div class="col-lg-2">
        <button id="GetCalendar" type="submit" class="btn btn-primary btn-block" onclick="GetCalendar()">Get Calendar</button>
    </div>
</div>

<div class="row">
    <p class="lead">
        <div id="CalendarGrid" class="grid"></div>
    </p>
</div>

Once the UI HTML is ready, its time for the exciting part, the Javascript part :).  There are two functions for this project; MakeCalendarData – prepares the data of the calendar and MakeCalendarGrid – makes the calendar grid.

MakeCalendarData takes in two parameters, the Month and the Year.  In a nutshell, it returns an object called ObservableArray parse per day, e.g., Monday, Tuesday, etc.  which you can provide any content under the switch case routine.  The object return is not an ordinary Javascript array, its an observable array, a Knockout observable array, cool eh!  There is already a built-in Knockout object inside the Wijmo controls, you don’t need to manually code it!

    function MakeCalendarData(Month, Year) {
        var Sun = "", Mon = "", Tue = "", Wed = "", Thu = "", Fri = "", Sat = "";
        var data = new wijmo.collections.ObservableArray();

        // Get the start day, e.g., Monday=1, Tuesday=2, etc.
        var firstDay = new Date(Year, Month, 1);
        var startingDay = firstDay.getDay();

        // Get the month length
        var cal_days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        var monthLength = cal_days_in_month[Month];
        if (Month == 1) { //FEB
            if ((Year % 4 == 0 && Year % 100 != 0) || Year % 400 == 0) {
                monthLength = 29;
            }
        }

        var day = 1;
        for (var i = 0; i < 9; i++) {
            for (var j = 0; j <= 6; j++) {
                if (day <= monthLength && (i > 0 || j >= startingDay)) {
                    switch (j) {
                        case 0:
                            Sun = day.toString();
                            break;
                        case 1:
                            Mon = day.toString();
                            break;
                        case 2:
                            Tue = day.toString();
                            break;
                        case 3:
                            Wed = day.toString();
                            break;
                        case 4:
                            Thu = day.toString();
                            break;
                        case 5:
                            Fri = day.toString();
                            break;
                        case 6:
                            Sat = day.toString();
                            break;
                    }
                    day++;
                }
            }

            data.push({
                Sunday: Sun,
                Monday: Mon,
                Tuesday: Tue,
                Wednesday: Wed,
                Thursday: Thu,
                Friday: Fri,
                Saturday: Sat
            });

            if (day > monthLength) {
                break;
            } else {
                Sun = ""; Mon = ""; Tue = ""; Wed = ""; Thu = ""; Fri = ""; Sat = "";
            }
        }
        return data;
    }

MakeCalendarGrid is a standard Wijmo FlexGrid initialization and customization.  First you make a collection view from the data created in your MakeCalendarData function, then you initialize the DOM.  The rest of the code is just a simple control formatting, just to look good :).

     function MakeCalendarGrid(Month, Year) {
        CalendarData = new wijmo.collections.CollectionView(MakeCalendarData(Month, Year));
        CalendarData.pageSize = 5;

        CalendarGrid.dispose();
        CalendarGrid = new wijmo.grid.FlexGrid('#CalendarGrid');
        CalendarGrid.initialize({
            columns: [
                        {
                            "header": "Sunday",
                            "binding": "Sunday",
                            "width": "7*",
                            "allowSorting": false,
                            "isContentHtml": true,
                            "wordWrap": true
                        },
                        {
                            "header": "Monday",
                            "binding": "Monday",
                            "width": "7*",
                            "allowSorting": false,
                            "isContentHtml": true,
                            "wordWrap": true
                        },
                        {
                            "header": "Tuesday",
                            "binding": "Tuesday",
                            "width": "7*",
                            "allowSorting": false,
                            "isContentHtml": true,
                            "wordWrap": true
                        },
                        {
                            "header": "Wednesday",
                            "binding": "Wednesday",
                            "width": "7*",
                            "allowSorting": false,
                            "isContentHtml": true,
                            "wordWrap": true
                        },
                        {
                            "header": "Thursday",
                            "binding": "Thursday",
                            "width": "7*",
                            "allowSorting": false,
                            "isContentHtml": true
                        },
                        {
                            "header": "Friday",
                            "binding": "Friday",
                            "width": "7*",
                            "allowSorting": false,
                            "isContentHtml": true,
                            "wordWrap": true
                        },
                        {
                            "header": "Saturday",
                            "binding": "Saturday",
                            "width": "7*",
                            "allowSorting": false,
                            "isContentHtml": true,
                            "wordWrap": true
                        }
            ],
            autoGenerateColumns: false,
            itemsSource: CalendarData,
            isReadOnly: true,
            selectionMode: wijmo.grid.SelectionMode.Cell
        });
        CalendarGrid.trackChanges = true;
        CalendarGrid.itemFormatter = function (panel, r, c, cell) {
            if (panel.cellType == wijmo.grid.CellType.Cell) {
                var flex = panel.grid;
                flex.rows[r].height = 80;
            }
        };
    }

Here is a sample screen shot of the calendar in production:

b2

That’s it!  You can get the full ASP.NET source code in Github using this link.  Happy coding and if you find this blog helpful, you can make the donation by clicking the Paypal button below.

Posted in Javascript

How to create an ASP.Net MVC 5 site using bootstrap free templates?

Here are the steps in making a beautiful bootstrap site using ASP.NET MVC 5.

1. Download a free template or you can buy a premium template if you want.  For our example, we will be using the free Grayscale template of StartBootstrap.  After downloading, you should get the following files:

b1

2. Open Visual Studio 2013 and create an ASP.NET Web Application.

b2

In configuring, the application must be MVC.

I included Web API because I used them a lot in my application.

And lastly, it must have an Authentication, I normally use the Individual User Accounts.

The last part is very important, because it’s very hard to add an authentication module once the project has been created, trust me, based on experience.

b3

3.Once the project has been created, the next thing that we should do is to copy the files from our downloaded template to our project.  Make sure to overwrite any directories of the same name.

b4

4. Open the BundleConfig.cs file in the App_Start directory and comment all contents in the RegisterBundles method as shown in the image below:

b5

5. Now we will modify the Views.  In modifying the Views, all you need to do is to open the Index.html file included in the template and copy it to the corresponding Views.

The first View that will modify is the _Layout.cshtml, which is located in the Views\Shared folder.  Delete all the content and replace it with the code below.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Grayscale - Start Bootstrap Theme</title>
    <!-- Bootstrap Core CSS -->
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <!-- Custom CSS -->
    <link href="/css/grayscale.css" rel="stylesheet">
    <!-- Custom Fonts -->
    <link href="/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>

<body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top">
    @RenderBody()
</body>

</html>

6. Next, is to modify the Index.cshtml, which is located in Views\Home.  Delete all the content and replace it with the code below.

@{
    ViewBag.Title = "Home Page";
}

    <!-- Navigation -->
<nav class="navbar navbar-custom navbar-fixed-top" role="navigation">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">
                <i class="fa fa-bars"></i>
            </button>
            <a class="navbar-brand page-scroll" href="#page-top">
                <i class="fa fa-play-circle"></i>  <span class="light">Start</span> Bootstrap
            </a>
        </div>
        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse navbar-right navbar-main-collapse">
            <ul class="nav navbar-nav">
                <!-- Hidden li included to remove active class from about link when scrolled up past about section -->
                <li class="hidden">
                    <a href="#page-top"></a>
                </li>
                <li>
                    <a class="page-scroll" href="#about">About</a>
                </li>
                <li>
                    <a class="page-scroll" href="#download">Download</a>
                </li>
                <li>
                    <a class="page-scroll" href="#contact">Contact</a>
                </li>
            </ul>
        </div>
        <!-- /.navbar-collapse -->
    </div>
    <!-- /.container -->
</nav>
<!-- Intro Header -->
<header class="intro">
    <div class="intro-body">
        <div class="container">
            <div class="row">
                <div class="col-md-8 col-md-offset-2">
                    <h1 class="brand-heading">Grayscale</h1>
                    <p class="intro-text">A free, responsive, one page Bootstrap theme.<br>Created by Start Bootstrap.</p>
                    <a href="#about" class="btn btn-circle page-scroll">
                        <i class="fa fa-angle-double-down animated"></i>
                    </a>
                </div>
            </div>
        </div>
    </div>
</header>
<!-- About Section -->
<section id="about" class="container content-section text-center">
    <div class="row">
        <div class="col-lg-8 col-lg-offset-2">
            <h2>About Grayscale</h2>
            <p>Grayscale is a free Bootstrap 3 theme created by Start Bootstrap. It can be yours right now, simply download the template on <a href="http://startbootstrap.com/template-overviews/grayscale/">the preview page</a>. The theme is open source, and you can use it for any purpose, personal or commercial.</p>
            <p>This theme features stock photos by <a href="http://gratisography.com/">Gratisography</a> along with a custom Google Maps skin courtesy of <a href="http://snazzymaps.com/">Snazzy Maps</a>.</p>
            <p>Grayscale includes full HTML, CSS, and custom JavaScript files along with LESS files for easy customization.</p>
        </div>
    </div>
</section>
<!-- Download Section -->
<section id="download" class="content-section text-center">
    <div class="download-section">
        <div class="container">
            <div class="col-lg-8 col-lg-offset-2">
                <h2>Download Grayscale</h2>
                <p>You can download Grayscale for free on the preview page at Start Bootstrap.</p>
                <a href="http://startbootstrap.com/template-overviews/grayscale/" class="btn btn-default btn-lg">Visit Download Page</a>
            </div>
        </div>
    </div>
</section>
<!-- Contact Section -->
<section id="contact" class="container content-section text-center">
    <div class="row">
        <div class="col-lg-8 col-lg-offset-2">
            <h2>Contact Start Bootstrap</h2>
            <p>Feel free to email us to provide some feedback on our templates, give us suggestions for new templates and themes, or to just say hello!</p>
            <p>
                <a href="mailto:feedback@startbootstrap.com">feedback@startbootstrap.com</a>
            </p>
            <ul class="list-inline banner-social-buttons">
                <li>
                    <a href="https://twitter.com/SBootstrap" class="btn btn-default btn-lg"><i class="fa fa-twitter fa-fw"></i> <span class="network-name">Twitter</span></a>
                </li>
                <li>
                    <a href="https://github.com/IronSummitMedia/startbootstrap" class="btn btn-default btn-lg"><i class="fa fa-github fa-fw"></i> <span class="network-name">Github</span></a>
                </li>
                <li>
                    <a href="https://plus.google.com/+Startbootstrap/posts" class="btn btn-default btn-lg"><i class="fa fa-google-plus fa-fw"></i> <span class="network-name">Google+</span></a>
                </li>
            </ul>
        </div>
    </div>
</section>
<!-- Map Section -->
<div id="map"></div>
<!-- Footer -->
<footer>
    <div class="container text-center">
        <p>Copyright &copy; Your Website 2014</p>
    </div>
</footer>
<!-- jQuery -->
<script src="/js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js"></script>
<!-- Plugin JavaScript -->
<script src="/js/jquery.easing.min.js"></script>
<!-- Google Maps API Key - Use your own API key to enable the map feature. More information on the Google Maps API can be found at https://developers.google.com/maps/ -->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCRngKslUGJTlibkQ3FkfTxj3Xss1UlZDA&sensor=false"></script>
<!-- Custom Theme JavaScript -->
<script src="/js/grayscale.js"></script>

Now run your project.  You should get this beautiful page in your localhost 🙂

b6

For the complete source code, you can download it in GitHub.

That’s it.  Happy coding and if you find this blog helpful, you can make the donation by clicking the Paypal button below.



									
Posted in ASP.NET
Author

Harold Glenn P. Minerva
Software Developer / Tech Enthusiast
Living in the Philippines

View Harold Glenn Minerva's profile on LinkedIn

Instagram

Software Engineer - Seasonal and Range Trading Software. Magenta Trader is a powerful stock market visualization software that increases your probability of trading success.

Software Architect and Founder - Easyfis.com is a multi-tenant cloud-based Software-as-a-Service (SaaS) business app that caters to micro, small and medium trading businesses.

CTO and Co-Founder - We give your company the leverage by providing innovative software solutions products such as Point-of-Sales (POS), Financial Information System (FMIS), Payroll and DTR (HRIS), and many more.

%d bloggers like this: