ASP.NET Core 1.0 – Configure Application Insights

This article will show how to integrate Microsoft Azure Application .Insights into a web application using ASP.NET Core 1.0 to Detect, triage, and diagnose issues in your web application

Visual Studio Application Insights   monitors your live application to help you detect and diagnose performance issues and exceptions, and discover how your app is used. It can be used with a wide variety of application types. It works for apps that are hosted on your own on-premises IIS servers or on Azure VMs, as well as Azure web apps.

STEP 1 – Create Azure Account

You need to get a Windows Azure account. Everyone can open a Windows Azure account for free.

Check the link below for more information.

http://www.windowsazure.com/en-us/pricing/free-trial/ 

STEP 2 – Create a new Application Insight into your Azure Account

After authentication, select new resource, and choose the option Monitoring + Management

A new tab will be open.

Choose the option Application Insight

 

It will appear a new window, to configure this resource has you can check on the image below

On the field Name set your ApplicationInsight configuration Name. On my case it will be called Demo.
Select the application Type, on our demo it will be ASP.NET Web Application.

After select all options, select the button Create.

This resource will be created on the subscription selected and it will be displayed

STEP 3 – Create ASP.NET Core Web Application

Using the Application Insights, it will be necessary create the project ASP.NET Core Web Application

Select the template Web Application on ASP.NET 5 Templates:

Add nuget package Microsoft.ApplicationInsights.AspNetCore to solution

 

STEP 4 – Configure Application Insights into your Web Application

After install the package we should configure the key from the resource created on Azure Portal.

For that select the file appsettings.json on your solution.

Go to the Azure Portal into the Demo Application Insight created and check the settings like on image below:

Open the appsettings.json file and copy your instrumentation key from Azure portal

We also need to change our Startup class like this:

C#
using System; 
 
using System.Collections.Generic; 
 
using System.Linq; 
 
using System.Threading.Tasks; 
 
using Microsoft.AspNetCore.Builder; 
 
using Microsoft.AspNetCore.Hosting; 
 
using Microsoft.Extensions.Configuration; 
 
using Microsoft.Extensions.DependencyInjection; 
 
using Microsoft.Extensions.Logging; 
 
  
 
namespace AppInsightsDemo 
 
{ 
 
    public class Startup 
 
    { 
 
        public Startup(IHostingEnvironment env) 
 
        { 
 
            var builder = new ConfigurationBuilder() 
 
                .SetBasePath(env.ContentRootPath) 
 
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) 
 
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) 
 
                .AddEnvironmentVariables(); 
 
  
 
            if (env.IsDevelopment()) 
 
            { 
 
                // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. 
 
                builder.AddApplicationInsightsSettings(developerMode: true); 
 
            } 
 
            Configuration = builder.Build(); 
 
        } 
 
  
 
        public IConfigurationRoot Configuration { get; } 
 
  
 
        // This method gets called by the runtime. Use this method to add services to the container. 
 
        public void ConfigureServices(IServiceCollection services) 
 
        { 
 
            // Add framework services. 
 
            services.AddApplicationInsightsTelemetry(Configuration); 
 
  
 
            services.AddMvc(); 
 
        } 
 
  
 
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
 
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
 
        { 
 
            loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
 
            loggerFactory.AddDebug(); 
 
  
 
            app.UseApplicationInsightsRequestTelemetry(); 
 
  
 
            if (env.IsDevelopment()) 
 
            { 
 
                app.UseDeveloperExceptionPage(); 
 
                app.UseBrowserLink(); 
 
            } 
 
            else 
 
            { 
 
                app.UseExceptionHandler("/Home/Error"); 
 
            } 
 
  
 
            app.UseApplicationInsightsExceptionTelemetry(); 
 
  
 
            app.UseStaticFiles(); 
 
  
 
            app.UseMvc(routes => 
 
            { 
 
                routes.MapRoute( 
 
                    name: "default", 
 
                    template: "{controller=Home}/{action=Index}/{id?}"); 
 
            }); 
 
        } 
 
    } 
 
}

 

STEP 5 – Test Web Application

To test the integration of Application Insights into our application, just need to run it.

The collect of information, will start immediately.


Resources

Application Insights: https://www.visualstudio.com/products/application-insights-vs 

My personal blog: https://joaoeduardosousa.wordpress.com/  

Advertisements

ASP.NET Core 1.0 – How to configure Angular2 with TypeScript

