Advertisements

Create An Intelligent Bot Application Using Microsoft Bot Framework


Introduction

In our previous article, we learned how to Create and Connect a chat bot with Azure Bot Service . In this article, we are going to create an intelligent bot application using Microsoft Bot Framework.

ngrok Software

So first we need to download ngrok software. What is ngrok ?

“ngrok” is a network tunneling software. The Bot Framework Emulator works with ngrok to communicate with bots hosted remotely. Click this link https://ngrok.com/download to download ngrok network tunneling software.

Bot Framework Emulator

The Bot Framework Emulator is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel. So we need to download Bot Framework Emulator for both local and server testing. So please go through this link to download Bot Framework Emulator click here.

After successful download please run the exe file for Bot Framework Emulator. Then first time it will open a “App Settings Window” there we need to provide the exact path of ngrok in our system ( Provide “ngrok” saved folder path in our system ).

The following screenshot “ngrok” saved into C drive Downloads folder ( C:\Users\RajeeshMenoth\Downloads\ngrok ).

Web.config

When you are connecting to remote server or anything other than local host then we need to provide the following credentials “BotId” & “MicrosoftAppId” & “MicrosoftAppPassword” in Web.Config and Bot Framework Emulator. This we will get it from azure “AppSettings” in our created Web App Bot.

<configuration>
<appSettings>
<!-- update these with your BotId, Microsoft App Id and your Microsoft App Password-->
<add key="BotId" value="YourBotId" />
<add key="MicrosoftAppId" value="" />
<add key="MicrosoftAppPassword" value="" />
</appSettings>
</configuration>

Microsoft Bot Framework In Visual Studio

Click on “File -> New -> Project -> Visual C# -> Bot Application”

Note : If the Bot Application Template is not present in the Visual Studio 2015 then please go to “Tools -> Extensions and Updates”. Then search and Install the “Bot Application” in our Visual Studio.

Code

I just changed the default code for Web App Bot. Then we added our own logic into this C# Code in Bot Application.

using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Bot.Connector;

namespace Bot_App
{
[BotAuthentication]
public class MessagesController : ApiController
{
///

<summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>

public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
if (activity.Type == ActivityTypes.Message)
{
ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
// calculate something for us to return
int length = (activity.Text ?? string.Empty).Length;
Activity reply = activity.CreateReply("");

// return our reply to the user
switch (activity.Text)
{
case "hi":
case "hello":
reply = activity.CreateReply($"{activity.Text} buddy, How may I assist you ?");
break;
case "how are you":
reply = activity.CreateReply($"Fine , What about you ?");
break;
case "Where are you ?":
reply = activity.CreateReply($"Bangalore , What about you ?");
break;
case "bye":
reply = activity.CreateReply($"Bye , Thank you !!");
break;
default:
reply = activity.CreateReply($"This is chat bot using Bot Framework !!");
break;
}

await connector.Conversations.ReplyToActivityAsync(reply);
}
else
{
HandleSystemMessage(activity);
}
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}

private Activity HandleSystemMessage(Activity message)
{
if (message.Type == ActivityTypes.DeleteUserData)
{
// Implement user deletion here
// If we handle user deletion, return a real message
}
else if (message.Type == ActivityTypes.ConversationUpdate)
{
// Handle conversation state changes, like members being added and removed
// Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
// Not available in all channels
IConversationUpdateActivity update = message;
var client = new ConnectorClient(new Uri(message.ServiceUrl), new MicrosoftAppCredentials());
if (update.MembersAdded != null && update.MembersAdded.Any())
{
foreach (var newMember in update.MembersAdded)
{
if (newMember.Id != message.Recipient.Id)
{
var reply = message.CreateReply();
reply.Text = $"Welcome {newMember.Name}!";
client.Conversations.ReplyToActivityAsync(reply);
}
}
}
}
else if (message.Type == ActivityTypes.ContactRelationUpdate)
{
// Handle add/remove from contact lists
// Activity.From + Activity.Action represent what happened
}
else if (message.Type == ActivityTypes.Typing)
{
// Handle knowing tha the user is typing
}
else if (message.Type == ActivityTypes.Ping)
{
}

return null;
}
}

}

