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 & 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.

 

Send Email Using ASP.NET Core 1.1 With MailKit In Visual Studio 2017


Introduction

We are familiar with Sending Email Using Asp.Net With C#. But today, we are going to teach you how to send email using ASP.NET Core 1.1 with MailKit. We can implement it in ASP.Net Core very easily as compared to the previous versions of ASP.NET.

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

MailKit

MailKit is a cross-platform mail client library built on top of MimeKit. That means we get all the mail sending libraries from MailKit, such as – Simple Mail Transfer Protocol (SMTP) etc.

Simple Mail Transfer Protocol (SMTP)

Simple Mail Transfer Protocol (SMTP) is a TCP/IP protocol used in sending and receiving e-mail. Most e-mail systems that send mail over the Internet use SMTP to send messages from one server to another.The messages can then be retrieved with an e-mail client using either POP or IMAP.

The following is a list of SMTP Server and Port Numbers.

Sl.No Mail Server SMTP Server( Host ) Port Number
1 Gmail smtp.gmail.com 587
2 Outlook smtp.live.com 587
3 Yahoo Mail smtp.mail.yahoo.com 465
4 Yahoo Mail Plus plus.smtp.mail.yahoo.com 465
5 Hotmail smtp.live.com 465
6 Office365.com smtp.office365.com 587
7 zoho Mail smtp.zoho.com 465

Assemblies Required

The following assemblies are required for sending email using ASP.NET Core with MailKit.

using MailKit.Net.Smtp;
using MimeKit;

Adding MailKit in Our Project

Go to “Tools -> NuGet Package Manager -> Manage Nuget Package for Solutions…” Then, search “MailKit”, Choose and Install the latest version “V1.12.0” in your application.

MailKit Installation

MailKit Installation

Project Structure

New .NET Core tooling is available in Visual Studio 2017 by default. In the Dependencies folder, every package tool has separate folder like MailKit saved into NuGet folder. If you have a client side tool like bower, then its dependencies are saved into it’s folder.

Project Structure ASP.NET Core 1.1

Project Structure ASP.NET Core 1.1

Code

The following code contains the mail sending code of ASP.NET Core.

using MailKit.Net.Smtp;
using MimeKit;
using System;

namespace EmailApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                //From Address
                string FromAddress = "From Email Address";
                string FromAdressTitle = "Email from ASP.NET Core 1.1";
                //To Address
                string ToAddress = "To Email Address";
                string ToAdressTitle = "Microsoft ASP.NET Core";
                string Subject = "Hello World - Sending email using ASP.NET Core 1.1";
                string BodyContent = "ASP.NET Core was previously called ASP.NET 5. It was renamed in January 2016. It supports cross-platform frameworks ( Windows, Linux, Mac ) for building modern cloud-based internet-connected applications like IOT, web apps, and mobile back-end.";

                //Smtp Server
                string SmtpServer = "smtp.gmail.com";
                //Smtp Port Number
                int SmtpPortNumber = 587;

                var mimeMessage = new MimeMessage();
                mimeMessage.From.Add(new MailboxAddress(FromAdressTitle, FromAddress));
                mimeMessage.To.Add(new MailboxAddress(ToAdressTitle, ToAddress));
                mimeMessage.Subject = Subject;
                mimeMessage.Body = new TextPart("plain")
                {
                    Text = BodyContent

                };

                using (var client = new SmtpClient())
                {

                    client.Connect(SmtpServer, SmtpPortNumber, false);
                    // Note: only needed if the SMTP server requires authentication
                    // Error 5.5.1 Authentication 
                    client.Authenticate("From Address Email", "Password");
                    client.Send(mimeMessage);
                    Console.WriteLine("The mail has been sent successfully !!");
                    Console.ReadLine();
                    client.Disconnect(true);

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}

Important Points

  • When you are sending mail with your “gmail” account, enable less secure apps so that you will be able to login from all apps. Otherwise, it will throw authentication error like 5.5.1 authentication.
  • Remove 2-Step Verification.