This article will show how to configure Angular 2 and TypeScript in a ASP.Net Core based API

STEP 1 – Make sure you have installed the prerequisites

Without these requisites, application will not run.

STEP 2 – Create ASP.NET Core Web Application

Go to Visual StudioFile New Project menu, expand the Web category, and pick ASP.NET Core Web Application like on the image below

Select the template Web API:

 

STEP 3 – Prepare Web Application to run Angular 2

At this point, we have our backend part ready. Let’s setup the frontend.

A Web API project can’t serve static files like JavaScripts, CSS styles, images, or even HTML files. Therefore we need to add a reference to Microsoft.AspNetCore.StaticFiles in the project.json:

  • “Microsoft.AspNetCore.StaticFiles”: “1.0.0 “,

And in the startup.cs, we need to add the following line, just before the call of UseMvc().

  • app.UseStaticFiles();

Another important thing we need to do in the startup.cs is to support the Routing of Angular 2. If the Browser calls a URL that doesn’t exist on the server, it could be an Angular route. Especially if the URL doesn’t contain a file extension.

Just before we call UseStaticFiles() insert the following code:

C#
app.Use(async (context, next) => 
{ 
    await next(); 
 
    if (context.Response.StatusCode == 404 
        && !Path.HasExtension(context.Request.Path.Value)) 
    { 
        context.Request.Path = "/index.html"; 
        await next(); 
    } 
}); 
 
STEP 4 – Configure Angular 2

 

Now we prepared the ASP.NET Core application to start to follow the angular.io tutorial.

  • You need to create tsconfig.json which is the TypeScript compiler configuration file. It guides the compiler to generate JavaScript files.

C#
{ 
  "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" 
  ] 
 
} 
 
  •  Create a typings.json file in your project folder angular2-demo as shown below:

 

C#
{ 
  "globalDependencies": { 
    "core-js""registry:dt/core-js#0.0.0+20160602141332", 
    "jasmine""registry:dt/jasmine#2.2.0+20160621224255", 
    "node""registry:dt/node#6.0.0+20160621231320" 
  } 
}
  • Add package.json file to your project folder with the below code:

C#
package.json 
{ 
  "name""angular2-demo", 
  "version""1.0.0", 
  "scripts": { 
    "start""concurrent \"npm run tsc:w\" \"npm run lite\" ", 
    "tsc""tsc", 
    "tsc:w""tsc -w", 
    "lite""lite-server", 
    "typings""typings", 
    "postinstall""typings install" 
  }, 
  "license""ISC", 
  "dependencies": { 
    "angular2""2.0.0-beta.7", 
    "systemjs""0.19.22", 
    "es6-promise""^3.0.2", 
    "es6-shim""^0.33.3", 
    "reflect-metadata""0.1.2", 
    "rxjs""5.0.0-beta.2", 
    "zone.js""0.5.15" 
  }, 
  "devDependencies": { 
    "concurrently""^2.0.0", 
    "lite-server""^2.1.0", 
    "typescript""^1.7.5", 
    "typings":"^0.6.8" 
  } 
}
The package.json will contain the packages that our apps require. These packages are installed and maintained with npm (Node Package Manager). To install packages, run the below npm command in command prompt.

 

Create a sub-folder called app/ inside your wwwroot project folder to the place Angular app components.

The files which you create need to be saved with .ts extension. Create a file called environment_app.component.ts in your app/ folder with the below code:

C#
environment_app.component.ts 
 
import {Component, View} from "angular2/core"; 
 
@Component({ 
   selector: 'my-app' 
}) 
 
@View({ 
  template: '<h2>My First Angular 2 App</h2>' 
}) 
 
export class AppComponent { 
} 
 
Next, create environment_main.ts file with the below code:

 

C#
import {bootstrap} from "angular2/platform/browser" 
import {AppComponent} from "./environment_app.component" 
 
bootstrap(AppComponent); 
 
The environment_main.ts file tells Angular to load the component.

 

  • Now create a index.html in your project folder angular2demo/ with the below code:

C#
<!DOCTYPE html> 
<html> 
  <head> 
    <title>Hello World</title> 
    "https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.33.3/es6-shim.min.js"> 
    "https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.20/system-polyfills.js"> 
    "https://code.angularjs.org/2.0.0-beta.6/angular2-polyfills.js"> 
    "https://code.angularjs.org/tools/system.js"> 
    "https://code.angularjs.org/tools/typescript.js"> 
    "https://code.angularjs.org/2.0.0-beta.6/Rx.js"> 
    "https://code.angularjs.org/2.0.0-beta.6/angular2.dev.js"> 
     
 
      System.config({ 
        transpiler: 'typescript', 
        typescriptOptions: { emitDecoratorMetadata: true }, 
        packages: {'app': {defaultExtension: 'ts'}} 
      }); 
 
      System.import('/app/environment_main') 
            .then(null, console.error.bind(console)); 
     
  </head> 
<body> 
   <my-app>Loading...</my-app> 
</body> 
</html>

 

Angular will launch the app in the browser with our component and places it in a specific location on index.html.

STEP 5 – Run application

Resources

Angular2: http://www.angular2.com/

My personal blog: https://joaoeduardosousa.wordpress.com/ 

ASP.NET Core 1.0 – How to configure Angular2 with TypeScript

This article will show how to configure Angular 2 and TypeScript in a ASP.Net Core based API

STEP 1 – Make sure you have installed the prerequisites

Without these requisites, application will not run.

STEP 2 – Create ASP.NET Core Web Application

Go to Visual StudioFile New Project menu, expand the Web category, and pick ASP.NET Core Web Application like on the image below

Select the template Web API:

 

STEP 3 – Prepare Web Application to run Angular 2

At this point, we have our backend part ready. Let’s setup the frontend.

A Web API project can’t serve static files like JavaScripts, CSS styles, images, or even HTML files. Therefore we need to add a reference to Microsoft.AspNetCore.StaticFiles in the project.json:

  • “Microsoft.AspNetCore.StaticFiles”: “1.0.0 “,

And in the startup.cs, we need to add the following line, just before the call of UseMvc().

  • app.UseStaticFiles();

Another important thing we need to do in the startup.cs is to support the Routing of Angular 2. If the Browser calls a URL that doesn’t exist on the server, it could be an Angular route. Especially if the URL doesn’t contain a file extension.

Just before we call UseStaticFiles() insert the following code:

C#
app.Use(async (context, next) => 
{ 
    await next(); 
 
    if (context.Response.StatusCode == 404 
        && !Path.HasExtension(context.Request.Path.Value)) 
    { 
        context.Request.Path = "/index.html"; 
        await next(); 
    } 
}); 
 
STEP 4 – Configure Angular 2

 

Now we prepared the ASP.NET Core application to start to follow the angular.io tutorial.

  • You need to create tsconfig.json which is the TypeScript compiler configuration file. It guides the compiler to generate JavaScript files.

C#
{ 
  "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" 
  ] 
 
} 
 
  •  Create a typings.json file in your project folder angular2-demo as shown below:

 

C#
{ 
  "globalDependencies": { 
    "core-js""registry:dt/core-js#0.0.0+20160602141332", 
    "jasmine""registry:dt/jasmine#2.2.0+20160621224255", 
    "node""registry:dt/node#6.0.0+20160621231320" 
  } 
}
  • Add package.json file to your project folder with the below code:

C#
package.json 
{ 
  "name""angular2-demo", 
  "version""1.0.0", 
  "scripts": { 
    "start""concurrent \"npm run tsc:w\" \"npm run lite\" ", 
    "tsc""tsc", 
    "tsc:w""tsc -w", 
    "lite""lite-server", 
    "typings""typings", 
    "postinstall""typings install" 
  }, 
  "license""ISC", 
  "dependencies": { 
    "angular2""2.0.0-beta.7", 
    "systemjs""0.19.22", 
    "es6-promise""^3.0.2", 
    "es6-shim""^0.33.3", 
    "reflect-metadata""0.1.2", 
    "rxjs""5.0.0-beta.2", 
    "zone.js""0.5.15" 
  }, 
  "devDependencies": { 
    "concurrently""^2.0.0", 
    "lite-server""^2.1.0", 
    "typescript""^1.7.5", 
    "typings":"^0.6.8" 
  } 
}
The package.json will contain the packages that our apps require. These packages are installed and maintained with npm (Node Package Manager). To install packages, run the below npm command in command prompt.

 

Create a sub-folder called app/ inside your wwwroot project folder to the place Angular app components.

The files which you create need to be saved with .ts extension. Create a file called environment_app.component.ts in your app/ folder with the below code:

C#
environment_app.component.ts 
 
import {Component, View} from "angular2/core"; 
 