Localhost

Run our Bot Application in local then it will open our application with a localhost port number. So we can use this in our “Bot Framework Emulator”.

The bot endpoint like this : http://your_bots_hostname/api/messages&#8221;

Bot Endpoint

In the Bot Framework Emulator we can add our localhost or remote server “bot end point”. We can directly connect localhost port number in Bot Framework Emulator. But note that in the actual server endpoint we need to given “Microsoft App ID” and “Microsoft App Password”.

Actual endpoint of our chat bot is getting from Apps Setting ( for this we need to create a Web Chat Bot in Azure Using Bot Service ).

Application Settings

We will get all the credentials of our Web Chat Bot App ( Azure ) in Apps Setting ( for this we need to create a Web Chat Bot in Azure Using Bot Service ).

Output

Click on the “Connect” then it will trigger our Bot Application.

Summary

We learned how to Create An Intelligent Bot Application Using Microsoft Bot Framework. I hope this article is useful for all Azure chat bot beginners.

Reference

Download

See Also

You can download other ASP.NET Core source codes from MSDN Code, using the link, mentioned below.

Advertisements

Create and Connect a chat bot with Azure Bot Service


Introduction

This article explains how to Create and Connect a chat bot with Azure Bot Service.

Azure Account

First, we need to create an account on the Azure portal. Only then can we host the application in the cloud environment. So, please check the following steps to create an Azure account.

Azure Account Registration

Create an account through this link to  click here.

Web App Bot

  1. Click on “New” on the left side menu and it will open an Azure Marketplace , there we can see list of services so click on “AI + Cognitive Services” then click on the “Web App Bot” for our bot service app.

BOT Service Registration

  1. Bot name  : The display name of our bot service and that appears in channels and directories. We can change this name at any time.
  2. Subscription : We can select our Azure subscription for chat bot service.
  3. Resource group : We can create a new resource group or choose from an existing one ( We selected our existing resource group as “AzureDemo” ).
  4. Location : We can select our location of resource group. The best thing is we can choose a location closest to our customer. The location cannot be changed once the bot is created.
  5. Pricing tier : Select a pricing tier of bot service.
  6. App name : The unique URL name of our bot service , We given “menothbot” as our App name and the URL is look like this : http://menothbot.azurewebsites.net/
  7. Bot template : There are two templates available in bot C# and Node.js. We can choose any of the template and that will create a echo bot.
  8. App service plan/Location : We can choose a best service plan that closest to our customer.
  9. Azure Storage : We can create a new data storage account or use an existing one. By default, the bot will use Table Storage.
  10. Application Insights : This will provide service-level and instrumentation data like traffic, latency, and integrations. We can switch on or off this option.

11.Click on the “Create” button and wait for the build success.

12. Once the build is succeeded, then click on the “Dashboard” and we can see “menothbot” bot is created in the All resources list . Bot is ready for use !!.

Online Code Editor

  1. Click on the “menothbot” bot in dashboard window , Then After we can see a list option available for our bot service. So click on the “Build” option in left side menu and it will open multiple option in right side. Just click on “Open online code editor” link.

2. Online code editor will open a source code window of our bot service app. So we can edit and add code in this section and currently it will display the default “echo bot” code of our bot service. Click on “WWWROOT -> Dialogs -> EchoDialog.cs”.

3. If you made any changes in the online code editor then click on the “build console” option on the left side menu and run it “build.cmd” command for the execution and deployment of the code.

Test in Web Chat

We can quickly test our bot through “Test in Web Chat” option. , So just click on the “Test in Web Chat” in the left side menu and it will open a chat bot on right side window. Here it will display few messages that we already added in the “EchoDialog.cs” in online code editor.

Code :

