Category: Programming

Building your first ASP.NET Core MVC app with Visual Studio

  1. Get Started
    • ASP.NET Core Web Application (.NET Core)
  2. Adding Controller
  3. Adding View
    • Layout Page
      • Views/Shared/_Layout.cshtml
      • @RenderBody()
    • Passing Data from the Controller to View
      • ViewData dictionary
  4. Adding Model
    • Scaffolding a controller
      • MVC Controller with views, using Entity Framework
    • Update the database
      • dotnet ef migrations add [migration name]
      • dotnet ef database update
    • Strongly typed models and the @model keyword
  5. Working with SQL Server LocalDB
    • Seed the database
  6. Controller Methods and Views
    • Protect your controller from over-posting
    • Validate AntiForgeryToken
  7. Adding Search
  8. Adding New Field
  9. Adding Validation
    • System.ComponentModel.DataAnnotations
  10. Examining the Details and Delete Methods

See Also

 

ASP.NET Core MVC App

Models
Classes that represent the data of the app and that use validation logic to enforce business rules for that data. Typically, model objects retrieve and store model state in a database.

Views
Views are the components that display the app’s user interface (UI). Generally, this UI displays the model data.

Controllers
Classes that handle browser requests, retrieve model data, and than specify view templates that return a response to the browser. In an MVC app, the view only displays information; the controller handles and responds to user input and interaction. For example, the controller handles route data and query-string values, and passes these values to the model. The model might use these values to query the database.

 

Learning Git

Git is a software that allows you to keep track of changes made to a project over time. Git works by recording the changes you made to a project, storing those changes, then allowing you to reference them as needed.

  1. A Working Directory where you’ll be doing all the work creating, editing, deleting and organizing files.
  2. A Staging Area where you’ll list changes you make to the working directory.
  3. A Repository where Git permanently stores those changes as different versions of the project.
git init -- creates a new Git repository
git status -- inspects the contents of the working directory and staging area
git add -- adds files from the working directory to the staging area
git diff -- shows the difference between the working directory and the staging area
git commit -- permanently stores file changes from the staging area in the repository
git log -- shows a list of all previous commits
git checkout HEAD filename -- discards changes in the working directory
git reset HEAD filename -- unstages file changes in the staging area
git reset SHA -- can be used to reset to a previous commit in your commit history
git branch -- lists all a Git project’s branches
git branch branch_name -- creates a new branch
git checkout branch_name -- used to switch from one branch to another
git merge branch_name -- used to join file changes from one branch to another
git branch -d branch_name -- deletes the branch specified
git clone -- creates a local copy of a remote
git remote -v -- lists a Git project’s remotes
git fetch -- fetches work from the remote into the local copy
git merge origin/master -- merges origin/master into your local branch
git push origin branch_name -- pushes a local branch to the origin remote

See Also

Choosing the Right Source Control

Git has become wildly popular as a version control system in the development community. Companies large and small, individuals, the open source community, and others swear by Git.

Is it the right source control system for you?

After reading the following infographic, I choose to stick with Subversion.

Choosing the Right Source Control
Choosing the Right Source Control

References

ASP.NET MVC 5 Menu using Site Map Provider & Bootstrap 3 Navbar

1. Install MvcSiteMapProvider MVC5 NuGet package. This package is a SiteMapProvider implementation for the ASP.NET MVC 5 framework.

2. In web.config, downsize the MvcSiteMapProvider configuration to the minimal. Keep it simple, stupid. (KISS)

<system.web>
  <siteMap defaultProvider="MvcSiteMapProvider">
    <providers>
      <clear />
      <add name="MvcSiteMapProvider" type="MvcSiteMapProvider.DefaultSiteMapProvider, MvcSiteMapProvider" siteMapFile="~/Mvc.Sitemap" />
    </providers>
  </siteMap>
</system.web>

3. Modify the ~\Mvc.sitemap file as the following.

<?xml version="1.0" encoding="utf-8" ?>
<mvcSiteMap xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-4.0"
            xsi:schemaLocation="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-4.0 MvcSiteMapSchema.xsd">
  <mvcSiteMapNode title="Home" controller="Home" action="Index">
    <mvcSiteMapNode title="About" controller="Home" action="About" />
    <mvcSiteMapNode title="Contact" controller="Home" action="Contact" />
    <mvcSiteMapNode title="Administration" clickable="false">
      <mvcSiteMapNode title="User Mgmt" controller="Home" action="UserMgmt" />
      <mvcSiteMapNode title="Role Mgmt" controller="Home" action="RoleMgmt" />
    </mvcSiteMapNode>
    <mvcSiteMapNode title="Profile" clickable="false">
      <mvcSiteMapNode title="Change Password" controller="Home" action="ChangePassword" />
      <mvcSiteMapNode title="Separator" clickable="false" />
      <mvcSiteMapNode title="Sign Off" controller="Home" action="SignOff" />
    </mvcSiteMapNode>
  </mvcSiteMapNode>
</mvcSiteMap>

4. To support submenu inside a dropdown menu, append the following CSS to ~/Content/Site.css

/* Bootstrap Dropdown Submenu */
.dropdown-submenu {
	position: relative;
}

