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

How: ASP.NET MVC using Entity Framework(Database First Approach)

Entity framework is part of .NET Framework it generates necessary database command that execute connection with database without using the standard SQL queries.  To expand our understanding on how Entity Framework works. I created an ASP.NET MVC web application to share what I’ve learned. For beginners like me hopes this helps.

Image below is the table I created for this project. I name the database as Employee_Listing and for the table I name it as Table.  If this is your first time to create a database visit this thread Create Database using Visual Studio  for detailed instruction on how I created this database.

Entity Framework

Application Final UI Output:

Entity Framework

Final Output

Let’s Start:

       Note:

1. I assume you have already created a project and added entity framework if not visit the link from the note above . Now add ADO.NET Entity Data Model. I prefer adding it to my Model folder. To add, right click on the Models folder, click Add and choose New Item.

Entity Framework

Add ADO.NET Entity Data Model

2. From Add New Item window select Data under Visual C# from the left pane and choose ADO.NET Entity Data Model from the middle pane. Then name your model. In my case I name it as Employee_Listing.

Entity Framework

Name Entity Model

3. In the next window select option Generate from Database and then click “Next”

Entity Framework

Generate from database

4. Create new connection by simply clicking New Connection button

Entity Framework

Create New Connection

5. Choose Data source for your database. In my case it is Microsoft SQL Server then click “Continue”.

Entity Framework

Choose SQL Server

6. In connection properties choose your Server name and select your Database name as shown below.

Entity Framework

Choose Server and Database Name

7. To test connection of your database click “Test Connection” button. Then press “OK”.

Entity Framework

Test Connection

8. Click “Next” to proceed.

Entity Framework

Entity Model Wizard

9. Choose Table you want to add to your project.

Entity Framework

Choose Table

10. If security warning pop-up select “OK”.

Entity Framework

Security Warning

11. Visual Studio will create edmx file with the Table model for your database.

Entity Framework

Project View

12. The image below is the full screenshot of my Models folder.

Entity Framework

Models folder

13. Table.cs is the class Model of the Table I added with ADO.NET Entity Data Model.

Entity Framework

Table.cs

Code inside Table.cs

  • This is our Entity Model class. I added [Required] attribute to every property declared from this model for Data Annotation to be used for model binding to our UI form inputs.

Let’s start with the coding part

We are going to use the default Controller for MVC Template which is HomeController. Located under HomeController folder and its default view located under Views->Home->index.cshtml.

Entity Framework

Solution Explorer

1. Create a view for your application. Open Index.cshtml file refer to highlighted text shown in the image above.

Index.cshtml

  • Create a form using html helper to bind our model.
  • @using MVC_Data_Entity.Models -> gain access to our Models folder
  • @model Table -> gain access to our actual Model class which is the class Table inside Table.cs.
  • <script src=”~/Scripts/jquery-1.10.2.min.js”></script> -> Add JQuery script.
  • Get_Data() -> JavaScript function use for transferring data to our view from our Controller
  • Delete(id) -> JavaScript function that call delete function in controller to delete specific data from our database
  • Edit(id) – > JavaScript function that call select function from our controller and fill form with the existing data.
  • table_data(data) -> This is a table design JavaScript function to be fill in our table without a whole page loading.
  • @Html.ValidationSummary -> Show validation error base on the [required] attribute we set in our Table Model.
  • @Html.ValidationMessageFor -> Show validation error for specific inputs.

Code:

2. Next open your HomeController. Let’s create and apply CRUD (Create, Read, Update and Delete) which is the basic function for most of the systems.

 

HomeController.cs

Function summary for HomeController

  • Index() – > Load default view
  • Index(Table model) -> received post request from our UI form.
  • GetData() -> Get all data from our table.
  • Select_data_for_edit(int id) – > Select specific data by id from our database table
  • Delete(int id) -> Delete data from table by id
  • Update()-> Update data entry from database table
  • Insert_data(Table model) -> Insert new entry to database table

Code:

 

3. Layout.cshtml

  • This file is located at Views ->Shared->Layout.cshtml.
  • This is where we can modify sites main menu.

Code:

Final Output:

Entity Framework

Final Output

This is a working application. Hopes this help!!

Thank you for reading!! Happy coding!!


Post you may like:

[pt_view id=”2384ae03it”]

How to Create Database using Visual Studio 2013(SQL Server)

How to Create Database

– Creating a Database is very common things in most of the developers, however for a beginner like me creating one is a bit of a struggle, especially if you are just starting to learn and understand programming. So I decided to create a simple instruction to share what I learn in different ways on how to access SQL Servers. If you are using Visual Studio as your development environment, it might be familiar to you if we are going to use Visual Studio SQL object Explorer to browse for the database. If not, let me guide you using simple instruction written below.