using System;
using System.Threading.Tasks;
using Microsoft.Bot.Connector;
using Microsoft.Bot.Builder.Dialogs;
using System.Net.Http;

namespace Microsoft.Bot.Sample.SimpleEchoBot
{
[Serializable]
public class EchoDialog : IDialog<object>
{
protected int count = 1;

public async Task StartAsync(IDialogContext context)
{
context.Wait(MessageReceivedAsync);
}

public async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument)
{
var message = await argument;

if (message.Text == "reset")
{
PromptDialog.Confirm(
context,
AfterResetAsync,
"Are you sure you want to reset the count?",
"Didn't get that!",
promptStyle: PromptStyle.Auto);
}
else if (message.Text == "hi")
{
await context.PostAsync($"{this.count++}: Hi , How may I assist you ?");
context.Wait(MessageReceivedAsync);
}
else if (message.Text == "how are you ?")
{
await context.PostAsync($"{this.count++}: fine , What about u ?");
context.Wait(MessageReceivedAsync);
}
else if (message.Text == "hello")
{
await context.PostAsync($"{this.count++}: Hello , Tell Me !!");
context.Wait(MessageReceivedAsync);
}
else
{
await context.PostAsync($"{this.count++}: You said {message.Text} , This is Azure Bot Service !! Thank You All !!
by
RajeeshMenoth !! ");
context.Wait(MessageReceivedAsync);
}
}

public async Task AfterResetAsync(IDialogContext context, IAwaitable<bool> argument)
{
var confirm = await argument;
if (confirm)
{
this.count = 1;
await context.PostAsync("Reset count.");
}
else
{
await context.PostAsync("Did not reset count.");
}
context.Wait(MessageReceivedAsync);
}

}
}

 Connect a bot to Web Chat

This is very simple way to connect our bot service app to Web Chat in Azure. Please check the following steps !!.

  1. Click on the “Channels” menu in the left side option. Then it will open a window with channels details there you can see edit option in “Web Chat” channel.

2. Click on the edit option in “Web Chat” channel and It will display two “Secret Keys” with Iframe code. So choose the first “Secret Key” and add it on iframe code.

iframe code

Copy paste your iframe code in your html code and add the secret key available in the web chat edit option . Then it will display the Web chat bot in your app.

<iframe src='https://webchat.botframework.com/embed/menothbot?s=YOUR_SECRET_HERE'></iframe>

Output

Reference

See Also

You can download other ASP.NET Core source codes from MSDN Code, using the link, mentioned below.

Summary

We learned how to Create and Connect a chat bot with Azure Bot Service. I hope this article is useful for all Azure chat bot beginners.

 

C-SharpCorner MVP Award 2017


Most Valuable Gift in this Year !! Hatrick, 3rd time in a row !!.

Thank you C# Corner for giving me such a wonderful gift, MVP Award 2017!!

Truly this year began with a bang !!

RajeeshMenothMVP

RajeeshMenothMVP

C# Corner MVP

C# Corner MVP

Create & Deploy an ASP.NET Core web app in Azure


Introduction

Nowadays, most people are choosing web hosting on a cloud platform. Microsoft lovers like us basically select “Microsoft Azure” as our hosting environment.That’s the reason I have written this new article defining a simple way of hosting in Azure.

Before reading this article, you must read the articles given below for ASP.NET Core knowledge.

Azure Account 

First, we need to create an account on the Azure portal. Only then can we host the application in the cloud environment. So, please check the following steps to create an Azure account.

Azure Account Registration

Create an account through this link to Azure Portal.

Domain Registration

We need to host our application in a particular domain. Check the following steps –

  1. Click on “All resources” on the left side menu and it will open a dashboard with an empty or already existing list of resources that we have created earlier.
  2. Click on the “Add” button and it will open another window with multiple options. We can choose an appropriate option to host our application.
  3. As per our requirement, we choose “Web + Mobile” and clicked on the “Web App” on the right side.
App Name Creation

App Name Creation