In the following code, we can mention username for “gmail” account but in other service like “hotmail”, we must provide the full email address because other Microsoft accounts, like Outlook, live, etc. have the same SMTP Server Address “smtp.live.com”.

client.Authenticate("From Address Email", "Password");

csproj

In previous version, ASP.NET Core 1.0 contained all the versions & dependencies in project.json file but in new version, i.e., ASP.NET Core 1.1, they are saved in csproj.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="MailKit" Version="1.12.0" />
  </ItemGroup>

</Project>

Output

References

Conclusion

We learned how to send email using ASP.NET Core 1.1 with MailKit in Visual Studio 2017. I hope, you liked this article. Please share your valuable suggestions and feedback.

Visual Studio 2017 : New Features & Installation


Introduction

Feeling great & Looking Smart. I know every one is excited for the new release of “Visual Studio 2017”. Yes , Microsoft Visual Studio celebrated it’s 20th years of glory with all tech lovers in the world love it. Now, it has come up with lots of excitement. Thus, I am happy to share the important features of Visual Studio 2017 with all the tech lovers.

Visual Studio 2017 System Requirements

The following are the minimum requirements of Visual Studio 2017 installation.

Download Visual Studio 2017

Go to this link Visual Studio 2017 , choose & download your favorite edition.

Installing Visual Studio 2017

Visual Studio 2017 Installation Window shows 3 sections.

  1. Workloads
  2. Individual components
  3. Language packs

Workloads

We can choose the appropriate development section from Visual Studio Workloads. I selected “ASP.NET and Web development & .NET Core cross-platform development”. It also contains around 5.50 GB. Thus, If you select all Workloads, then it will reach 50 GB+.

Individual components

We can choose the required component from this section.

Language packs

We can use different languages in Visual Studio. Thus, we can choose the appropriate language in this section.

Installation Process

We are going to install Visual Studio Community 2017 edition in our machine. Ones the following process is complete, we can launch & access the new features in Visual Studio 2017.

Features in Visual Studio 2017

The following are the new features in Visual Studio 2017.

Live Unit Testing

This feature is only available in Visual Studio 2017 Enterprise edition. Without running the solution, we can easily test the Application because few hidden background process happens in our Application through “Live Unit Testing”. We can enable Live Unit Testing for which you need to go to the “Test” command of the top-level menu bar in VS, choose “Live Unit Testing”, then “Start”.

Image Credit : Channel 9 Visual Studio 2017 Lanuch

Image Credit : Channel 9 Visual Studio 2017 Lanuch

We noticed that 3 symbols appeared in our code due to running on background Live Testing.

  • Cross Sign – line of executable code. The test is covered and it indicates that a failure test.
  • Tick Mark – line of executable code. The test is covered and it indicates that a success test.
  • Minus – line of executable code. Not yet covered a single Test.

Dotted Line

The is a very cool feature in Visual Studio 2017 because this option helps to identify the exact open and close curly braces “{}” through dotted line in our code. This dotted line is really helpful for when you are working on a bulk amount of code in a single page.

Filttered IntelliSense Search

The new Filtering IntelliSense Search option is available in Visual Studio 2017. This option is one of the powerful way to consume the search time in our code. The following IntelliSense bottom tray contains icons as Properties, Interface, Modules, Namespaces, Enums, Classes, Constants etc. For example, if i want to search an Interface, then I can choose an Interface Icon from the bottom of the tray, else it will show all the possible contents in our solution.

Improvements Of Navigation Controls

  1. Go to All ( Cntrl + T )
  2. Go to Line ( Cntrl + G )
  3. Go to File ( Cntrl + 1 + F )
  4. Go to Type ( Cntrl + 1 + T )
  5. Go to Member ( Cntrl + 1 + M )
  6. Go to Symbol ( Cntrl + 1 + S )

Go to All ( Cntrl + T )

Press “Cntrl + T”, then it will display one tray above the search bar. Thus, we can search the content with the help of the options given below like Line/Files/Types/Members/Symbols. For example, I want to search type in our entire solution or an Application. Now, choose “Type” Icon in the tray and type in the search bar, so it will filter and show the exact results as much as faster than the earlier versions of VS. The shortcut is “Cntrl + 1 + T”.