@Component({ 
   selector: 'my-app' 
}) 
 
@View({ 
  template: '<h2>My First Angular 2 App</h2>' 
}) 
 
export class AppComponent { 
} 
 
Next, create environment_main.ts file with the below code:

 

C#
import {bootstrap} from "angular2/platform/browser" 
import {AppComponent} from "./environment_app.component" 
 
bootstrap(AppComponent); 
 
The environment_main.ts file tells Angular to load the component.

 

  • Now create a index.html in your project folder angular2demo/ with the below code:

C#
<!DOCTYPE html> 
<html> 
  <head> 
    <title>Hello World</title> 
    "https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.33.3/es6-shim.min.js"> 
    "https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.20/system-polyfills.js"> 
    "https://code.angularjs.org/2.0.0-beta.6/angular2-polyfills.js"> 
    "https://code.angularjs.org/tools/system.js"> 
    "https://code.angularjs.org/tools/typescript.js"> 
    "https://code.angularjs.org/2.0.0-beta.6/Rx.js"> 
    "https://code.angularjs.org/2.0.0-beta.6/angular2.dev.js"> 
     
 
      System.config({ 
        transpiler: 'typescript', 
        typescriptOptions: { emitDecoratorMetadata: true }, 
        packages: {'app': {defaultExtension: 'ts'}} 
      }); 
 
      System.import('/app/environment_main') 
            .then(null, console.error.bind(console)); 
     
  </head> 
<body> 
   <my-app>Loading...</my-app> 
</body> 
</html>

 

Angular will launch the app in the browser with our component and places it in a specific location on index.html.

STEP 5 – Run application

Resources

Angular2: http://www.angular2.com/

My personal blog: https://joaoeduardosousa.wordpress.com/ 

ASP.NET Core 1.0 – Change Bootstrap layout in 3 Steps

Introduction

This article walks you through the steps for creating a ASP.NET Core Web Application using Bootstrap as template for layout and change it to a new one.

STEP 1 – Create ASP.NET Web Application

  • Open Visual Studio 2015 and create a new project of type ASP.NET Core Web Application.
  • On this project I create a solution called ASPNETCoreBootstrap.

  • Press OK, and a new screen will appear, with several options of template to use on our project.
  • Select the option web Application.

STEP 2 – Upgrade version if necessary

You can verify the version of bootstrap on two ways.

First one, accessing the files on lib\bootstrap\dist\css folder. If open for example the file Bootstrap.css, we can check that the version of bootstrap is the 3.3.6

 

Another way to verify the bootstrap version is to check the installed Bower package.

  • Right click the solution and select Manage Bower packages for solution.. option.
  • In the Manage Bower screen, select Installed Packages section.
  • Then select the bootstrap package in the center pane to see the version details.

As you see the version is 3.3.6

STEP 3 – Change Layout

The default bootstrap template used in Visual Studio 2015 is Jumbotron. Jumpotron’s original source code is available here in bootstrap website.

On this sample we will change this template to a free bootstrap template Creative that could be download here:https://startbootstrap.com/template-overviews/creative/.

To made tha t change we need to:

  • Add the style sheet creative.css to the CSS folder
  • Add the style sheet creative.js to the JS folder
  • Add the img folder from template downloaded

Now, open the layout file _Layout.cshtml in the Shared folder under Views Folder and copy the content from index.html to layout.cshtml according to your layout

This is the sample created with solution:

This is the sample after our changes:

Configure Angular4 with TypeScript on a WebApplication with VS 2017

This article will show how to configure Angular 4 and TypeScript in a ASP.Net MVC web application

STEP 1 – Make sure you have installed the prerequisites

Without these requisites, application will not run.

  • Visual Studio 2017
  • TypeScript 2.0 for Visual Studio 2017

STEP 2 – Create ASP.NET MVC Web Application

Go to Visual StudioFile New Project menu, expand the Web category, and pick ASP.NET Web Application like on the image below

Select the template MVC:

 

STEP 3 – Configure Angular 4

We need now to prepare our frontend to run Angular 4

  • Create tsconfig.json which is the TypeScript compiler configuration file.
JavaScript
{ 
  "compilerOptions"{ 
    "target""es5", 
    "module""commonjs", 
    "moduleResolution""node", 
    "sourceMap": true, 
    "emitDecoratorMetadata": true, 
    "experimentalDecorators": true, 
    "lib": [ "es2015""dom" ], 
    "noImplicitAny": true, 
    "suppressImplicitAnyIndexErrors": true 
  } 
} 
  • Add package.json file to your project folder with the below code:

The most important things in your package.json are the name and version fields. Those are actually required, and your package won’t install without them. The name and version together form an identifier that is assumed to be completely unique. Changes to the package should come along with changes to the version.

 

JavaScript
{ 
  "name""angular-quickstart", 
  "version""1.0.0", 
  "description""QuickStart package.json from the documentation for visual studio 2017 & WebApi", 
  "scripts"{ 
    "start""tsc && concurrently \"tsc -w\" \"lite-server\" ", 
    "lint""tslint ./app/**/*.ts -t verbose", 
    "lite""lite-server", 
    "pree2e""webdriver-manager update", 
    "test""tsc && concurrently \"tsc -w\" \"karma start karma.conf.js\"", 
    "test-once""tsc && karma start karma.conf.js --single-run", 
    "tsc""tsc", 
    "tsc:w""tsc -w" 
  }, 
  "keywords": [], 
  "author""", 
  "license""MIT", 
  "dependencies"{ 
    "@angular/common""4.0.2", 
    "@angular/compiler""4.0.2", 
    "@angular/core""4.0.2", 
    "@angular/forms""4.0.2", 
    "@angular/http""4.0.2", 
    "@angular/platform-browser""4.0.2", 
    "@angular/platform-browser-dynamic""4.0.2", 
    "@angular/router""4.0.2", 
 
    "angular-in-memory-web-api""~0.2.4", 
    "systemjs""0.19.40", 
    "core-js""^2.4.1", 
    "rxjs""5.0.1", 
    "zone.js""^0.7.4" 
  }, 
  "devDependencies"{ 
    "concurrently""^3.2.0", 
    "lite-server""^2.2.2", 
    "typescript""~2.0.10", 
 
    "canonical-path""0.0.2", 
    "tslint""^3.15.1", 
    "lodash""^4.16.4", 
    "jasmine-core""~2.4.1", 
    "karma""^1.3.0", 
    "karma-chrome-launcher""^2.0.0", 
    "karma-cli""^1.0.1", 
    "karma-jasmine""^1.0.2", 
    "karma-jasmine-html-reporter""^0.2.2", 
    "protractor""~4.0.14", 
    "rimraf""^2.5.4", 
 
    "@types/node""^6.0.46", 
    "@types/jasmine""2.5.36" 
  }, 
  "repository"{} 
} 

 

  • Create a sub-folder app on the root folder. On this folder we need to create our typescript files:
    • main.ts
    • app.module.ts
    • app.component.ts
    • app.component.html
  • Create your index.html file like showing below:

 

HTML
<!DOCTYPE html> 
<html<head    >document.write(' href="' + document.location + '" />'); 
    <title>Angular4 Routing</title> 
    <base href="/"    <meta charset="UTF-8"    <meta name="viewport" content="width=device-width, initial-scale=1"    <base href="/"    <link rel="stylesheet" href="styles.css" 
    <!-- load bootstrap 3 styles --> 
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" 
 
    <!-- Polyfill(s) for older browsers --> 
     src="node_modules/core-js/client/shim.min.js"> 
     src="node_modules/zone.js/dist/zone.js"> 
     src="node_modules/systemjs/dist/system.src.js"> 
 
     src="systemjs.config.js"> 
            System.import('app/main.js').catch(function (err) { console.error(err); }); 
     
 
</head> 
<body    <my-app>Loading App</my-app> 
</body> 
</html> 
Angular will launch the app in the browser with our component and places it in a specific location on index.html.

 

 

STEP 5 – Run application

Resources

Angular4: https://angular.io/

My personal blog: https://joaoeduardosousa.wordpress.com/ 

Angular4 Routing on VS 2017

This article will show how to configure Angular 4 Routing on an ASP.Net MVC web application

STEP 1 – Make sure you have installed the prerequisites

Without these requisites, application will not run.

  • Visual Studio 2017
  • TypeScript 2.0 for Visual Studio 2017

STEP 2 – Create ASP.NET MVC Web Application

Go to Visual StudioFile New Project menu, expand the Web category, and pick ASP.NET Web Application like on the image below

Select the template MVC:

 

STEP 3 – Configure Angular 4

We need now to prepare our frontend to run Angular 4

  • Create tsconfig.json which is the TypeScript compiler configuration file.
