How to generate and publish Angular 2 build files using NodeJS in Asp.net Application

Introduction

In this article we will discuss on the procedures to generate Angular 5 build files from NodeJS. We will also look at Publishing the same files to Deployment folder.

PreRequisites

  • Make sure NodeJS is installed in your machine
  • Install Angular cli using command “npm i -g @angular/cli@latest

Description

To generate Angular build files in Asp.Net project, we need to create custom build commands and update the .csproj file. I have copied the commands available on .Net core project to generate angular build files.

After adding the below commands, Asp.Net application will generate angular build files in a folder namely “Dist” in root folder of our project.

To add the commands in cs proj file,

  • Right click on project file and select Unload Project option
  • Right click again on project file and select Edit option

CsProj Edit

  • Add a Target Node and paste the commands inside it.

In above codes first section is to check if node is available on your machine and displays an error message if node is not installed.

Next two commands are important as those are the ones which creates angular build files. Notice the “ng build”, this is an Angular CLI command which compiles the application into an output directory. We set two commands one for Release and another one for Debug configuration.

Additionally, like ng build, we can also use production build command “ng build –prod”.

The Include attribute in _CustomFiles node specifies the folder to find the files for deployment is “dist” All files and folders inside dist folder will be deployed during publish process.

Using Publish to deploy the code in Visual Studio

To deploy the files using Publish option we need to make some additional changes. We need to inform the MsBuild to grab the files from dist folder for deployment.  Below commands will perform the same.

Since we are using Asp.Net application project, after build, couple of folders like bin, src will be created. We don’t need these folders for an Angular Project deployment. Hence, we will use below commands to exclude those folders from deployment package.

Next line of code, will cause the “AfterBuild” target to be executed,, when files will be copied for deployment.

Complete Code

References Used

  1. Deploying Extra Files in Asp.Net Web Deployment

 

 

Advertisements

, , , , ,

Leave a comment

Getting started with MongoDB in Asp.Net Core

Introduction

In this article we will discuss on the procedures to build a simple application in Asp.Net Core which communicates with MongoDB database.

Description

This application will do the CRUD operation on a Mongo database and then displays the details in a table.

ThirdPartyTool Used

Robo 3T – is a third party tool which provides a lightweight MongoDB management tool

Implementation

Setting up MongoDB:

If you have not installed the mongodb exe then download and install the same from MongoDB Download Center

After installation of the database, in order to access the mongodb we have to start the MongoDB Process.

To start MongoDB, run mongod.exe in command prompt. Make sure you are running the command prompt from installation folder of Mongodb.  By default installation path is set as C:\Program Files\MongoDB\Server\3.6\bin\

Additionally we need a data directory to store all data in MongoDB. User can set the path for data files using the –dbpath option to mongod.exe

CommandStart

You can begin using the Robo 3T after starting mongodb process.

For this demo I have created a Collections namely Customer with 3 columns

Robo3T.png

Since the database is ready now we will start building the application. Follow along the article to create sample application

Below is a sample demonstration of the application we are going to make

demo.gif

Create a new Project in Visual Studio

CoreProject

And Select the Template for Asp.Net Core MVC Web Application

MVCCore

To interact with MongoDB from c# code, we need to install .NET MongoDB Driver which provides asynchronous interaction with MongoDB.  I utilized the below nugget commands to add driver into my project

Model Class

Lets make an entity class called “Customer” which fits the schema of the Customer table in the database

The class contains Id property of the type ObjectId. This property is used to match an item in MongoDB collections. We as well have another attribute, namely BsonElement which is applied to represent an “element” in the MongoDB collection.

Controller Methods

In Controller we will add code for reading, editing, creating and deleting records from MongoDB.  I have moved the code to retrieve the mongodb database details to a common method.

Views Code

Since this was a more of a MongoDB demo I have used the scaffolding option available with MVC to generate View. You can modify this as per your needs.

Index View

Create View

Delete View

Details View

Edit View

Conclusion

In this article we have looked into procedures to create a simple application in MVC Core using MongoDB as database.

You can download the source code for Asp.NetCoreMVCMongoDBDemo from GitHub.

 

, , , , , ,

Leave a comment

Host WCF Service in Azure App Service

Introduction

In this article we will discuss on the procedures to host a WCF Service on WebApps in Azure  App Service. Azure App Serivce consists of four sub types and they are

  • Web Apps    – Provides hosting service for Web Applications
  • Mobile Apps – Provides a mobile-application development platform that’s highly scalable.
  • Logic Apps   – Provides a visual designer to automate the business process in a series of workflow
  • API Apps      – Provides design and hosting services for Rest API

Description

Usually we use Cloud Services on Azure to host WCF services. While Cloud Services hosting works as expected, the requirement we got was to find an option to host wcf service using one of the features in Azure AppService itself.

We can use WebApps feature to host the WCF in Azure AppService. Follow along this article to find out the procedures.

Step 1: Right Click on WCF Project in Visual Studio and Select the Publish Option

