Sunday, 22 October 2017

Basic ASP.NET MVC 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:
public class MVCBasicModel

    {

        public int ID { get; set; }

        public string Name { get; set; }

        public int Ecode { get; set; }

        public string Position { get; set; }

        public string Location { get; set; }

    }
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.
private List<Models.MVCBasicModel> GetData()

        {

            List<Models.MVCBasicModel> list = new List<Models.MVCBasicModel>();

           using (SqlConnection conn = new SqlConnection("Data Source=Computer Name;Initial           Catalog=sad_db;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"))

            {
                SqlCommand cmd = new SqlCommand("Select * From Employee", conn);

                conn.Open();

                SqlDataReader reader = cmd.ExecuteReader();

                while (reader.Read())

                {
                    list.Add(new Models.MVCBasicModel

                    {
                        ID = int.Parse(reader["Id"].ToString()),

                        Name = reader["Employee_Name"].ToString(),

                        Ecode = int.Parse(reader["EmpCode"].ToString()),

                        Position = reader["Position"].ToString(),

                        Location = reader["Location"].ToString()

                    });

                }

                reader.Close();
            }

            return list;
        }
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
public ActionResult Index()

        {
            return View(GetData());
        }
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
@model IEnumerable<MVCBasic.Models.MVCBasicModel>

@{

    ViewBag.Title = "Home Page";

}
<div class="jumbotron">

   <table class="table table-bordered">

       <thead>

           <tr>

               <th>ID</th>

               <th>Name</th>

               <th>Employee_code</th>

               <th>Position</th>

               <th>Location</th>

           </tr>

       </thead>

       <tbody>

           @{
               foreach (var data in Model)
               {

               <tr>
                   <th>@data.ID</th>

                   <th>@data.Name</th>

                   <th>@data.Ecode</th>

                   <th>@data.Position</th>

                   <th>@data.Location</th>

               </tr>

               }
           }

       </tbody>

   </table>

</div>
and we’re done.. Thank you for reading. Happy coding!!

Code Summary:
MVCBasicModel.cs
using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace MVCBasic.Models

{

    public class MVCBasicModel

    {

        public int ID { get; set; }

        public string Name { get; set; }

        public int Ecode { get; set; }

        public string Position { get; set; }

        public string Location { get; set; }

    }

}
 HomeController.cs
using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Data.SqlClient;


namespace MVCBasic.Controllers

{
    public class HomeController : Controller

    {
        Models.MVCBasicModel model = new Models.MVCBasicModel();

        public ActionResult Index()

        {

            return View(GetData());

        }

        private List<Models.MVCBasicModel> GetData()

        {
            List<Models.MVCBasicModel> list = new List<Models.MVCBasicModel>();

            using (SqlConnection conn = new SqlConnection("Data Source=PROG-RA;Initial Catalog=sad_db;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"))

            {
                SqlCommand cmd = new SqlCommand("Select * From Employee", conn);

                conn.Open();

                SqlDataReader reader = cmd.ExecuteReader();

                while (reader.Read())

                {
                    list.Add(new Models.MVCBasicModel

                    {

                        ID = int.Parse(reader["Id"].ToString()),

                        Name = reader["Employee_Name"].ToString(),

                        Ecode = int.Parse(reader["EmpCode"].ToString()),

                        Position = reader["Position"].ToString(),

                        Location = reader["Location"].ToString()

                    });

                }

                reader.Close();

            }

            return list;

        }    
    }

}
Index.cshtml
@model IEnumerable<MVCBasic.Models.MVCBasicModel>

@{

    ViewBag.Title = "Home Page";

}

<div class="jumbotron">

   <table class="table table-bordered">

       <thead>

           <tr>

               <th>ID</th>

               <th>Name</th>

               <th>Employee_code</th>

               <th>Position</th>

               <th>Location</th>

           </tr>

       </thead>

       <tbody>

           @{

               foreach (var data in Model)

               {

               <tr>

                   <th>@data.ID</th>

                   <th>@data.Name</th>

                   <th>@data.Ecode</th>

                   <th>@data.Position</th>

                   <th>@data.Location</th>

               </tr>

               }

           }

       </tbody>

   </table>

</div>

Enable Internet Information Service (IIS)

What Is IIS?
It is a Web Server software created by Microsoft which is designed for hosting websites.  It can be used in a standard Html page and dynamic pages like PHP pages and ASP.NET applications.To dig deeper with the definition of IIS and its history you can refer to Wikipedia.org for full details.
If you are working in a project and you want to show your progress to one of your team member in a network you might need to use IIS. Below are instructions on how to enable IIS on Windows 10.
Let’s Start:
  1. Go to your control panel. You can use start Menu then search for Control Panel then select Control panel from the search result. Use the image below for your reference.
  2. You can also use Run by holding window button from your keyboard and pressing R key then type keyword Control Panel.
                                               CTRL + R

       3. In the Control Panel Window select Uninstall program.

                                                                                 Control Panel

4. From the Installed Updates window click on the Turn Windows feature on or off link                  from the left pane.

                                                                         Installed Update

5. Windows feature window should pop-up, scroll down and search for Internet Information Services (IIS).Expand Internet Information Services and select option as shown in the image below.
                                                                             Windows Feature

6. Wait for windows to enable your Local IIS.
                                                                       Enabling IIS

7. To verify if  it is successfully enable, go to start menu and type IIS and select Internet information Services (IIS) as the image shown below.

                                                     Search for IIS

8. Internet Information Services (IIS) Manager

                                                               IIS Manager Dashboard
You’re done! Your Internet Information Service or IIS is successfully enabled. You can now start hosting your ASP.Net Web Applications from your local IIS.

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

Start Menu

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



                                                             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. 
                                                                            wwwroot directory

II. Publish ASP.NET Website
My Site Preview:
                                                                                  My Site
1.> Open your project in visual studio 2013 and go to solution explorer. Right click on your project name and select publish.
                                                                      Publish
2.> In the Publish Web Window choose Profile and then create new profile name for your publish profile.
                                                                              New Profile
3.> Enter your desired publish profile name. Then press “OK”.
                                                                             Name your profile
4.> Click “Next” to proceed. Use File System as your publish method.
                                                                         Publish Method
5.> Select your published directory. In my case it is C:\inetpub\wwwroot\MySites which the default website directory of IIS. Then click “Open”.
                                                                           Select Directory
6.> Lastly click on publish button.
                                                                       Publish Option

7.> Wait for Visual Studio to finish publishing.
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.
                                                                          Open IIS Manager
2.> You’re done!! To browse your site right click on MySites Select Manage Application then choose browse.
                                                                             IIS Manager
3.> Browser will appear with your site preview.
4.> You can also access your websites using your local IP ex. http://192.168.1.2/MySites


React Hooks - custom Hook

  v CustomHook Ø React allows us to create our own hook which is known as custom hook. Example – 1 localStorage Demo Step-1 Create ...