JavaScript
{ 
  "compilerOptions"{ 
    "target""es5", 
    "module""commonjs", 
    "moduleResolution""node", 
    "sourceMap": true, 
    "emitDecoratorMetadata": true, 
    "experimentalDecorators": true, 
    "lib": [ "es2015""dom" ], 
    "noImplicitAny": true, 
    "suppressImplicitAnyIndexErrors": true 
  } 
} 
  • Add package.json file to your project folder with the below code:

The most important things in your package.json are the name and version fields. Those are actually required, and your package won’t install without them. The name and version together form an identifier that is assumed to be completely unique. Changes to the package should come along with changes to the version.

 

JavaScript
{ 
  "name""angular-quickstart", 
  "version""1.0.0", 
  "description""QuickStart package.json from the documentation for visual studio 2017 & WebApi", 
  "scripts"{ 
    "start""tsc && concurrently \"tsc -w\" \"lite-server\" ", 
    "lint""tslint ./app/**/*.ts -t verbose", 
    "lite""lite-server", 
    "pree2e""webdriver-manager update", 
    "test""tsc && concurrently \"tsc -w\" \"karma start karma.conf.js\"", 
    "test-once""tsc && karma start karma.conf.js --single-run", 
    "tsc""tsc", 
    "tsc:w""tsc -w" 
  }, 
  "keywords": [], 
  "author""", 
  "license""MIT", 
  "dependencies"{ 
    "@angular/common""4.0.2", 
    "@angular/compiler""4.0.2", 
    "@angular/core""4.0.2", 
    "@angular/forms""4.0.2", 
    "@angular/http""4.0.2", 
    "@angular/platform-browser""4.0.2", 
    "@angular/platform-browser-dynamic""4.0.2", 
    "@angular/router""4.0.2", 
 
    "angular-in-memory-web-api""~0.2.4", 
    "systemjs""0.19.40", 
    "core-js""^2.4.1", 
    "rxjs""5.0.1", 
    "zone.js""^0.7.4" 
  }, 
  "devDependencies"{ 
    "concurrently""^3.2.0", 
    "lite-server""^2.2.2", 
    "typescript""~2.0.10", 
 
    "canonical-path""0.0.2", 
    "tslint""^3.15.1", 
    "lodash""^4.16.4", 
    "jasmine-core""~2.4.1", 
    "karma""^1.3.0", 
    "karma-chrome-launcher""^2.0.0", 
    "karma-cli""^1.0.1", 
    "karma-jasmine""^1.0.2", 
    "karma-jasmine-html-reporter""^0.2.2", 
    "protractor""~4.0.14", 
    "rimraf""^2.5.4", 
 
    "@types/node""^6.0.46", 
    "@types/jasmine""2.5.36" 
  }, 
  "repository"{} 
} 
  • Create a sub-folder app on the root folder. On this folder we need to create our typescript files:
    • main.ts
    • app.module.ts
    • app.component.ts
    • app.component.html
    • need to create also components to each route we need. On this example we need to create two components Roo1Component and Root2Component that must be declares on app.module.ts
  • Create your index.html file like showing below:

 

HTML
<!DOCTYPE html> 
<html<head    >document.write(' href="' + document.location + '" />'); 
    <title>Angular4 Routing</title> 
    <base href="/"    <meta charset="UTF-8"    <meta name="viewport" content="width=device-width, initial-scale=1"    <base href="/"    <link rel="stylesheet" href="styles.css" 
    <!-- load bootstrap 3 styles --> 
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" 
 
    <!-- Polyfill(s) for older browsers --> 
     src="node_modules/core-js/client/shim.min.js"> 
     src="node_modules/zone.js/dist/zone.js"> 
     src="node_modules/systemjs/dist/system.src.js"> 
 
     src="systemjs.config.js"> 
            System.import('app/main.js').catch(function (err) { console.error(err); }); 
     
 
</head> 
<body    <my-app>Loading App</my-app> 
</body> 
</html> 
Angular will launch the app in the browser with our component and places it in a specific location on index.html.

 

 

STEP 5 – Run application

Resources

Angular4: https://angular.io/

My personal blog: https://joaoeduardosousa.wordpress.com/ 

ASP.NET – Connect to Azure CosmoDB

This article will show how to configure and use CosmoDB on an ASP.Net MVC web application

The tasks will be stored as JSON documents in Azure Cosmos DB

STEP 1 – Make sure you have installed the prerequisites