.dropdown-submenu > .dropdown-menu {
	top: 0;
	left: 100%;
	margin-top: -6px;
	margin-left: -1px;
	-webkit-border-radius: 0 6px 6px 6px;
	-moz-border-radius: 0 6px 6px 6px;
	border-radius: 0 6px 6px 6px;
}

.dropdown-submenu:hover > .dropdown-menu {
	display: block;
}

.dropdown-submenu > a:after {
	display: block;
	content: " ";
	float: right;
	width: 0;
	height: 0;
	border-color: transparent;
	border-style: solid;
	border-width: 5px 0 5px 5px;
	border-left-color: #cccccc;
	margin-top: 5px;
	margin-right: -10px;
}

.dropdown-submenu:hover > a:after {
	border-left-color: #ffffff;
}

.dropdown-submenu.pull-left {
	float: none;
}

.dropdown-submenu.pull-left > .dropdown-menu {
	left: -100%;
	margin-left: 10px;
	-webkit-border-radius: 6px 0 6px 6px;
	-moz-border-radius: 6px 0 6px 6px;
	border-radius: 6px 0 6px 6px;
}

.navbar-nav .divider-vertical {
    height: 40px;
    margin: 0 9px;
    border-left: 1px solid #f2f2f2;
    border-right: 1px solid #ffffff;
}

5. The MvcSiteMapProvider renders a menu as a unordered list which doesn’t fit the Bootstrap’s Navbar component. We need to create a partial view to fill this gap. Add a partial view file BootstrapMenuHelperModel.cshtml under ~\Views\Shared\DisplayTemplates

@model MvcSiteMapProvider.Web.Html.Models.MenuHelperModel
@using System.Web.Mvc.Html
@using MvcSiteMapProvider.Web.Html.Models

@helper  TopMenu(List<SiteMapNodeModel> nodeList)
{
    <nav class="navbar navbar-default" role="navigation">
        <div class="container-fluid">
            <div class="collapse navbar-collapse">
                <ul class="nav navbar-nav">
                    @foreach (SiteMapNodeModel node in nodeList)
                    {
                        string url = node.IsClickable ? node.Url : "#";

                        if (!node.Children.Any())
                        {
                            <li><a href="@url">@node.Title</a></li>
                        }
                        else
                        {
                            <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown">@node.Title <span class="caret"></span></a>@DropDownMenu(node.Children)</li>
                        }

                        if (node != nodeList.Last())
                        {
                            <li class="divider-vertical"></li>
                        }
                    }
                </ul>
            </div>
        </div>
    </nav>
}

@helper DropDownMenu(SiteMapNodeModelList nodeList)
{
    <ul class="dropdown-menu" role="menu">
        @foreach (SiteMapNodeModel node in nodeList)
        {
            if (node.Title == "Separator")
            {
                <li class="divider"></li>
                continue;
            }

            string url = node.IsClickable ? node.Url : "#";

            if (!node.Children.Any())
            {
                <li><a href="@url">@node.Title</a></li>
            }
            else
            {
                <li class="dropdown-submenu"><a href="@url">@node.Title</a>@DropDownMenu(node.Children)</li>
            }
        }
    </ul>
}

@TopMenu(Model.Nodes)

Notes: 2 value-added features worth mention in the above code snippet. a) Handle multi-level site map using Bootstrap’s Dropdowns component (This post shows 2 levels site map, I tested with 4 levels site map); b) Support adding Separator in the menu (Refer to above ~\Mvc.sitemap snippet in step 4).

6. Edit the _Layout.cshtml file again to render the MvcSiteMap’s menu using the Bootstrap menu partial view.

......
<body>
	<div class="container">
		<div class="row">
			<div class="span12">
				<nav>
					@Html.MvcSiteMap().Menu("BootstrapMenuHelperModel")
				</nav>
			</div>
		</div>
		<!-- //row -->
		<div class="row">
			<div class="span12 body-content">
				@RenderBody()
				<hr />
				<footer>
					<p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
				</footer>
			</div>
		</div>
		<!-- //row -->
	</div>
    ......
</body>
......

7. Completed!!!

DropDown Menu
DropDown Menu
DropDown Menu w/ Separator
DropDown Menu w/ Separator

You can download the code sample here.

References

Schedule Database Backup in SQL Server

1. In Microsoft SQL Server Management Studio, right-click SQL Server Agent, then click New, then click Job

2. Input Name, “JOB_BACKUP_DATABASE”

3. Click Steps, then click New

4. Input Step Name, “BACKUP DATABASE TO DISK”

5. Paste the following Command

DECLARE @todayText char(8)
SET @todayText = CONVERT(char(8), GETDATE(), 112)

DECLARE @path nvarchar(256)
SET @path = N'D:\DatabaseBackup\DB_NAME.{DATESTAMP}.bak'
SET @path = REPLACE(@path, '{DATESTAMP}', @todayText);

BACKUP DATABASE [DB_NAME]
    TO  DISK = @path
    WITH NOFORMAT, NOINIT,  NAME = N'DB_NAME - Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO

6. Click OK

7. Click Schedules, then click New

8. Input Name, “Daily 18:00″

9. Setup the appropriate schedule

10. Click OK

11. Click OK again