How to create custom 404 error handler in ASP.NET MVC

Custom 404 error handler – 404 Error refer to a not found resource/URL . Here’s how a default 404 Error notification looks in ASP.NET MVC.

custom 404 error handler

ASP.NET MVC has his own custom error handler that can be enable inside Web.Config file from your solution explorer.

Let’s Start:

First, to enable error redirection modify your Web.Config file.Search for <system.web> in your Web.Config and Add the code below inside the <system.web></system.web>.

Second, navigate to your Controller folder and create a controller ErrorController.This will serve as our custom error handler. Inside this controller create an action result method, let’s named it as NotFound this will return our custom view for 404 error.

Third, create a view for NotFound action result method.By default view for controller can be manually created inside View->Error folder.  Or by simply right clicking on your Not Found method inside ErrorController and selecting Add View.

custom 404 error handler

Custom Error Preview:

custom 404 error handler

 

Note: I used Bundle Config inside App_Start folder to call my custom style.css file.

custom 404 error handler

To add bundle you can simply copy the code below into your BundleConfig file where ~/Content/style.css is the location of your stylesheet and ~/Content/Custom/Error  is the name of your bundle.

  • Add(new StyleBundle(“~/Content/Custom/Error”).Include(

“~/Content/style.css”));

To call this bundle you can simply use @Styles.Render(“~/Content/Custom/Error”)

Code:

To add designed to the view we can also add icons. In my case i used the image below. Which i included inside image folder.  And used <img src=”~/images/smile.png” /> to include image in my view.

custom 404 error handler

Fourth, Create styles for your view. In my case I create a file name style.css inside content folder from solution explorer.

custom 404 error handler

Style.css Code:

And we are done. Every time a URL is invalid this error notification will appear instead of the default 404 error notification.

custom 404 error handler

Thank you for reading!! Happy coding!!

 

 

How to use WebClient in C# (System.Net.WebClient)

System.Net.WebClient
Using System.Net.WebClient class in consuming Web API.

System.Net.WebClient – The easiest way to download and upload data from and to a Web API is using Web Client. Here’s a few codes  to implement Web Client in 4 different method.

  • using System.Net;

Method: GET

Method: POST

Method: DELETE

Method: PUT


 

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:

Reporting-Creating ReportViewer Report

Reporting

1. Reporting – Create a new windows application project in your visual studio 2013 then add report viewer to your project.

Reporting

Add ReportViewer

2. Dock report viewer to your form.

Reporting

Dock ReportViewer

3. Add Dataset to your project by simply right clicking on your project name and selecting Add-New Item

Reporting

Add New Item

4. Select data from the left pane and search for Dataset from the middle pane

Reporting

Add Dataset

5. Open Dataset you just added and add DataTable. See image below.

Reporting

Create DataTable

6. Add a column to your table.

Reporting

Add Column

7. Add Report to your project (RDLC file). Right-click again on your project name in your solution explorer and select Add->New Item, then select Reporting from the left pane and choosing Report from the middle pane.

Reporting

Add RDLC Report

8. Open your RDLC report then add List tools from your toolbox located on the left side of your RDLC designer.

Reporting

Add List

9. Choose Dataset for your List Table. In my case it is Dataset1.

Reporting

Choose DataSource

10. Add a column to your list by simply right clicking on any cell and selecting Insert Column.

Reporting

Add Column

11. Manually add column name to your List Table from your DataTable. See image below.

Reporting

Add Column name

12. This is my final view of the design for my RDLC report.

 

Reporting

Final RDLC Design

13. To add Data to our list and display it in our reportviewer from our form. Copy the code below. I write my code inside form load event .

Note:
ReportViewer.Report1.rdlc

• ReportViewer -> Name of my project
• Report1.rdlc -> Name of my rdlc report
• DataSet1 -> Dataset Name

14. Then run your project by simply clicking F5 on your keyboard.

Reporting

Final View

Than you for reading!!

Happy Coding!!

LinQ Tutorial on DataTable – C#

LinQ Tutorial
LinQ Tutorial