Find All Reference ( Shift + F12 )

We can find all the references in our entire solution. The highlighted one is all the reference results by a combination of project, definition and path.

Code Suggestions

This is a very exciting feature in VS2017. It gives us the good code practice in our Application. The code given below notices that we have written an “If” condition without curl braces. Thus, it gives us the suggestion tp add the curl braces to understand the code.

Code Style Changing

We can change the code style option in our VS2017. Go to “Tools -> Options -> Text Editor -> Basic -> Code Style -> Naming”.

Reference

Conclusion

We learnt installation & new features of Visual Studio 2017. I hope, you liked this article. Please share your valuable suggestions and feedback.

Getting started with ASP.NET Core 1.0


Introduction

In this article, I will explain how to Install a .NET Core tools preview for Visual Studio and how to print “Hello World” in the latest Asp.Net Core 1.0.

Step 1 :

First download Visual Studio 2015 with Update 3 through the link  click here.

Step 2 :

Go to Install .NET Core tools preview for Visual Studio. This .NET Core tools adds support for .NET Core projects in Visual Studio 2015.

Install Dotnet Core

Install DotNet Core

Step 3 :

This is really interesting !! Open Visual Studio 2015 and create new Project.

Open Templates – > Visual C# -> Click .NET Core Category and you can see “ASP.NET Core Web Application” template.

DotnetCore Template in VS 2015

DotnetCore Template in VS 2015

Step 4 :

Select Empty Templates ( based on your requirement ) in Asp.Net Core Templates Category. If you are going to host the app in Microsoft Azure Service and check in the “Host in the cloud option”.

DotNet Core Empty Page

DotNet Core Empty Page

Step 5 :

Open “Startup.cs” class in “HelloWorldDotnetCore” project folder.

Dotnet Core Startup Class

Dotnet Core Startup Class

Step 6 :

We are creating mini middle ware Application, using lambda expression in “app.Run”. This piece of code is creating “Hello World”.

C# Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace HelloWorldDotnetCore
{
    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
        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();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
           app.Run(async (context) =>
            {
                await context.Response.WriteAsync(" Welcome to Dotnet Core !!");
            });
           
        }
    }
}

Output 1 :

Dotnet Core Hello World

Dotnet Core Hello World

Step 7 :

Two “app.run” doesn’t work in .Net Core followed by using “app.Use”. It will pass two parameters and Add the next middleware content In .Net Core.

C# Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace HelloWorldDotnetCore
{
    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
        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();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.Use(async (context, next) =>
            {
                await context.Response.WriteAsync("Hello World!!");
                await next();
            });

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync(" Welcome to Dotnet Core !!");
            });
           
        }
    }
}

Output 2 :

Dotnet Core Output 2

Dotnet Core Output 2

Reference :

Conclusion :

We learned how to Install .NET Core tools preview for Visual Studio and how to print “Hello World” in the latest ASP.NET Core 1.0.

DISPLAY LINE NUMBERS IN THE VISUAL STUDIO EDITOR


Introduction 

In this article you will learn how to set the line number in Visual Studio Editor.We can simply set this option in two or four steps.The main purpose of setting this option is we can easily find out the code line number in both aspx page and aspx.cs page.Other important one is when we facing an error in programming it’s providing the line number and error message details.So we can quickly find out the code line number.

Step 1: Before setting the line code number in Visual Studio the both pages are look like this.

1

Figure 1

2

Figure 2

Step 2: Select Tools section in visual studio editor. Select -> Tools -> Options.

3

Figure 3

Step 3: Open the Text Editor , Text Editor -> All Languages -> General -> Click the check box Line Numbers -> Click Ok.

4

Figure 4

Step 4: After the step 3 just check out the both pages like aspx and aspx.cs.

5

Figure 5

6

Figure 6

Summary

We learned how to set the line number in Visual Studio Editor. I hope this article is useful for all .NET beginners.

%d bloggers like this: