Tuesday, August 11, 2015

How to integrate SmartAdmin into ASP.NET MVC 5 – Part 1


How to integrate SmartAdmin 1.4.x into ASP.NET MVC 5 – Part 1

Closed
Public
Hello SmartAdmin fans!
I hope that the following quick how-to will get you started in integrating SmartAdmin inside MVC.  It will be a multi -part guide that will slowly dive deeper into enabling all the wonders that MVC has to offer, and in this Part 1 of the guide we will be setting up our developement environment with the end goal of having a website that looks and behaves exactly as the template does running on the MVC framework!
Table of Contents
Prerequisites
For the how-to’s I am asuming the availability of the following software, already installed and configured with their default settings:
  • Visual Studio 2013 — For creating the project structure and hosting the website locally (http://www.visualstudio.com)
  • Web Essentials 2.2 — For helping us in creating a fluent editing environment/experience (available inside VS2013 through Tools -> Extensions and Updates)
  • Koala 2.0.3 — For compiling and minifying the LESS and JS files on-the-fly (http://koala-app.com)
  • SmartAdmin 1.4.1 — The template of choice! (other and earlier versions might work but files and locations can differ)
  • Basic knowledge — This goes for HTML5, CSS, jQuery and C#
  • Your music of choice — I always feel that having good music in the background helps me develop ;-) (http://www.di.fm)
For Visual Studio 2013 it is highly recommended to install Update 2; Web Essentials 2.2 was optimized for this version and is assumed to have been installed throughout this guide.
Step 1 : Setting up the environment
Note: If you follow these steps you should end up with the exact same end-result as I have been able to, I understand that it can be hard without any screenshots or a reference project, but I will make these available in due time, please be patient!
  1. Open the Visual Studio 2013 edition of your choice
    • The edition should not matter, but I am using Premium so certain commands could be slightly different
    • I will be going through my own tutorial in Express edition to make sure it’s usable for hobby developers
  2. Goto: File -> New -> Project
    • Choose: Visual C# -> Web -> ASP.NET Web Application
  3. Choose the location to store your project or use the suggested default location,give it a better name and press OK
    • Suggestion: website or webapp
  4. In the following window select the “Empty” template option
    • We do this to prevent VS from adding the default Nuget packages and site structure, which would require a lot more work to get SmartAdmin ready
    • This is also to ensure that the SmartAdmin nuglets are not overwrriten with newer and possibly incompatible versions (ie, jQuery and Bootstrap)
  5. Ensure that the core references for “MVC” are selected
    • We do actually want to create an MVC site, but we have no interest in the default project template
    • This is because we have a much better one available (Woohoo!)
  6. In the Authentication section select: No Authentication
    • Integration with (forms) authentication will be explained in a later step
  7. Press OK and sit back while Visual Studio prepares your project for use
    • This will create and empty MVC 5.1 website (when Update 2 is installed)
    • If you want, you can use the Nuget Package Manager to update to MVC 5.2
Now we have to perform some custom actions to make the default MVC environment more SmartAdmin friendly,  we do this by adding some of the template resource folders to the project:
  1. Press WIN+E and browse to the folder where you have unpacked your SmartAdmin template
  2. Go inside the folder: \DEVELOPER\HTML_version\
  3. Press WIN+E again and browse to the location where your project was created/saved
  4. Your Visual Studio project/folder structure should look like this:
    • /packages/ (Added by Visual Studio when creating the MVC project)
    • /website/ (This is the name we gave to our project)
    • SmartAdmin.sln (the name of the Visual Studio solution, which I renamed after creation)
  5. Go inside the folder: website
  6. Copy the following folders from your HTML_version template folder into your project folder
    • css
    • fonts
    • img
    • js
    • sound
  7. Now go back to your Visual Studio and, with the project selected in the Solution Explorer, click on the: “Show All Files” button in the upper right corner
    • This will list all (hidden) files/directories on disk but that are not currently part of your project
  8. CTRL + left-click each folder mentioned in step 6 and then right-click and choose: Include in project
    • This will ensure that when you build and deploy your website all neccesary (resource) files are included and available
Now that we have our assets in place we need to start making some MVC changes to the website project that we created so that the template pages can be loaded and preferably looks exactly like when you double-clicked index.html!
  1. Go back to the Solution Explorer inside Visual Studio and select the “Views” folder
  2. Right-click and choose: Add -> MVC 5 Layout Page (Razor)
  3. Name the file: “_ViewStart” and press OK
  4. Select all its content by pressing: CTRL+A and replace it with the following lines:
    • @{
    •     Layout = “~/Views/Shared/_Layout.cshtml”;
    • }
    • Note: Normally this is done for you when you choose to create a default MVC site but it requires a lot of work to clean-up before you can use it with SmartAdmin
    • This references a specific path and file, so we have to create them
  5. Right click the “Views” folder and using right-click, add another folder called: “Shared
  6. Right click your new folder and select: Add -> MVC 5 Layout Page (Razor)
  7. Name the file: “_Layout” and press OK
  8. Select all its content by pressing: CTRL+A and delete it!
I hope you are still with me, it may seem like an aweful lot of preparation, but this is a one time deal, promise! So now this is were the real integration work begins, since we have already done the grunt work by preparing our environment we can start to create our “routing” folder setup so we can see the template in action! For the sake of this how-to we are going to use the “blank_.html” template as our basis, you can use any page you want, but you will have to do some more work to arrive at the same steps, it should however be much easier to adapt the approach demonstrated in this guide to add additional content using the other template pages after you have followed all the steps outlined in this guide. Use the following steps to setup our initial “landing” page for MVC using the SmartAdmin blank_.html template file:
  1. Press WIN+E and browse to the folder where you have unpacked your SmartAdmin template
  2. Go inside the folder: .\DEVELOPER\HTML_version\
  3. Find the file: “blank_.html” and open it in any editor (notepad will do just fine)
  4. Select all its content by pressing: CTRL+A, and copy it to the clipboard by pressing: CTRL+C
  5. Now go back to Visual Studio and CTRL+V inside the earlier created  “_Layout.cshtml” file
    • Optionally you can press CTRL+K+D to format the file to your preferred formatting settings (spaces, line breaks and tabs etc)
  6. Using the handy provided table of contents inside the HTML-source we can locate the “MAIN CONTENT” section
    • Using CTRL+F will speed things up here
  7. Find the section named “widget grid” (should be line 679)
  8. Fold the section by pressing the “[-]” button inside the editor on the left side of the <section> tag
  9. Now select all lines that are related and/or contain the word widget and press delete
    • For the purpose of this how-to we will not need the widgets
    • This spot is perfect for our MVC integration! (Sorry Jarvis!)
  10. In the big empty void left behind by our wild and impulsive action, paste the following codelet:
    • @RenderBody()
    • MVC needs this to serve as a “locator” to know where the contents for each page are injected into
So close you can almost taste it, AAAAAAAAH! Just a little more patience folks, Soon(tm)! Since by default MVC assumes you have a “/home/index” page/route available we have to full-fil this requirement in order to see anything at all in our browser. Of course you can change this around to any name you like, just be sure to change it throughout the MVC structure (Controller, View, Route). Without this default page, even if it’s completely empty, your site will not work and not show anything, so let’s add one shall we?
  1. Go back to Solution Explorer inside Visual Studio and select the “Views” folder
  2.  Right click and select: Add -> Folder
    • Create a folder named: “Home
  3. Right click the “Home” folder and select: Add -> MVC 5 View Page (Razor)
    • Name the file: “Index” and press OK
  4. Select all its content by pressing: CTRL+A and delete it (we seem to be doing this a lot!)
  5. In the Solution Explorer now select the “Controllers” folder
  6. Right click the on the “Controllers” folder and select: Add -> Controller
  7. In the new window that shows, select: MVC 5 Controller – Empty and click “Add
    • Change “DefaultController” to “HomeController” and click “Add”
    • A default action “Index” is created for us automaticaly which will match our created Index.cshtml view earlier, great!
  8. Press CTRL+F5
    • This should launch the website using a local built-in webserver
You’ve done it!
SmartAdmin integrated into MVC in a very basic way, but none the less a victory!  Now you might notice the spinner and loader bar taking a very very VERY long time to complete, but this partially because of the Web Essentials panel being “injected” into our site source code and an odd limitation of IIS Express it seems, but I cannot completely confirm this. However as this panel enables on-the-fly loading of resource files (CSS and JS), we will leave it enabled for now.
In Part 2 of this article series we will be using the Koala tool to help us manage the LESS and JS files and create compiled and minified CSS and JS files for use within our MVC project, as well as enable/use Web Essentials to allow our site to be magically refreshed everytime we edit an unminified LESS or JS file from our assets folder!
Hope this helps!

Sunday, August 9, 2015

ASP.NET MVC - Application Folders

ASP.NET MVC - Application Folders


To learn ASP.NET MVC, we are Building an Internet application
Part II: Exploring the Application Folders

MVC Folders

A typical ASP.NET MVC web application has the following folder content:
Solution    Application information
Properties
References
Application folders
App_Data Folder
Content Folder
Controllers Folder
Models Folder
Scripts Folder
Views Folder
Configuration files
Global.asax
packages.config
Web.config
The folder names are equal in all MVC applications. The MVC framework is based on default naming. Controllers are in the Controllers folder, Views are in the Views folder, and Models are in the Models folder. You don't have to use the folder names in your application code.
Standard naming reduces the amount of code, and makes it easier for developers to understand MVC projects.
Below is a brief summary of the content of each folder:

The App_Data Folder

The App_Data folder is for storing application data.
We will add an SQL database to the App_Data folder, later in this tutorial.

The Content Folder

The Content folder is used for static files like style sheets (css files), icons and images.
Visual Web Developer automatically adds a themes folder to the Content folder. The themes folder is filled with jQuery styles and pictures. In this project you can delete the themes folder.
Visual Web Developer also adds a standard style sheet file to the project: the file Site.css in the content folder. The style sheet file is the file to edit when you want to change the style of the application.
Content
We will edit the style sheet file (Site.css) file in the next chapter of this tutorial.

The Controllers Folder

The Controllers folder contains the controller classes responsible for handling user input and responses.
MVC requires the name of all controller files to end with "Controller".
Visual Web Developer has created a Home controller (for the Home and the About page) and an Account controller (for Login pages):
Controllers
We will create more controllers later in this tutorial.

The Models Folder

The Models folder contains the classes that represent the application models. Models hold and manipulate application data.
We will create models (classes) in a later chapter of this tutorial.

The Views Folder

The Views folder stores the HTML files related to the display of the application (the user interfaces).
The Views folder contains one folder for each controller.
Visual Web Developer has created an Account folder, a Home folder, and a Shared folder (inside the Views folder).
The Account folder contains pages for registering and logging in to user accounts.
The Home folder is used for storing application pages like the home page and the about page.
The Shared folder is used to store views shared between controllers (master pages and layout pages).
Views
We will edit the layout files in the next chapter of this tutorial.

The Scripts Folder

The Scripts folder stores the JavaScript files of the application.
By default Visual Web Developer fills this folder with standard MVC, Ajax, and jQuery files:
Scripts
Note: The files named "modernizr" are JavaScript files used for supporting HTML5 and CSS3 features in the application.

Tutorial Ringkas 6.0 More events

More events

Okay, the onclick event from last chapter was easy, but let's try creating all the code required to use an event from scratch. We will also add yet a new control, to make things more interesting - the DropDownList, which allows the user to select an item from a list. Add the folowing code snippet somewhere in the Default.aspx file:
<asp:DropDownList runat="server" id="GreetList" autopostback="true">
    <asp:ListItem value="no one">No one</asp:ListItem>
    <asp:ListItem value="world">World</asp:ListItem>
    <asp:ListItem value="universe">Universe</asp:ListItem>
</asp:DropDownList>
This thing works just like a normal HTML SELECT element, which is of course what it's translated into upon rendering. The only attribute that would seem new to a person with basic HTML experience, is the autopostback. You will learn more about postbacks in one of the next chapters, but for now, just know that it makes the control contact the server eachtime an item is selected by the user. We will use this to our benefit now, by adding an event:
<asp:DropDownList runat="server" id="GreetList" autopostback="true" onselectedindexchanged="GreetList_SelectedIndexChanged">
We are using the onselectedindexchanged event, and assigning a method from CodeBehind which does not yet exist. You are free to choose the name of the method, but using a convention with the name of the control, an underscore, and then the name of the event, helps you keep track of it all. We better go create the event, so change to the Default.aspx.cs file, and add the following method:
protected void GreetList_SelectedIndexChanged(object sender, EventArgs e)
{
    HelloWorldLabel.Text = "Hello, " + GreetList.SelectedValue;
}
Once again, we make this extremely simple. We use the SelectedValue property of our dropdown list, which holds the text from the value property of the selected item. Try running the site, and select an item from the dropdown list. Pretty neat, huh? All commen controls come with a bunch of usefull events, which you can subscribe to like this.

Tutorial Ringkas 5.0 Events

Events

ASP.NET is an event-driven way of making web applications. With PHP and Classic ASP, you have one file, which is executed line after line, from start to end. However, ASP.NET is very different. Here we have events, which are either activated by the user in one way or another. In the previous example, we used the Page_Load method. Actually, this is an event, which the Page class calls when the page is loaded. We will use the same technique in the next example, where we will add a couple of controls to our simple hello world example. To make it a bit more interesting, we will change the "world" word with something defined by the user. Have a look at this codelisting, where we add two new controls: A Button control and a TextBox control.
<form id="form1" runat="server">
<div>
    <asp:Label runat="server" id="HelloWorldLabel"></asp:Label>
    <br /><br />
    <asp:TextBox runat="server" id="TextInput" /> 
    <asp:Button runat="server" id="GreetButton" text="Say Hello!" />
</div>
</form>
As you can see, we now have the 2 new controls added, but they really can't do much at the moment. You can run the example if you wish to check this out for your self - if you click the button, the page is simply reloaded. Let's change that, and let's start by doing it the easy way. VS comes with a WYSIWYG editor, and while I hardly ever use it my self, it does make some things easier, like creating events.

So, click the Design button in the bottom of VS. Now you will see a visual representation of our page. We wish to add a Click event to the button, and this is very simply - just doubleclick the GreetButton, and you will be taken to the CodeBehind file of our page. As you can see, a fine new method has been added, called GreetButton_Click. If you have a look at the Default.aspx file (you need to go from Design view to Source view), you will see that an attribute has been added to our Button control, telling which method to call when the button is clicked. All this work done with a simple doubleclick.

Now lets add some code to our new event. We wish to use the text from the TextBox, on our good old Label with the "Hello, world!" text. This is also very simple, and all it requires is a single line of code:
HelloWorldLabel.Text = "Hello, " + TextInput.Text;
Run the project again (F6), and you will see the our old page with a couple of new controls. The "Hello, world!" text is still there, because we set it in the Page_Load event. Now try entering a name in the textbox, and press the button. Voila, the text is changed, and we have just used our first control event. Notice how we can add code which is not necessarily called unless the user performs a specific task. This is different from the good old Classic ASP/PHP approach, but you will soon get used to it, and you will probably also come to like it a lot!

Tutorial Ringkas 4.0 CodeBehind

CodeBehind

While our first example was fine, we unfortunately broke one of the coding principles of ASP.NET: To separate markup and code. As you noticed, we added a scripting block (using <% %>), where we wrote a line of C# code to use the label. While this is just fine for a small and simple example like this, we would soon get a real mess with a bunch of C# code within an even bigger amount of HTML code. If you throw in some JavaScript and some CSS as well, it will soon become very chaotic to edit. That's why MS introduced CodeBehind, a technique which allows you to completely separate markup (HTML, CSS etc.) and code (C#, VB.NET etc.). So let's remove the script block (from <% to %>) and save the file.

As we talked about earlier, VS added a file called Default.aspx.cs. If you can't see it in the Solution Explorer, then click the little plus sign left of the Default.aspx file. Open this file. Now, if you haven't worked with .NET or another non-web programming language before, it might look a bit scary at this point. It looks nothing like HTML. However, I will try to explain the different parts of the content, and soon you will hopefully see that CodeBehind is a great tool to get a better overview of your work. Here is a complete listing of the file as it looks right now:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}
For now, the top part is rather irrelevant to us. It's a list of namespaces being included with the using keyword, for usage in the file. Since this is an ASP.NET tutorial and not a dedicated C# tutorial, I won't explain this in depth. Next, we have the class. Classes are a part of the concept of Object Oriented programming, which has become very popular, especially with languages like Java and C#. OO is a very complex subject, which also won't be explained within this tutorial.

The name of this class is "_Default", and the : (colon) tells us that this class inherits from the Page class in the System.Web.UI namespace. This means that our page can already do a bunch of things, without any programming, because it inherits methods and properties from another class. All ASP.NET pages inherits from the Page class, or another class which inherits from the Page class.

The only method within this class is the Page_Load, which is called everytime the page is loaded. Let's use that to our advantage, and set the ext from this method. We can use the exact same line of code as before, but of course without the script block tags. Add the line of code between the { and } characters:
HelloWorldLabel.Text = "Hello, world!";
That's it. Run the project (F6), and have a look. The page looks exactly like before, but we have just used CodeBehind for the first time. But this example is starting to get a bit old, so in the next chapter, we will look into something a bit more interesting.

Tutorial Ringkas 3.0 Hello, world!

Hello, world!

In almost every programming tutorial you will find the classic "Hello, world!" example, and who am I to break such a fine tradition? Let me show you how you can say hello to the world from ASP.NET. Open the Default.aspx (if it's not already opened) by doubleclicking it in the Solution Explorer. It already contains a bunch of HTML markup, as well as some stuff you probably won't recognize, like the Page directive in the top, or the runat attribute on the form tag. This will all be explained later, but for now, we want to see some working code.

First of all, we will add a Label control to the page. A Label control is some what simple, since it's just used to hold a piece of text. Add the following piece of HTML-looking code somewhere between the set of <form> tags:
<asp:Label runat="server" id="HelloWorldLabel"></asp:Label>
Secondly, add this script block somewhere on the page, preferably below the Page directive in the top:
<%
    HelloWorldLabel.Text = "Hello, world!";
%>
If you haven't worked with ASP.NET before, I'm sure there's a bunch of things that you're wondering about now, but as I said, this is all about seeing some results right now. To see the page in action, use Debug -> Start Without Debugging, or simply press F6. Visual Studio will now compile your project, and launch the page you're working on in your default browser. The page will simply have a piece of text which says "Hello, world!" - congratulations, you have just created your first ASP.NET website! Here is the complete listing:
<%
    HelloWorldLabel.Text = "Hello, world!";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label runat="server" id="HelloWorldLabel"></asp:Label>
    </div>
    </form>
</body>
</html>

Tutorial Ringkas 2.0 Cipta Fail Default.aspx

With MS Visual Studio installed, we're ready to create our first ASP.NET website. In VS, this is very easy. Open the File menu and select "New Web Site". You will be presented with the following dialog:



You need to select "ASP.NET Web Site", if it's not already selected. You should also name your new site. This is done by entering a name in the Location box. This text box is probably already filled for you, with the last part being something like "Website1". You can choose to accept this, as well as the location of the project, or you can enter a new one, like I did. I have created a folder, "My Websites", and within this folder, I would like to create the new project with the name of "FirstWebSite". For now, this is less important, but later on you might wish to gather all your projects in a specific folder.

This tutorial will focus on the C# language. Once again, no knowledge of this is required, so if you already know another .NET language, you will get to learn some C# with this tutorial as well. Select C# in the Language dropdown. Now, click the Ok button to create this new website.

VS will create a very basic website for you, consisting only of a Default.aspx file (and it's partner, the Default.aspx.cs file) and an App_Data folder. I will explain this later, but for now, just accept the fact that they are there. We will only use the Default.aspx for this first example. Move on to the next chapter, for the obligatory "Hello, world!" example.