This LINQ tutorial will show you some basic codes on implementing LINQ in C#.LINQ is an acronym for Language Integrated Query, which is descriptive for where it’s used and what it does. The Language Integrated part means that LINQ is part of programming language syntax. To have an overall view of the definition of LINQ please refer to this site I find csharp-station.com. Below are basic codes for implementing LINQ on a DataTable.

For more tutorial visit this link ASP.NET MVC Developement.

CopyToDataTable();

Note:

  • Employee -> DataTable Name

Select  All

Note:

  • Employee -> DataTable Name

Select Specific column from DataTable

 

Note:

  • Name -> Table Column Name
  • Address -> Table Column Name
  • Employee -> DataTable Name

Count()

  Note:

  • Name -> Table Column Name
  • Address -> Table Column Name
  • Employee -> DataTable Name

 

Count();

 Note:

  • Name -> Table Column Name
  • Employee -> DataTable Name
  • data -> Variable

 

ToList()

Note:

  • Name -> Table Column Name
  • Address -> Table Column Name

SUM()

Note:

  • NUmberOfEmployee-> Table Column Name
  • data -> variable
  • Employee -> DataTable Name

Group BY & order by

 

 

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″]

Import Excel to Datagridview – C#

Import Excel – This project is intended to read excel using Microsoft.Office.interop.Excel namespace.There are a lot of ways to read an excel file in C# but for beginners like me this might be a help. Below is a simple way on how to read and import data in DataGridView.

Let’s Start:

  1. Create a new project by going to File->New->Project

    Import Excel

    New project

  2. From New Project window Name your project as Upload_Data_From_Excel.(You can also name it to your preference).Then click “OK” to proceed. See image below.

    Import Excel

    Name Project (Upload_Data_From_Excel)

  3. After you have successfully created your project. Add controls to your form.
  • Add button for upload click event.
  • Add OpenFileDialog for browsing files
  • DatagridView for viewing of data

 Design it to whatever you like.

Import Excel

Create design

  1. Rename your button. To rename click on the button you added to your form and navigate to its property located below your solution explorer. In my case I name it as btn_Upload.

    Import Excel

    Change button name

  2. Now navigate to your solution explorer and right click on Reference and choose Add Reference to add Microsoft.Office.Interop.Excel .

    Import Excel

    Add Reference

  3. From reference manager window expand Assemblies and click Extensions from the left pane and search for Micorosft.Office.Interope.Excel from the middle pane.

    Import Excel

    Add Microsoft Office Interop

  4. To see if reference was successfully added go to your project solution explorer and expand Reference then look for Microsoft.Office.Interop.Excel.

    Import Excel

    Check Reference if Added

  5. After we verify and successfully added Microsoft.Office.Interop.Excel. Open your form design and double click on btn_Upload button to add button click event.

    Import Excel

    Double Click on button upload

  6. Copy and paste the code below to your btn_Upload Click Event

  1. To test, run your application by pressing ctrl + f5 without debugging or f5 for debugging mode.

    Import Excel

    Run Project

  2. Click on upload button and select your excel file.
Import Excel

Open File

Note: Data on excel file should be in table format

 

Final output:

Excel File:

Import Excel

Excel File

Project Output:

 

Import Excel

Final Output

Full Code:

Thank you for reading!

Happy Coding!!

 


Post you may like:

[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”]

Basic ASP.NET MVC Web Application Implementation

What is MVC?

  • Model View Controller (MVC) is a framework, a Programming architecture where you designed your code in 3 different modules. Model, it is where all your logical properties or data are declared. View, it is where you designed or creates your Client user interface and lastly Controller, it is where you process data and connect model to view.

MVC Diagram:

To illustrate how MVC work in ASP.NET lets create a sample project.

To be guided with the sample Project. Below are the names I used for the function.

Note:  I’m using visual studio 2013 for this tutorial

  • MVCBasicModel.cs => Name of the Model Class(Located under Models Folder)
  • HomeController.cs => Default controller generated by Visual studio after Creation of new     MVC Application Project(Located under Controller folder)
  • Index.cshtml => Default view for HomeController(Located under Views/Home Folder)