Azure Right Click

Step 2:  Publish dialog box will display. In that Select the Microsoft Azure AppService option. If you are deploying WCF Service for the first time then select “Create New” and click on Publish Button

AzureWCF1

Step 3: Now we will see the App Service configuration dialog window. In the dialog window, we have to create the configuration details for WebApp in Azure

  • App Name – Name of the hosted wcf service application in azure
  • Subscription – Your active subscription for Azure. This field will be auto populated when you login to azure
  • Resource Group – Enables you to work with the resources in your solution as a
  • App Service Plan – Option to select the deployment location and the App Service Plan for deployment

AzureWCF2Step 4: Before publishing to Azure, Make sure the application type is “Web AppAzureWCF3

Step 5: Click on Create button to start deployment to Azure. You can also find the status of deployment in Output Window of Visual StudioAzureWCF4 Deploying

AzureWCF5 OutputStep 6: After successful deployment, the published WCF Service will be displayed on the App Service section on Azure portal.AzureWCF6AzureWindowStep 7: Click on Published WCF Service to find more details and URL of service.AzureWCF6Azure Publish

Accessing the WCF Service

Create a console app as client application for WCF Service. Right click on console app and use the Add -> Service Reference option to access wcf service on client applicationServiceReference

ServiceReferenceAdded

Once we add the WCF Service reference, we can call the WCF method like below

CallingWCF

 

, , , , ,

1 Comment

Simple CRUD Application in Asp.Net Core Razor Pages

Introduction:

This article presents how to produce a simple application using Razor Pages in Asp.Net Core. This application will do the CRUD operation on a SQL Server database and then displays the details in a table.

You require to have Visual Studio 2017 Version 15.3 and .NET Core 2.0 installed in order to work with Razor Page Applications. You can get more details from here

Implementation

Create a new Project in Visual Studio

CoreProject

And Select the Web Application Template for Razor Pages

RazorPages

Project Structure

If you take a look at the project structure you will notice the main difference in Razor Pages is that there is No Controller and Views folder. All files in Razor Pages are inside the “pages” folder. You can also create subfolders within the pages folder to keep the files organized.

Another important point to note is the @page directive on the RazorPages. @page directive will cause the file to handle the requests directly, without utilizing a controller.

Sample Application:

Now let’s start building a simpler application which performs CRUD operations on Employee database using Razor Pages. Below is a sample demonstration of the application we are going to make.

demo

Model and Database

To load the information from database, we are using EntityFrameworkCore and its associated methods.  Make sure you install the EF Core nugget packages from here

In this example I have used the DatabaseFirstApporach.  DatabaseFirstApporach lets the EnityData Model to generate classes, dbcontext etc from the database automatically. All other functionalities like database and model sync exists as is.

Let’s create an entity class called “Employee” which matches the schema of the Employee Table in the database

Next we will add a DbContext class , which will act as a session between entity class and database.

Next we will provide the connection string for database in appsettings.json file

Finally we will register dbContext using dependency injection. Modify the startup.cs file and add the below code

Adding Views for Create, Edit, Update, Delete (CRUD)

Create View (CreatePage.cshtml)

On Create page we used 3 directives.

@page: Razor Pages mandates that “@page” directive should be the first directive on page.

@inject: Another directive you can find on page is @inject. @inject directive is used for dependency injection in to views. Using @inject we inject the dbContext to View, which will be used to for all db related operations.

@functions: In Razor page, we can add the function-level content code(C#) to view. We can also have the content in code behind CreatePage.cshtml.cs page.

Edit View

Next we will see the EditPage.  Most of the coding are similar to create page which we already seen earlier. However in this page, we need to pass the selected row id as route parameter

We used asp-route-{value} attribute from anchor tag helper to generate the Edit Link. At runtime the {value} field (in our example ‘id’) will be mapped to the route parameter value which will be used by Edit Page to retrieve the selected row value.

<a asp-page="/EditPage" asp-route-id="@item.EmployeeID">Edit</a>

EditPage.cshtml.cs

All other pages have the similar code structure. The difference is only the operation performed on each pages. All codes have comments added which are select explanatory

Index View(Home Page)

Delete View

DeletePage.cshtml.cs

You can find complete code of this demo from here

, , , ,

1 Comment

[Solution]Dropdownlist not retaining selected item on Postback

Introduction

In this article we will look into an alternative solution to the problem with dropdownlist where selecteditems are not retained on postback.

Problem Description

When we select an item in dropdownlist and do a postback(button click) then the value selected on dropdownlist will reset to the first item in dropdownlist.

demo

Usually this issue happens when we reload the items in dropdownlist on every postback. To resolve the issue we will load the dropdownlist inside the If(!IsPostBack) block.

   protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DropDownList2.Items.Insert(0, new ListItem("One", ""));
                DropDownList2.Items.Insert(1, new ListItem("Two", ""));
                DropDownList2.Items.Insert(2, new ListItem("Three", ""));
                DropDownList2.Items.Insert(3, new ListItem("Four", ""));
                DropDownList2.Items.Insert(4, new ListItem("Five", ""));
                DropDownList2.Items.Insert(5, new ListItem("Six", ""));
                DropDownList2.Items.Insert(6, new ListItem("Seven", ""));
                DropDownList2.Items.Insert(7, new ListItem("Eight", ""));
                DropDownList2.Items.Insert(8, new ListItem("Nine", ""));
                DropDownList2.Items.Insert(9, new ListItem("Ten", ""));
                DropDownList2.SelectedIndex = 4;
            }
        }

