SignalR Chat Application with ASP.NET MVC

SignalR Chat App With ASP.NET

SignalR Chat App With ASP.NET – This article will show you an actual application using SignalR in ASP.NET MVC. The main goal for this project is to have an idea of how we can use SignalR in a real-time web application.

As stated on this site https://www.asp.net/signalr:

“ASP.NET SignalR is a library for ASP.NET developers that makes developing real-time web functionality easy. SignalR allows bi-directional communication between server and client. Servers can now push content to connected clients instantly as it becomes available.

SignalR allows us to create a real-time application over HTTP. HTTP is a standard protocol used to communicate between a client and a server. Below is sample diagram of HTTP request from a client and a server.

SignalR Chat App With ASP.NET

As you can see from the diagram above their is disconnected state between client and a server. While SignalR is like a tunnel that has a bi-directional connectivity. Please see image below.

SignalR Chat App with ASP.NET

To see how SignalR works in real time. Let’s create a Web Chat Application. This application will show a real-time and stateless manner of SignalR.

SignalR Chat App With ASP.NET

Overview:

Note:  I’m using the default MVC template of ASP.NET

I assume you have already created a project or if not you can refer to this blog post How to start with asp.net MVC.

Let’s start:

First, open Nuget Package Manager. To open go to your solution explorer and right-click on your project name. Once Nuget package manager is opened, search for SignalR and install.

SignalR Chat App with ASP.NET

To verify if the assembly reference is installed. It should look like the image below.

SignalR Chat App with ASP.NET

Second, add SignalR Hub Class. To add, right-click on your project name and select add > add new item then search for hub. Then rename your hub. In my case, I name it as ChatHub.

SignalR Chat App With ASP.NET

Open your hub class and copy the code below.

Code:

Third, open your default controller which is HomeController and create a new action result. This will return our ChatView design that we are about to create in our next steps.

Code:

Fourth,create ChatView.cshtml. Go to your solution explorer and navigate to Views >Home folder then create a new view. Right-click on Home Folder and then select add > MVC 5 View Page with Razor. Choose Layout.cshml as your layout page for your view.

SignalR Chat App With ASP.NET

Copy code below to your ChatView.cshtml

Code:

Fifth, establish a connection with your SignalR library using Jquery. Copy code below to your ChatView.cshtml.

Lastly, redesign your default view which is index.cshtml inside your Views>Home Folder. Open the file and replace content with the code below.

Code:

And we are good to go. To see the final output of this project. Run your project by pressing F5. Then register two new users for testing purposes. Then open this project in Mozilla and google chrome to see a real-time chat application. See image below.

SignalR Chat App With ASP.NET

Thank you for reading!!

Happy coding!!

Code Summary:

ChatHub.cs > Hub Class

Code:

HomeController.cs > Controller

Code:

ChatView.cshtml > View

Code:

 

Index.cshtml > Home Page View

Code:

Restful Web Services C# – ASP.NET Web API

ASP.NET Web API – In my previous blog ASP.NET Web Application using MVC I have created a simple project that explains how to create Restful Web Services(WEB API) using MVC default route. By this time I will create another project that will show you how to create ASP.NET API using API Controller class. This is the standard flow on creating API project in ASP.NET.

Let’s Start:

Step 1. First, open your visual studio and create new Project.

Restful Web Services

New Project

Step 2. Name your Project to your preference. In my case I name it as myRestAPI. Then press “OK”.

Restful Web Services

Name Project

Step 3. Select Empty from your template window shown below and check Web API from the checkbox below template option.

Restful Web Services

Select Empty Template

This is how your solution explorer looks for an Empty template project

Restful Web Services

Solution explorer

Step 4. Now add Web API Controller class inside your Controllers folder. To add right click on your Controller folder, select Add then choose New Item.

Restful Web Services

Add Web API Controller Class

Step 5. From the New Item window search for Web API Controller Class(v2) . Name your class controller then press Add.

Restful Web Services

Name Web API Controller

The image below is the API Controller Default route:

Restful Web Services

Web API URL Default Route

Step 6. Before we proceed with this file (MyAPController) let’s create an additional class inside Model folder. This will be used as a model to create our sample data later. To add, right click on your Model folder select Add then choose New Item.

