ASP.NET – Connect to MySQL Azure Database

Introduction

Using MVC, Entity Framework, ASP.NET Scaffolding, and Azure MySQL you can create a web application that stores your information on an MongoDB Azure database. This demo shows you how to create a web application with MVC and Entity Framework 7, that communicate with a MySQL Azure database.

 

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 MySQL Database on Windows Azure

After get access to an Azure Account, we need to create a MySQL Database to store your data.

So for that we need to select the option New on the left bottom of our web page and then select the option Data + Storage -> MySQL Database-> Set the name and provide the configurations you need.

After created the Database, we need to get the connection string that will be used on Web Aplication to access the Azure Database.

For that, select the database created and on the main window, on the right side, we have an option called “Show Connection String”.

When we select that option, a new tabwill appear, like the following image, with the connection string formatted to different providers.

STEP 3 – Create ASP.NET Web Application

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

 

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

After selection of our template, your first web application using ASP.NET is created.

 

STEP 4 – Create Data Model

After we have our web application created, we need to ceate our data model.

For that, select the option Add New Item on solution and choose the option Class. Create the class like the one on the image above.

We need to validate that EntityFramework anf MySQL.Data.Entity are installed like we saw on the image below

STEP 5 – Scaffolding

This could be made easily using the Scaffolding functionality.

On the solution on the top of controller folder, select the option Add New Scaffold Item.

On the new screen, select the option MVC6 Controller with views using entity framework.

 

Select the name of the controller, class model and data context class.

The new controllers and views associated, was created with sucess.

STEP 6 – Change Connection String

STEP 7 – Change Menu Layout

To test the new entity created, we can add one new entries on the web application menu.

 

STEP 8 – Run Application

Press now the F5 button, to run the web application.

The new entities appear on the menu.

Press the option car to see our entity in action

Advertisements

ASP.NET Core 2.0 -Dependency Injection

In this article, I’ll show you the new feature introduced in ASP .NET Core that allows you to inject dependencies directly into a View using the dependency injection container.

ASP .NET Core has introduced a feature called view injection that allows you to inject dependencies into a view using the inject keyword.

Previously, to retrieve data from a View, we needed to pass it from the Controller using the Controller properties, such as ViewBag, ViewData, or Model properties.

In ASP.NET Core MVC, this task became very simple using the Inject directive that allows you to inject the dependencies directly into the View and retrieve the data.

Let’s see this working in practice!

STEP1 – Creating the ASP .NET Core Project in VS 2017

Open VS 2017 and on the File menu click New Project. Then select the Visual C # -> Web template and check ASP .NET Core Web Application (.NET Core).

Then enter the name AspNetCoreDemo and click OK.

In the next window, choose the ASP .NET Core 2.0 version and mark the Web Application (Model-View-Controller) template without authentication and click the OK button:

 

STEP2 – Creating a new service in the application

Let’s define a very simple service just for testing in our application.

Create the Services folder in the project (Project -> New Folder), and then add the CountriesService.cs file to this folder containing the following code:

 

 

STEP 3 – Injecting the service into View

 

C#
using System.Collections.Generic; 
namespace AspNetCoreDemo.Services 
{ 
    public class CountriesService 
    { 
        public List<string> GetCountries() 
        { 
            return new List<string>() { "Portugal""Spain""France" }; 
        } 
    } 
} 
 We will now have how we can inject the service created in the project view using the @inject directive.

Think of the @Inject directive as a property being added in your View and populating the property using dependency injection.

The basic syntax used is: @inject <service> <name>

At where :
1. @ inject – is the directive used to inject dependencies;
2. <service> – is the class of service.
3. <name> – is the service injection name through which we can access the service’s methods.

Let’s open the Index.cshtml file from the /Views/Home folder and include the code below in this file

 

HTML
@inject AspNetCoreDemo.Services.CountriesService Countries 
@foreach (var countryName in Countries.GetCountries()) 
        { 
            <ul                <li>@countryName</li> 
            </ul> 
        }
STEP4 – Registering the service in the Startup.cs file

 
Open the Startup.cs file and add the code below to this file that registers the service created for dependency injection in the ConfigureServices method.

C#
public void ConfigureServices(IServiceCollection services) 
        { 
            services.AddMvc(); 
            services.AddTransient<CountriesService>(); 
        }
STEP5 – Result

Executing the project, we will obtain the following result:

ASP.NET Core 2.0 – Apply bootstrap template

Introduction

This article walks you through the steps for creating an ASP.NET Core 2.0 Web Application using Bootstrap as the template for layout.

 

STEP1 – Creating the ASP .NET Core Project in VS 2017

Open VS 2017 and on the File menu click New Project. Then select the Visual C # -> Web template and check ASP .NET Core Web Application (.NET Core).

Then enter the name AspNetCoreDemo and click OK.

In the next window, choose the ASP .NET Core 2.0 version and mark the Web Application (Model-View-Controller) template without authentication and click the OK button:

STEP2 – Upgrade version if necessary

You can verify the version of bootstrap in two ways.

First one, accessing the files on wwwroot\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.7

 

 

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

Just select the bower.json file on the project and check the version.

 

STEP3 – Change Layout

The default bootstrap template used in Visual Studio 2017 is Jumbotron. Jumpotron’s original source code is available here Jump  in the 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/ Jump .

 

To make that change we need to:

  • Add the stylesheet creative.css to the CSS folder
  • Add the stylesheet creative.js to the JS folder
  • Add the image folder from template downloaded
  • Add the css folder from template downloaded
  • Add the vendor folder from template downloaded

 

  • Now, open the layout file _Layout.cshtml in the Shared folder under Views Folder

 

Copy the content from index.html to layout.cshtml according to your layout

 

This is the sample created with the solution:

This is the sample after our changes:

 

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/

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 using Visual Studio 2017

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/

ASP.NET Core – How to configure Angular2 with TypeScript

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

Download code here: https://code.msdn.microsoft.com/ASPNET-Core-How-to-feb8d5ff/view/Reviews

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/

ASP.NET Core 1.0 – Enable Minification

To enable minification, ensure the following:
1. Config.asax, register the BundlesConfig
protected void Application_Start()

{
         BundlesConfig.RegisterBundles(BundleTable.Bundles);
}

2. BundleConfig.cs, include the scripts and enable optimizations
public static void RegisterBundles(BundleCollection bundles)

{
  bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
    "~/Scripts/jquery-{version}.js"));
BundleTable.EnableOptimizations = true;
}

3. main.html, register the scripts

@section scripts {
       @Scripts.Render("~/bundles/jquery")
}

4. In addition the minification process changes $scope and $q into random variables. Since this does nto tell angular what to inject, the solution is to declare your dependencies wrapped in []:
angular.module("MyApp")

       .controller("MyCtrl", ["$scope", "$q", function($scope, $q) {
  // your code
}])

 

This is just the steps you need to enable minification.