However if you see the code preceding, you will notice that the dropdownlist is populated inside if(!IsPostBack) block. Now what is causing the issue?

Solution:

On further analysis I noticed that while populating the dropdownlist, user is passing an empty string to “value” property of dropdownlist.  Dropdownlist will render on page at runtime without value being populated. This invalid code for dropdownlist caused the issue.

<select name="DropDownList2" id="DropDownList2">
<option value="">One</option>
<option value="">Two</option>
<option value="">Three</option>
<option value="">Four</option>
<option selected="selected" value=""> Five</option>
<option value="">Six</option>
<option value="">Seven</option>
<option value="">Eight</option>
<option value="">Nine</option>
<option value="">Ten</option>
</select>

To resolve the issue we need to provide an entry to “value” property in dropdownlist.

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DropDownList2.Items.Insert(0, new ListItem("One", "1"));
                DropDownList2.Items.Insert(1, new ListItem("Two", "2"));
                DropDownList2.Items.Insert(2, new ListItem("Three", "3"));
                DropDownList2.Items.Insert(3, new ListItem("Four", "4"));
                DropDownList2.Items.Insert(4, new ListItem("Five", "5"));
                DropDownList2.Items.Insert(5, new ListItem("Six", "6"));
                DropDownList2.Items.Insert(6, new ListItem("Seven", "7"));
                DropDownList2.Items.Insert(7, new ListItem("Eight", "8"));
                DropDownList2.Items.Insert(8, new ListItem("Nine", "9"));
                DropDownList2.Items.Insert(9, new ListItem("Ten", "10"));
                DropDownList2.SelectedIndex = 4;
            }
        }

Demo

demo1

 

, , , ,

Leave a comment

Bundling and Minification in AspNetCore

Introduction:

In this article we will look into an easy option to do bundling and minification in Asp.Net Core. For those who are new to Bundling and Minification let’s try to understand these concepts.

Bundling

Bundling is the process of combining multiple javascript files to a single file. By this way we will reduce the number of requests needed for loading the files. i.e. if we had javascript code in multiple files then system will generate multiple requests to load all files however since we bundled all files there will be only one requests to load file. This will improve the load time.

Minification

Minification is the process of reducing the size of files (css , javascript). Usually size reduction happens by removing unwanted spaces in file.

For ex, below Javascript code

will change like below after minification.

Bundling and Minification using Gulp

We have variety of options available for Third party tools like Gulp and Grunt can be used to do bundling and minification process. However the problem with this approach is it involves additional steps which are slightly complex.

Using Bundler and Minification Extension

Mads Kristensen has created an extension namely “Bundler and Minifier”, using this we can easily do both bundling and minification in Asp.netCore. You can download the installer for extension from here.

Once you installed the extension, to do bundling and minification all you do is to Right click on the file and then select Bundler & Minifier option.

2017-08-22 14_38_43-Clipboard

If you have a single javascript file then you will see the only Minify File option.

MinfyOption

Once you select the option extension will generate the minified file for us. We can also follow the same process to minify css files as well.

, , , ,

Leave a comment

Implementing Multiselect feature on AutoCompleteExtender

AjaxControlToolkit’s AutoComplete extender is designed to be a single selection control. i.e. When user selects a value the dropdown list will be closed and selected text will be assigned to targeted textbox control.

Recently I got a question on the Asp.net Forums where the user wants to make the AutoCompleteExtender a multi select one. Besides the chosen values should be appended to textbox as comma separated values. This question caught my attention as it was a little tricky.

Here are the details of requirements

  • Keep the dropdown list of options on AutoComplete Extender opened
  • Allow multiple selection on AutoComplete Extender
  • Add the string to target textbox control as comma separated strings

We need to come up with a custom implementation to accomplish this requirement.  When I looked at some threads I found the code to keep the list opened. However, I need to customize it to generate comma separated values.

You can find complete implementation details here

Add a behaviorID to AutocompleteExtender control. We will use this id to close the dropdown list after user selecting values

Now we need to add a button to close the dropdown list after selecting values

Add the following javascript function to your page to close the window

Now we need to customize the inbuilt function “_setText” and “_hideCompletionList” function in order to accomplish our requirement

Complete Code

HTML

C#:

Code to populate the list when user type in characters on textbox

Demo

AutoCompleteExtenderDemo

, , , , ,

Leave a comment