Restful Web Services

Add Model Class

Step 7. Name your model. In my case, I name it as myModel.

Restful Web Services

Name Your Model

Step 8. Open myModel class then declare properties below.

Step 9. Open MyAPIController inside your Controller folder. If you name your API Controller same as mine you can copy and replace your code with the code below. If not manually create the method from the code below.

Method:

  • GetList() >> Return all data we created with our model.
  • GetName(int id) >> Return specific data by id.
  • Model >> Dummy list we create base on our myModel class.

Solution Explorer Overview – Restful Web Services

  • WebApiConfig >> contains default url route for Api Controller
  • myAPIController >> Api controller that contains our method
  • myModel >> Contains model data properties.
Restful Web Services

Solution Explorer

Step 10. To access GetList(). Run your project and navigate to this URL localhost:7831/api/myAPI

Restful Web Services

GetList()

Step 11. To access GetName(int id) >> localhost:7831/api/myAPI/GetName?id=1

Restful Web Services

GetName()

 

Code Summary:

MyAPIController

myModel:

From this moment you have now your own ASP.NET Web API. Thank you for reading.

Happy coding!!

 


Post you may like:

[pt_view id=”2384ae03it”]

Restful Web Services Tutorial with ASP.NET MVC

Restful Web Services Tutorial

Restful Web Services Tutorial – From my previous Article on how to Create Web API in ASP.NET. We have created an API method that will return Hello + the name input by the user. Now in this article let’s consume that API using a client Application.

Let’s start: – Restful Web Services Tutorial

1. Create a new ASP.NET MVC Web Application Project.

Create New Project

2. I assume you have already created a project. Now we will use again the default Controller of MVC which is HomeController. Open HomeController by navigating to Solution explorer->Controller folder and open HomeController.

HomeController

3. From your Index function inside your HomeController, lets create additional code that will connect as to the API we created from the previous blogs ASP.NET WEB API using ASP.NET MVC.

Add below Code to your index.

  • using System.Net » For Webclient(). Which is use to connect to our Web API
  • using System.Data » For DataTable()
  • using Newtonsoft.Json » JSON
  • Viewbag.Name = response » dynamically share values from our controller to our view.
  • John » Parameter value. It could be anything you want to supply.

 

Code:

The image below is the screenshot of my HomeController code.

Home Controller Code

4. Now to display this in our view and to make it as simple as possible I use ViewBag Property to pass data to our view. Now navigate to your View (index.cshtml) under Views->Home folder and open index.cshtml.

Index.cshtml

5. Replace the code from your actual index.cshtml using the code shown in the image below. This display whatever we save to our ViewBag.Name Property.

Index.cshtml

6. Lastly, Run your project using f5 to run your project in debugging mode or CTRL + f5 to run project without debugging mode. This should output parameter name we declare in this code from our index() method in HomeController.

  • string url = “http://localhost:41480/Home/HelloWorld?name=” + “John”;

If we replace the name parameter John into Regie from the code above the output should now be Hello Regie. But because I use John in my code the image below shows Hello John output.

 

Note:  Because we are using local project you need to run both API and client application to access both project. You can also publish your API in your local IIS read this thread How to Host ASP.NET Web App in IIS.

 

Output

That’s all we need in consuming Web API in ASP.NET.

Comments are greatly appreciated to improve my blog writing technique.

Thank you for reading. Happy Coding!

You might to want to revisit this blog  Create Web API in ASP.NET.


Post you may like:

[pt_view id=”2384ae03it”]

Rest API Application – ASP.NET MVC

Rest API Application – ASP.NET WEB API is a framework that allows you to build an HTTP service. This service can be accessed online using HTTP requests. API’s can include all possible method that exposed data from a database. Like INSERT, SELECT, DELETE and UPDATE. And because API is an HTTP service its method is accessible using a URL.

Let’s take a look at a simple example below on the actual way on how the API is created and behave in .NET framework.

Let’s Start: – Rest API Application

Step 1. Open your visual studio and go to File->New->Project. A New  Project dialog window will open.

Rest API Application

Create new Project