Let’s Start: 

1. First Open Visual Studio and go to View->SQL Server Object Explorer

How to Create Database

SQL Object Explorer

2. By default SQL Object Explorer contains available SQL server. You can also add Server by simply clicking on the icon with a plus sign located at the topmost part of your SQL Server Object Explorer

How to Create Database

Connect to database

3. After clicking on the add server icon, a dialog box will show. Input server name to add the server to your Object explorer. You can use Windows authentication for authentication type, however if you set a password for your server, you might need to input valid credentials for your authentication.

How to Create Database

Connect to Server

4. Image below is my local server I added in my SQL Server Object Explorer.

How to Create Database

SQL Server Object Explorer

5. Add database to your server, expand your server and right click on Database folder then Select Add New Database. See image below.

How to Create Database
How to Create Database

Add Database

6. Create Database window will pop-up. Name your database to your likings.

How to Create Database

Name Database

7. Creating a Table. Navigate again to your SQL server, expand Database folder and under your Database right click on the Table 

How to Create Database

Add Table

8. A new window should be open in the middle pane containing default id column which is set to primary.

 

How to Create Database

Table design

9.  Set id to auto increment by highlighting the id column and going to properties located just below your solution explorer. Expand Identity Specification and set (Is Identity) to true.How to Create Database

10. Now go back to the middle pane and add additional column we need for our table.How to Create Database

11. To save changes you made to your table click on update button located above your table design then click Update Database on the next pop-up window which is the image below.How to Create Database

12. To see if table is successfully created go to your SQL Server Object Explorer and expand your database and go under Table If you haven’t see your table yet right click on your database an click refresh.                         How to Create Database

13. You can also view table data by right-clicking on your table and selecting View DataHow to Create Database

14. And in the middle pane, you can see available data for your table.How to Create Database

You’re done!

Thank you for reading!!

Happy Coding!!

 


Post you may like:

[pt_view id=”2384ae03it”]

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

How to Host ASP.NET Application in IIS

Internet Information Services (IIS) are used to host ASP.Net Web application for either used it to show your development progress or for a test run of your websites. Or if you are a freelancer and you want to show your sites to your customer, IIS might be your best and easiest way.

For beginners like me, I created simple instructions in publishing ASP.NET MVC Application in IIS.

 Note:

Let’s Start:

I. Go to IIS sites root folder and create new folder.

  1. First open your IIS Manager. By going to start menu and typing “IIS” and select Internet Information Services from the search result. Refer to the image shown below.

    Host ASP.NET Application

    Start Menu

  2. In your IIS manager expand sites folder and right click on Default Web Sites. Then select Explore to open root directory.

    Host ASP.NET Application

    Internet Information Services Manager

  3. wwwroot directory appear create a folder inside the directory. This is where we publish our Websites. In my case I name it as MySites. 

    Host ASP.NET Application

    wwwroot directory

II. Publish ASP.NET Website

My Site Preview:

Host ASP.NET Application

My Site

 

  1. Open your project in visual studio 2013 and go to solution explorer. Right click on your project name and select publish.

    Host ASP.NET Application

    Publish

  2. In the Publish Web Window choose Profile and then create new profile name for your publish profile.

    Host ASP.NET Application

    New Profile

 

  1. Enter your desired publish profile name. Then press “OK”.

    Host ASP.NET Application

    Name your profile

  2. Click “Next” to proceed. Use File System as your publish method.

    Host ASP.NET Application

    Publish Method

  3. Select your published directory. In my case it is C:\inetpub\wwwroot\MySites which the default website directory of IIS. Then click “Open”.

    Host ASP.NET Application

    Select Directory

  4. Lastly click on publish button.

    Host ASP.NET Application

    Publish Option

  5. Wait for Visual Studio to finish publishing.

    Host ASP.NET Application

    Successfully Published

III. Convert your website to IIS Application

  1. Go to your IIS Manager and navigate to Sites-> Default Web Sites. Then search for your folder name where we published our websites. In my case I name it MySites. Right click on MySites folder and select Convert to Application.

    Host ASP.NET Application

    Open IIS Manager

  2. You’re done!! To browse your site right click on MySites Select Manage Application then choose browse.

    Host ASP.NET Application

    IIS Manager

  3. Browser will appear with your site preview.

    Host ASP.NET Application

    My Sites

  4. You can also access your websites using your local IP ex. http://192.168.1.2/MySitesHost ASP.NET Application

Thank you for reading!

Hopes this help. Enjoy coding!!


Post you may like:

 

[pt_view id=”2384ae03it”]

1 2 3 4 5