Goal: 

  • Generate data from database
  • Save in a list with model binding
  • Pass to view and display in a table

Output Preview:

To begin let’s create a new Project in Visual studio. You can also refer to my blog how to start with ASP.NET MVC Web application for detailed instructions on how to start a project.

  1. First open your Visual Studio. Navigate to File/New and then Choose Project right on top of your Visual Studio IDE.
  • IDE => Integrated Development environment
  1. New Project options will popup. Select Visual C# from the left side panel and Search for ASP.NET Web Application from the right side panel, then Click OK.
  2. After that select a template, which is MVC then click ok to proceed
  3. Congratulation!! You have successfully created your MVC project.

Now let’s create a Database and table. There are two ways in creating a database; you can use a SQL management studio or via Visual Studio. Here I’m going to use Visual Studio.

Note:  You need to have SQL Server installed on your machine to proceed with these steps

  1. To open SQL Server Explorer in Visual Studio Navigate to View from the menu bar and then click on SQL Server Object Explorer. SQL Server Object Explorer will show on left side of your visual studio IDE.
  2. Navigate to your local SQL Server. Right click on the Database folder and then click Add New Database. You can name it whatever you like, for me I name it as sad_db.
  3. After that navigate to your local SQL server again and under that you can see you’re newly created Database. Open your newly created database and go to Table Right Click on it to see add new Table option.
  4. Then add columns to your table.
  • Id => int
  • Employee_Name => varchar(100)
  • EmpCode => varchar(100)
  • Position => varchar(100)
  • Location => varchar(100)
  1. To manually insert sample data. Right click on your table again and choose view data.
  • Id => 1
  • Employee_Name => John
  • EmpCode => j-123
  • Position => Cashier
  • Location => Place

And now let’s proceed with the coding part. Let’s add our model class. From your solution explorer located on the right side panel of your Visual Studio IDE, navigate to the Model folder, then right click on it and select add option, then select the class. Name it as MVCBasicModel. This model will be used to bind with a list in our controller.

Declare these properties from your MVCBasicModel class:

In our HomeController.cs (Located under Controller folder from the solution explorer) create a separate function/method that will fetch data from our database and return data as a list. Name it as GetData ();

Note: To view Database Connection String navigate to SQL Server Object Explorer, right click on your database and then click properties. Under properties go down to Connection string then copy and replace SQL Connection string from the code below.

Passing data to the View

In your HomeController Index call our function GetData() to get the data we fetch from our database and return it  into our view, which is index.cshtml located under view/Home Folder

Index.cshtml

  • @model IEnumerable<MVCBasic.Models.MVCBasicModel> => to gain access the list we pass from our HomeController
  • Use foreach loop to manually fill our data to our table

and we’re done.. Thank you for reading. Happy coding!!

 

Code Summary:

MVCBasicModel.cs

 HomeController.cs

Index.cshtml


Related Post:

 

[pt_view id=”2384ae03it”]

Image to Base64 Encoding in C#

Image Encoding

Transmitting images through the network or through API’s and Web service in programming is a little bit tricky. And the best way to do it is to convert images into a string or to be significant convert it into ASCII code which is commonly understood by most of the computer system. On this page we are going to use Base64 encoding to convert an image into a string and as well as decoding it.

Note: Base64 encoding is not an encryption it is just done to safely transmit images or any bigbyte data without modification or being misinterpreted with any other computer systems.

Tutorial diagram

  • ImgToBase64() => function use to generate baser64 string from an image (image to base64 Conversion)
  • Base64ToImg()=> function use to convert base64 string to an image object
  • CreateImageObject() => function use to generate image object use for ImgToBase64() for testing

Let’s start by declaring namespaces we need for the conversion:

  •  using System.Drawing; => For creating new Image Object;·
  • using System.IO; => for memory stream, use to store our image in bytes

Image to Base64 Conversion

Base64 String to Image Conversion

Creating an image Object  => For Testing

Thank you for reading!! Happy Coding.

 


Post you may like:

[pt_view id=”2384ae03it”]

1 2