4. It will open another form to fill up our app details to host. We need to give a unique name in the “Appname” section and It will create a subdomain for our ASP.NET Core application.

5. We choose subscription as “Free Trial” because we created a free account on the Azure portal.

6. We need to host our app resources in Resource group, So first we need to create a resource group name in our Azure account. But we choose existing resource group name “AzureDemo” that we are already created in our Azure account.

7.”OS ( Operating System )” we selected as “Windows”( As per our requirement ).

8. We can create our own App Service Plan name.

9. Application Insight will give you the more clarity about your hosted app. Eg. analytics, etc.

10. Click on the “Create” button and wait for the build success.

Resource Group Name

Resource Group Name

11. Another way to create the Resource Group Name – click on “Resource groups -> Add”.

Resource Group

Resource Group

12. Once the build is succeeded, then we can see this output.

Build Succeeded

Simple steps to create an Asp.Net Core Application

  1. Open our  VisualStudio then click on File > New > Project.
  2. Select Visual C# > Web > ASP.NET Core Web Application.
  3. We have given our application name as “MyFirstAzureWebApp”.
  4. Then, click OK.
  5. Click on the “Ctrl+F5”

App Publishing into Azure
We created a default ASP.NET Core application ( We have done some changes in UI Section) for the publishing process.

  1. Right click on the application and click on the Publish menu.
App Publishing

App Publishing

2. Click on the “Microsoft Azure App Service”

3. We choose our existing resource group name ( That we created ! “AzureDemo” ) in our Azure Portal and It will display the App Name inside the “AzureDemo” folder. This will display only when we are login through the Visual Studio using Azure credentials ( Email & Password).

Resource Name

Resource Name

OutPut

The application is hosted in given domain address  http://menoth.azurewebsites.net/

Reference

See Also

You can download other ASP.NET Core source codes from MSDN Code, using the link, mentioned below.

Summary

We learned how to create and deploy an ASP.NET Core web app in Azure. I hope this article is useful for all ASP.NET Core & Azure beginners.

 

Sending SMS using ASP.NET Core With Twilio SMS API


Introduction

In this article, we will explain how to Send SMS using ASP.NET Core With Twilio SMS API. Twilio provides third party SMS API for sending sms over the global network. So we can learn a little bit through this article.

Before reading this article, you must read the articles given below for ASP.NET Core knowledge.

Package Installation

  1. Install-Package Twilio -Version 5.9.1

This package will install all the sms,video,etc related classes,methods and API’s for twilio.

  1. Install-Package jQuery.Validation.Unobtrusive -Version 2.0.20710

This package will install all the bootstrap & validation related Jquery libraries in our project.

Important Notes

1. If you don’t have any twilio account then you should register a free account using the following link Click here & I choose language as “C#”.

2. Once registration is completed then we can access Dashboard and Console of our twilio account. We will get “Account SID & Auth Token Id” from Dashboard for sending sms.

Dashborad Console

Dashborad Console

3. We need a Twilio From number because that number has sent sms to the global network! So we need to enable Twilio SMS number ( This will send sms from ur “To” numbers ). Go to this link click here and Click on the “Get a number” button in the “Programmble SMS Menu” mentioned in the following screenshot.

Get a Number

Get a Number

4. You have to get $15 for sending sms In the twilio trial account. I can see in my account they are charging $1 + for each sms and after that you need to buy a paid plan.

Name Spaces

The following namespaces are providing “ASP.Net Core MVC” & “Twilio SMS API” Classes & Methods.

using System;
using Microsoft.AspNetCore.Mvc;
using RegistrationForm.ViewModels;
using Twilio;
using Twilio.Types;
using Twilio.Rest.Api.V2010.Account;

Configuring ASP.NET MVC in ASP.NET Core

We are going to add “UseMvc” Middleware and “AddMvc()” Configure Services in Startup.cs Class. The code given below clearly mentions that manually we need to add our controller name and an action name in “MapRoute”. We can change this controller name and action name, which is based on our requirement in the Applications.

 app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