Without these requisites, application will not run.

  • Visual Studio 2017
  • CosmoDB configuration on Azure Portal

 

STEP 2 – Create ASP.NET MVC Web Application

Go to Visual StudioFile New Project menu, expand the Web category, and pick ASP.NET Web Application like on the image below

Select the template MVC:

 

STEP 3 – Create CosmoDB on Azure Portal

Go to Azure Portal an select Database -> Azure Cosmo DB

Fill the data requested and select the option Create

After CosmoDB was created, we can access the Keys that will be used on our web app.

For that select your databse, and on the options panel select the option Keys. All the necessary keys, will be created as you can see on the image below.

STEP 4 – Configure CosmoDB on WebApp

Add new Nuget package to your application as you can see on the image below.

Create your MVC:

  • We create a car model with 3 properties
C#
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using Newtonsoft.Json; 
 
namespace WebApp.Models 
{ 
    public class Car 
    { 
        [JsonProperty(PropertyName = "id")] 
        public string Id { getset; } 
 
        [JsonProperty(PropertyName = "model")] 
        public string Model { getset; } 
 
        [JsonProperty(PropertyName = "Year")] 
        public string Year { getset; } 
    } 
}
  • Add a CarController
  • And two views configured like this:
    • List View

  • Create View

 Like the list view, only need to change ViewName and Template associated (on this case), we must use the  Create Template

This is the final structure on our solution:

To run this web app we need to create a generic repository, to connect to Azure CosmoDB. Check the code below.

C#
using Microsoft.Azure.Documents; 
using Microsoft.Azure.Documents.Client; 
using Microsoft.Azure.Documents.Linq; 
using System.Configuration; 
using System.Linq.Expressions; 
using System.Threading.Tasks; 
using System.Net; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
 
namespace WebApp 
{ 
    public static class Repository<T> where T : class 
    { 
        private static readonly string DatabaseId = ConfigurationManager.AppSettings["database"]; 
        private static readonly string CollectionId = ConfigurationManager.AppSettings["collection"]; 
        private static DocumentClient client; 
 
        public static void Initialize() 
        { 
            client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["endpoint"]), ConfigurationManager.AppSettings["authKey"]); 
            CreateDatabaseIfNotExistsAsync().Wait(); 
            CreateCollectionIfNotExistsAsync().Wait(); 
        } 
 
        private static async Task CreateDatabaseIfNotExistsAsync() 
        { 
            try 
            { 
                await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(DatabaseId)); 
            } 
            catch (DocumentClientException e) 
            { 
                if (e.StatusCode == System.Net.HttpStatusCode.NotFound) 
                { 
                    await client.CreateDatabaseAsync(new Database { Id = DatabaseId }); 
                } 
                else 
                { 
                    throw; 
                } 
            } 
        } 
 
        private static async Task CreateCollectionIfNotExistsAsync() 
        { 
            try 
            { 
                await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId)); 
            } 
            catch (DocumentClientException e) 
            { 
                if (e.StatusCode == System.Net.HttpStatusCode.NotFound) 
                { 
                    await client.CreateDocumentCollectionAsync( 
                        UriFactory.CreateDatabaseUri(DatabaseId), 
                        new DocumentCollection { Id = CollectionId }, 
                        new RequestOptions { OfferThroughput = 1000 }); 
                } 
                else 
                { 
                    throw; 
                } 
            } 
        } 
 
        public static async Task<IEnumerable<T>> GetItemsAsync() 
        { 
            IDocumentQuery<T> query = client.CreateDocumentQuery<T>( 
                UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId)) 
                .AsDocumentQuery(); 
 
            List<T> results = new List<T>(); 
            while (query.HasMoreResults) 
            { 
                results.AddRange(await query.ExecuteNextAsync<T>()); 
            } 
 
            return results; 
        } 
 
        public static async Task<Document> CreateItemAsync(T item) 
        { 
            return await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId), item); 
        } 
    } 
}

For more information, please consult the official link from Microsoft: https://docs.microsoft.com/en-us/azure/cosmos-db/documentdb-dotnet-application

 

STEP 5 – Results

You can now, access to your CosmoDB on Azure portal, and check the data created

As you can see, all the data is on JSON format

 

Resources

Official Site: https://docs.microsoft.com/en-us/azure/cosmos-db/documentdb-dotnet-application

My personal blog: https://joaoeduardosousa.wordpress.com/