Step 2. From the left pane of New Project window select Templates->Visual C# -> Web. Then from the middle pane select ASP.NET Web Application. And name your application, in my case I name it as SampleAPI. Click “OK” if you’re done.

Rest API Application

New Project

Rest API Application

Step 3. Select a template. To make it simple we will use Web API with default MVC template. Choose Web API template and check MVC and Web API from checkbox right below you’re template option. See the image below.

Rest API Application

Templates

Because we are using MVC template for this project your start page will look like a standard ASP.NET MVC Web Application. But we are not really after the view in this project. Method inside API’s is access directly using a URL. See image below.

Rest API Application

Start View

The image below is the default Folder structure created in MVC Framework.

Rest API Application

Folder Structure

 

Step 4. Now, after you have created a Web API project navigate to your solution explorer and open HomeController inside Controller folder. As I discussed from my previous blogs about MVC, HomeController is the default controller of MVC template in ASP.NET Web Application.

Rest API Application

HomeController

Step 5. For simplicity and better understanding of this article we will create a simple method that will return name input by a user.

Ex. John => Hello John 

I name the method HelloWorld() but instead of returning Hello world we will return Hello + the name input by the user. See image below for the code.

Rest API Application

Hello World

Step 6. To access the method we just created run your project using f5 command for debugging mode.  And use the URL shown in the image below to access the method.

  • URL format localhost:port#/ControllerName/MethodName?Parameter=value.
  • Value => Supplied in the client side application

If the user input Regie as the name parameter the output would be Hello Regie

  • localhost:41480/Home/HelloWorld?name=Regie

 

Rest API Application

Output

Rest API Application

This might be a simple example but this will help you start your own WEB API Project. You can create additional method like connecting to your database and return a set of list or Update data from your database. This is all possible if you just know the concept of API’s.

To consume this API using ASP.NET MVC visit this thread Consume Web API using ASP.NET MVC

Thank you for reading. Happy Coding!!


Post you may like:

[pt_view id=”2384ae03it”]

ASP.NET MVC Entity Framework:Code First Approach

Populate HTML Table using JQUERY

ASP.NET MVC Entity framework code first approach allows you to create classes and use entity framework to generate your Table base on your design class. It has similarity with the model first approach, however it does not generate edmx file. To determine their differences visit this blog  Entity Framework Model first approach for the actual process on how the database is generated in this approach. To proceed with Code first approach below is the tutorial on how the database is generated in Code first approach.

Let’s start:

      Note:

1. I assume you have already created your project. Let’s proceed by adding class to our project. This will serve as our model so I prefer to put it inside Models folder. To add new item right click Models folder, choose Add then select Class. See image below for your guide.

Entity Framework

Add new item

2. From Add new item window, name your class. In my case I name it as Employee_Listing.

Entity Framework

Name your class

3. Copy the code below. This will serve as our model to be use by entity framework in generating our table design.

Code:

4. Now add another class for the DBContext of entity framework. This binds our model to Entity Framework and generate database schema for our model class.

Entity Framework

Employee_ListingDBContext

5.Open the file we just created and copy the code below.

Code:

6. The image below is the classes I created inside my Models folder.

Entity Framework

Model Folder

7. In order for us to connect to the desired database where we want to create our table. We need to add connection string to our web config file. Open your web.config and find this line <connectionStrings></connectionString>. Inside this line insert your Database connection string.

Note:

  • Employee_ListingDBContext –> DBCOntext class we created earlier. This should be name as the class where you bind your model into Entity Framework.
  • (localdb)\Projects-> This is my local SQL Server .
  • providerName=”System.Data.SqlClient” –> specify your provider name.

 

Code:

8. In order for me to execute the classes I made earlier I inserted a dummy data to the table and create a Table design in my Views. Open your HomeController.cs this is the default controller used to load the default view of your Web Application. See image below to locate file from your solution explorer.

Entity Framework

Solution Explorer

9. Below are the codes I used in my HomeController. From my index function I call my Entity framework class which is Employee_ListingDBContext and added dummy data to my model to be inserted to my table. I also created a list variable with our table model design where I store the data I selected from our database table and pass it to my views where I populate the data to my HTML Table.

Code:

10. Open your Index.cshtml file and copy the code below.To locate your index.cshtml navigate to Views->Home->index.cshtml or by simply right clicking anywhere inside your index function inside your HomeController and selecting Go To View option.

Entity Framework

Go To View

From your view, copy and paste codes below. This will create a table and populate data from our controller.

Note:

  • @model IEnumerable<CodeFirst_Approach.Models.Employee_Listing> – Give as access to the model list we pass from our controller.
  • @ -> drop to C# code.

Code:

11. Lastly, run your application by pressing F5 to run project in debugging mode or CTRL + F5 to run project without debugging mode.

 

Project final output:

Entity Framework

Final output

 

 


Post you may like:

 

[pt_view id=”2384ae03it”]

How: Adding Entity Framework Reference using NuGet

Adding Entity Framework

If you have already added Entity Framework you might want to check this thread ASP.NET MVC using EF for actual using of Entity framework in your code. If this is your first time you can continue reading steps below on Adding Entity Framework.

Let’s Start: – Adding Entity Framework Reference

1. Open NuGet Package Manager to add EntityFramework. Go to Tools->NuGet Package Manager ->Manage NuGet Packages for Solution. 

Adding Entity Framework

2. Search for EntityFramework and click install button.

Adding Entity Framework

Search For EntityFramework

3. Wait for NuGet Package Manager to install EntityFramework.

Adding Entity Framework

4. The image below is the view of Entity Framework after it is already installed.

Adding Entity Framework

5. To check if EntityFramework is successfully added to your project go to your solution explorer and under your reference EntityFramework should be found.

Adding Entity Framework

Project Reference

Entity Framework

You have successfully added Entity Framework to your project. You can now use it in your ASP.NET MVC Web Application.

 


You might want to check this thread..

 

[pt_view id=”d88f6acsu0″]

ASP.NET Entity Framework: Model First Approach (MVC)

Model first Approach is ASP.NET Entity framework functionality which creates a new model using entity framework designer and generate database schema from the model design. This is all found in EDMX(.edmx extension) file.

To fully understand how this entity framework approach work. I have created a simple tutorial on how to execute Model First Approach.

     Note:

Let’s start:
1. First add Add New Item to your project. In my case because it is an MVC Application I prefer placing it inside my Models folder. To add, right click on Models folder and click Add and choose New Item.

Entity Framework

Add New Item

2. Add ADO.NET Entity Data Model. Under Visual C# select Data and in the middle pane select ADO.NET Entity Data Model.

Entity Framework

ADO.NET Entity Data Model

3. Choose Empty Model then click “Finish” .

Entity Framework

Empty Model

4. After you have added ADO.NET Entity Data Model it will automatically create EDMX(.edmx extension) file. Like the image shown below.

Entity Framework

Designer

5. Add entity for your model. Right click anywhere inside EDMX designer click Add New->Entity. Refer to the image below.

Entity Framework

Add New Entity

6. Name your entity. In my case I name it as Employee and Entity Set is automatically generated by the framework as Employees.

Entity Framework

Name Entity

7. Add Scalar Property which represent your table column. To Add, right click anywhere inside your Entity and Select Add New – > Scalar Property.

Entity Framework

Add Scalar property

8. The image below is the overview of the designer with the toolbox that contains tools you can use to design your entity.

Entity Framework

Designer

9. Generate Database from Model. This will generate .sql file inside your EDMX file which contains command used to generate your database. Right click anywhere inside your designer and select Generate Database from Model.

Entity Framework

Generate Database from Model

10. From Generate Database Wizard window click “Next” to proceed.

Entity Framework

Generate Database Wizard

11. Entity Framework generate Data Definition Language(DDL) that contains command in generating Database from your model design. Click “Finish”.

Entity Framework

Data Definition Language

12. It will create .sql file that contains needed command to create your Database Schema.

Entity Framework

Employee.edmx.sql

13. Below are the codes inside Employee.edmx.sql file.

Note:
• USE[master]-> Database name. This is where I created my table when I hit on execute command with my file.

Code:

14. Open Employee.edmx.sql file and execute command to create database. Right click anywhere inside your Employee.edmx.sql editor and select Execute. See image below.

Entity Framework

Execute Command

15. A dialog box will pop-up asking for your server name where you want to create your table.

Entity Framework

Connect to server

16. Message will appear of saying “Command(s) completed successfully” .

Entity Framework

17. The image below is the table created by Entity Framework.

Entity Framework

Employees Table

You have successfully created your table. By this time you can now use Entity Framework Model first approach in your ASP.Net MVC Web application.
Thank you for reading. !!

 


Post you may like:

[pt_view id=”2384ae03it”]

Consuming SQL Stored Procedures (ASP.NET MVC Web Application)

For beginners: – SQL Stored Procedures

The objective of this project to get data from a Database Table using a stored procedure and display in a HTML Table .

Note: I’m using ASP.NET MVC Applciation

Summary of the classes I used in creating this example

  • index.cshtml » In MVC framework index is the View. This is responsible for the User Interface in the front end of your website. In this example it is the table design.
  • Controller.cs » Class that is responsible for processing of data that pass to the View.
  • function.js » Most common question asks for beginners in using MVC framework is how to pass data from a controller to a view. This is one of the answers instead of using the normal way of doing it I’m using JavaScript in transmitting data from a controller. This process populates your data in your view without reloading the whole page.
  • function.cs » I created a separate class for calling Store Procedure to modularized our function for easy debugging.

Now that you have known all of the function used for this example. I will go down the line and proceed with copying of code for your personal testing and better understanding.

OUTPUT VIEW:

Project Output

Project File structure:

File Structure

Index.cshtml

This file is responsible for your User Interface design. In ASP.NET MVC framework in every controller there is always a specific views associated with it. In this case we are using HomeController so the folder from Views->Home->index.cshtml is our main view. Navigate to this file and copy and paste code below.

User Interface

 Note:

  • <script src=”~/Scripts/jquery-1.10.2.min.js”></script> -> include JQuery Script from Scripts folder
  • <script src=”~/Scripts/function.js”></script> -> include function.js Script

Code:

 

function.cs

To modularize project I created a separate class use to connect to our store procedure. This is where all code associated to the database are found. I also created a folder called Service where I put this class.

To create a folder right click on your project name and choose Add to show all available option, then selects New Folder. Name your folder as Service.

Create new class name function.cs by right clicking on the folder you have just created. Then Select Add and choose class.

Add Class

Name your class as function.cs

Name your Class

Open the file you have just created and copy the code below.

Service Folder

To manually view Database Connection string visit this blog content How to view Connection String in Visual Studio

Code:

Note: 

  • SelectFromTable -> Name of Stored procedure we created from the previous tutorial. To view visit this blog Creating Stored Procedure.

 

HomeController.cs

This is the default Controller generated during the creation of project. We will use this as our main controller for this project. Navigate to this file and copy and paste code shown below.

Controller folder

Note:

  • Service.function myservice = new function(); -> use to access our method from service-> function.cs class.
  • Basic_Function -> Project Name
  • Service -> Folder name where I created my function.cs
  • function -> class Name

 

Code:

function.js

This script is used to update data to our html table in view. To create script file right click on the Scripts folder, Select Add then click on JavaScript File.

Add JavaScript File

Name your script as function.js

Script Name

Navigate to your file and copy and paste code below.

Script Folder

Note:  “/Home/SelectListing”

  • Home-> Controller name
  • SelectListing-> Method from HomeController

Code:

To run your project simply hit f5 button from your keyboard to run in debugging mode or hit Ctrl + f5 to run without debugging mode.


Related Post:

 

[pt_view id=”2384ae03it”]

ASP.NET MVC File Architecture

Solution Explorer

ASP.NET Web application is created with the MVC template and is auto generated by the Development Environment of Visual studio. Unlike any other framework MVC has very strict guidelines about where to place different elements like a Model should be in the Model Folder, the controller must be in the controller folder, View must be in the View folder and there’s more to it than that. If you put it a wrong place, your application might not work as you expected.

MVC is also created for the purpose of having a clean and organized coding technique. For further knowledge on how this folder is being used in this framework, let’s go down the line and make an overview of each element and folder in our solution explorer.

(You can also see blog post How to start with MVC ASP.NET Web Application)

MVC Architecture C#

The image below is the folders and files generated for a newly created Visual Studio ASP.NET MVC Web Application project. Let’s see significance in each file in the solution explorer.

MVC Architecture C#

Solution Explorer

App_Data

This folder contains application data like local Database used by the application like .mdf file. This folder doesn’t have special meaning in the MVC framework.

App_Start

This contains code that helps configure MVC application. Generally, we don’t modify this part of the code unless you are already familiar with it and wanted to configure it manually. Like RouteConfig.cs which is responsible for the routing of your application web address. BundleConfig.cs which responsible for minification of your JavaScript and CSS files.

MVC Architecture C#

App_start

Content

Content folder contains style sheet for your sites like Site.css.

MVC Architecture C#

Content

Controller

This is the heart of MVC where you can find all the classes that are responsible for the processing of data. The controller is always tied to the View folder.

MVC Architecture C#

Controller

For example, if we have HomeController in the controller folder, then we also have a Home folder in the views folder and if we have AccountController in the controller folder then we also have Account Folder in the views folder. Home Controller must be named with a Controller at the end in order for it to work.

MVC Architecture C#

View

View

This folder contains User interface of your application. See image below.

Account, Home and Manage folder are the View of your Controller while Shared folder contains a template of your Web Application. _layout.cshtml, it’s like a master page and responsible of how all your pages will look like. _LoginPartial.cshtml contains code for partial menu .Error.cshtml is responsible for displaying error. View Start.cshtml it calls the default layout of the page which is _layout.cshtml. Web.config is an app configuration file that contains assemblies needed for the project. 

MVC Architecture C#

Views

Fonts

Contains customize font you want to use in your project.

MVC Architecture C#

Font

Models

This folder contains classes that are responsible for the identification of data. This is where all application requirements are registered.

MVC Architecture C#

Script

Contains all JavaScript file of your application.

MVC Architecture C#

Script Folder

Favicon.ico -> default site logo icon

Packages.config -> this comes from nugget packages.

Web.config -> Configuration settings of your application

MVC Architecture C#

Default files

You can also refer to this link from DotNetmob.com for additional info on ASP.NET MVC Architecture.

Thank you for reading. Hope this helps. Enjoy Coding!!!

 


Related Post:

 

[pt_view id=”2384ae03it”]

How to start with ASP.NET MVC Web Application – Development

Web Application

This blog demonstrates how to start with ASP.NET Web Application. For those who are struggling with how to start a simple ASP.NET Project, let me guide you throughout the process.

Before we start we need a Development Environment to start with the project.

You can download Visual Studio 2013 from this  https://www.visualstudio.com/downloads/

If you have already installed Visual Studio on your machine we can proceed with the steps to start a project.

Begin with opening visual studio Development Environment. There are two options in starting a new project you can start from the file menu located at the top navigation bar as shown below.

Web Application

Visual Studio Developement Environtment

Or you can select New Project link from the start page of Visual Studio development environment refer to the image shown below.

Web Application

Start Page link

After that expand Visual C# node on the left pane and navigate to Web option. Then search for ASP.NET Web Application on the middle pane. Name it as MVC-SimpleApp. You can also name your apps to your preference. If you want to use different directory of your project use the browse button right below your project name. If your done click OK to proceed to the next steps. Use the image below for your guide.

Web Application

Project Options

From the New ASP.NET project dialog select template for your project Choose MVC as shown below.

Web Application

Project Template

You can also change application authentication. It is set to Individual User Accounts in default but here we‘re going to use No Authentication.  Image below is set to its default value change it to No Authentication.

Web Application

Authentication

The application will go idle for some time. Wait for Visual Studio to load necessary files needed for your project.

To run the project press f5 to run in debugging mode or Ctrl + f5 to run without debugging mode

Web Application

Website Preview

ASP.NET MVC Application includes bootstrap CSS and JavaScript by default so your site already responsive. Below is the image of the website view in small screen.

Web Application

Mobile View

From this moment you can start your first ASP.NET MVC Project.

Thank you for reading. Enjoy Coding!!

 


Related Post:

[pt_view id=”2384ae03it”]

1 2