Startup.cs

The class given below contains the complete middleware details in our Applications. I choose a default project in our Visual Studio 2015. So automatically it will generate the following classes & methods.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace SMSApp
{
    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?}");
            });
        }
    }
}

Code
The following code help to send sms over the global network using ASP.Net Core With Twilio SMS API.

[HttpPost]
        public IActionResult Registration(RegistrationViewModel model)
        {
            ViewData["Message"] = "Your registration page!.";

            ViewBag.SuccessMessage = null;

            if (model.Email.Contains("menoth.com"))
            {
                ModelState.AddModelError("Email", "We don't support menoth Address !!");
            }

            if (ModelState.IsValid)
            {
                try
                {
                    // Find your Account Sid and Auth Token at twilio.com/user/account
                    const string accountSid = "AXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
                    const string authToken = "6XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
                    TwilioClient.Init(accountSid, authToken);

                    var to = new PhoneNumber("+91" + model.Mobile);
                    var message = MessageResource.Create(
                        to,
                        from: new PhoneNumber("+18XXXXXXXXXX"), //  From number, must be an SMS-enabled Twilio number ( This will send sms from ur "To" numbers ).
                        body:  $"Hello {model.Name} !! Welcome to Asp.Net Core With Twilio SMS API !!");

                    ModelState.Clear();
                    ViewBag.SuccessMessage = "Registered Successfully !!";
                }
                catch (Exception ex)
                {
                    Console.WriteLine($" Registration Failure : {ex.Message} ");
                }

            }

            return View();
        }

New Tag Helpers

We used latest ASP.NET Core Tag Helpers in Registration page to access controller and actions, validation etc.





<div asp-validation-summary="All" class="text-danger"></div>



<label asp-for="Name"></label>  
<input asp-for="Name" class="form-control" />  
<span asp-validation-for="Name" class="text-danger"></span>  
<a asp-controller="Home" asp-action="Home" class="btn btn-info">Cancel</a>

Inject Tag Helpers

In the way given below, we can inject the Tag Helpers in our Application. Now, create the default “_ViewImports.cshtml” file in View Folder and add the code given below in that file.

@addTagHelper "*,Microsoft.AspNetCore.Mvc.TagHelpers"

Client Side validations

The Client Side validation is done with the help of Bootstrap & jQuery etc.

Validation

Validation

Registration Page

The message will send to the respective mobile number that you have given in the mobile number column in registration page.

OutPut

We will get a sms from the Twilio account, once we have registered successfully.

Reference

Download

See Also

You can download other ASP.NET Core source codes from MSDN Code, using the link, mentioned below.

Summary

We learned how to Send SMS using ASP.NET Core With Twilio SMS API. I hope this article is useful for all ASP.NET Core beginners.

Startup Page In ASP.NET Core


Introduction

I think we all are familiar with the configuration of the default startup page in the previous versions of AP.NET but it’s slightly different in ASP.NET Core applications. In this article, I will explain how to configure the default startup page In ASP.NET Core.

Default Startup Page Configuration

There are two ways to implement the default startup page in ASP.NET Core.

  • Default Configuration
  • Customized Configuration

Before reading this article, you must read the articles given below for ASP.NET Core knowledge.

Default Configuration

We can use UseDefaultFiles() extension method in ASP.NET Core 1.0. UseDefaultFiles() will only search for the files given in “wwwroot”. If any of the files are detected first in “wwwroot”, the files are run as default in the client browser.

  • default.html
  • default.htm
  • index.html
  • index.htm

UseDefaultFiles must be called before UseStaticFiles or any other method (app.Run, app.Use) to serve the default file in the client-side browser. As you state UseStaticFiles() method after UseDefaultFiles(), it will run UseStaticFiles() method as a default and automatically terminates the other files which come after UseStaticFiles() method.

Customized Configuration

In this case, we are calling other customized pages as default startup pages in ASP.NET Core 1.0. Thus, we can use DefaultFilesOptions in ASP.NET Core 1.0. If you want to run other files as default, check the code given below in Startup.cs.

Full Code

The following code containsthe full source code of startup page configuration in ASP.NET Core.

using Microsoft.AspNetCore.Builder;  
using Microsoft.AspNetCore.Hosting;  
using Microsoft.AspNetCore.Http;  
using Microsoft.Extensions.DependencyInjection;  
using Microsoft.Extensions.Logging;  
   
namespace StartupConfig  
{  
    public class Startup  
    {  
        // This method gets called by the runtime. Use this method to add services to the container.  
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 Jump  
        public void ConfigureServices(IServiceCollection services)  
        {  
        }  
   
        // 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();  
               
            DefaultFilesOptions DefaultFile = new DefaultFilesOptions();  
            DefaultFile.DefaultFileNames.Clear();  
            DefaultFile.DefaultFileNames.Add("Welcome.html");  
            app.UseDefaultFiles(DefaultFile);  
            app.UseStaticFiles();  
   
            if (env.IsDevelopment())  
            {  
                app.UseDeveloperExceptionPage();  
            }  
   
            app.Run(async (context) =>  
            {  
                await context.Response.WriteAsync("Hello World!");  
            });  
        }  
    }  
}  

project.json

The versions will be change based on the latest version’s updation in ASP.NET Core.

{  
  "dependencies": {  
    "Microsoft.NETCore.App": {  
      "version": "1.0.1",  
      "type": "platform"  
    },  
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",  
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",  
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",  
    "Microsoft.Extensions.Logging.Console": "1.0.0",  
    "Microsoft.AspNetCore.StaticFiles": "1.1.1"  
  },  
   
  "tools": {  
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"  
  },  
   
  "frameworks": {  
    "netcoreapp1.0": {  
      "imports": [  
        "dotnet5.6",  
        "portable-net45+win8"  
      ]  
    }  
  },  
   
  "buildOptions": {  
    "emitEntryPoint": true,  
    "preserveCompilationContext": true  
  },  
   
  "runtimeOptions": {  
    "configProperties": {  
      "System.GC.Server": true  
    }  
  },  
   
  "publishOptions": {  
    "include": [  
      "wwwroot",  
      "web.config"  
    ]  
  },  
   
  "scripts": {  
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]  
  }  
}  

Configuration Code

DefaultFilesOptions DefaultFile = new DefaultFilesOptions();
DefaultFile.DefaultFileNames.Clear();
DefaultFile.DefaultFileNames.Add("Welcome.html");
app.UseDefaultFiles(DefaultFile);
app.UseStaticFiles();

Reference

Output

Startup_Page

Startup_Page

See Also

You can download other ASP.NET Core source codes from MSDN Code, using the link, mentioned below.

Summary

We learned how to configure the default startup page in ASP.NET Core 1.0. I hope this article is useful for all ASP.NET Core 1.0 beginners.

Session State In ASP.NET Core and MVC Core


Introduction

In this article, we will explain how to create a “Session State in ASP.NET Core and MVC Core”.

Session State

In Session State, we can use to save and store user data while the user browses your web app. We already know that in previous versions of ASP.NET, we could store session as key value pair like this “Session[“Name”] = “Rajeesh Menoth”” and implement it in an easy way. But in the latest version of ASP.NET or ASP.NET Core, we need to do a few configurations for accessing and enabling Session State in the application. The main purpose of session is maintaining user data in memory because of HTTP is a stateless protocol.

Before reading this article, you must read the articles given below for ASP.NET Core knowledge.

Package Required

We need to install the stable version of “Microsoft.AspNetCore.Session” from Nuget Package Manager. Then only we can access Session State in ASP.NET Core 1.1.

Session In Nuget

Microsoft.AspNetCore.Session

.csproj

In “.csproj” we can check all the installed packages and versions details in ASP.NET Core 1.1.

<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Session" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
    <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" />

Assemblies Required

These are the assemblies mainly required for accessing functionality of Session State, MVC, JSON, etc

using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

Home Controller

The following code is the example of sharing session in ASP.NET Core 1.1.

using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

namespace SessionInCore.Controllers
{
    public class HomeController : Controller
    {
        const string SessionKeyName = "_Name";
        const string SessionKeyAge = "_Age";
        const string SessionKeyDate = "_Date";

        public IActionResult Index()
        {
            HttpContext.Session.SetString(SessionKeyName, "Rajeesh Menoth");
            HttpContext.Session.SetInt32(SessionKeyAge, 28);
            // Requires you add the Set extension method mentioned in the SessionExtensions static class.
            HttpContext.Session.Set<DateTime>(SessionKeyDate, DateTime.Now);

            return View();
        }

        public IActionResult About()
        {
            ViewBag.Name = HttpContext.Session.GetString(SessionKeyName);
            ViewBag.Age = HttpContext.Session.GetInt32(SessionKeyAge);
            ViewBag.Date = HttpContext.Session.Get<DateTime>(SessionKeyDate);

            ViewData["Message"] = "Session State In Asp.Net Core 1.1";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "My Contact Details";

            return View();
        }

        public IActionResult Error()
        {
            return View();
        }
        
    }

    public static class SessionExtensions
    {
        public static void Set<T>(this ISession session, string key, T value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

        public static T Get<T>(this ISession session, string key)
        {
            var value = session.GetString(key);
            return value == null ? default(T) :
                                  JsonConvert.DeserializeObject<T>(value);
        }
    }
}

The following code contains the Key name as “SessionKeyName” & Value name as “Rajeesh Menoth”. So we can set the Session String “Key” and “Value” in SetString(“Key”,”Value”).

const string SessionKeyName = "_Name";
HttpContext.Session.SetString(SessionKeyName, "Rajeesh Menoth");

The following code contains a similar Session code as an older version of ASP.NET.

Session["Name"] = "Rajeesh Menoth";

We can Assign and Get the Session string value using “GetString(Name)” Method in a simple way.

ViewBag.Name = HttpContext.Session.GetString(SessionKeyName);

In the following way we can set and get serializable objects to Session in our application.

//Accessing Extension Method.
HttpContext.Session.Set<DateTime>(SessionKeyDate, DateTime.Now);
//Example of Extension Method.
 public static class SessionExtensions
    {
        public static void Set<T>(this ISession session, string key, T value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

        public static T Get<T>(this ISession session, string key)
        {
            var value = session.GetString(key);
            return value == null ? default(T) :
                                  JsonConvert.DeserializeObject<T>(value);
        }
    }

Configure Services

The first step is we need to add the Session services to the container. So we can add the services in “ConfigureServices” method in “Startup.cs” class in our application.

public void ConfigureServices(IServiceCollection services)
        {
            //In-Memory
            services.AddDistributedMemoryCache();
            services.AddSession(options => {
                options.IdleTimeout = TimeSpan.FromMinutes(1);
            });              
            // Add framework services.
            services.AddMvc();
        }

Configure the HTTP request pipeline

We add the “app.UseSession()” inside the Configure Method in “Startup.cs” Class because it gets called by the runtime. One more advantage is we can use this method to configure the HTTP request pipeline in our application.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseSession();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

OutPut – Active Session

Session Active

Session Active

OutPut – Session Expired

We set 1 mins as the Session Timeout in “ConfigureServices” method in Startup.cs class.

 services.AddSession(options => {
                options.IdleTimeout = TimeSpan.FromMinutes(1);//Session Timeout.
            });
Session Expire

Session Expire

Reference

See Also

You can download other ASP.NET Core source codes from MSDN Code, using the link, mentioned below.

Conclusion

We learned how to create Session State In ASP.NET Core and MVC Core. I hope you liked this article. Please share your valuable suggestions and feedback.

%d bloggers like this: