Quantcast
Channel: aaroncore Wiki Rss Feed
Viewing all articles
Browse latest Browse all 20

Updated Wiki: Runtime demo with custom database

$
0
0

Runtime Demo with Custom Database

In this section, I get a web project, and create database at runtime, with 2 tables referred to 2 domain classes that be created in first section. I will create a database information form and a Setup button, and finally, we will see how database created.

First, I will create a project named Aaron.Web.Demo that is a ASP.Net MVC3 Project type. And then, install a package Aaron by nuget, or select "Set as StartUp Project" and then run the "Package Manager Console", type command:

Install-Package Aaron

When the package Aaron is created successfully, I will open Web.config file, find tag <appSettings /> and you will see key named dataMapping. And now, I put a value as follows:

<appSettings><!-- another keys... --><addkey="dataMapping"value="Aaron.Data.Mapping.CatalogMap, Aaron.Data.Mapping"/></appSettings>
That is the name of domain mapping in the previous section. You can choose any mapping and put in the value attribute. In above example, I choose CatalogMap, but you can also choose ArticleMap.

The next, I open Global.asax.cs file, find Application_Start() and add the follow code:

IoC.InitializeWith(new DependencyResolverFactory());
OK now, I open HomeController.cs file, in Action Index(), change as follow :

[HttpPost]
public ActionResult Index(InstallModel model)
{
    try
    {
        if (!DataHelper.HasSettingsFileOrNotNull()) // check Settings.txt file is existed.
        {
            // create Settings.txt file.
            DataHelper.SaveSettings("SqlServer", model.TrustedConnection, model.ServerName, model.DatabaseName, model.UserName, model.Password); 
        }

        if (!DataHelper.CreateDatabase())
        {
            ViewBag.Error = "Database has been created!";
        }
        else
        {
            // init tables or instace db.var dataProviderInstance = IoC.Resolve<IDataProvider>();
            dataProviderInstance.InitDatabase();

            // create web information demo.
            IoC.Resolve<ISysConfigurationProvider<WebInformationSettings>>().SaveSettings(new WebInformationSettings()
            {
                WebName = model.WebName,
                WebUrl = "",
                AllowAccountToSelectTheme = false,
                DefaultWebThemeForDesktops = "",
                WebClosed = false,
                WebClosedAllowForAdmins = false
            });
            ViewBag.Error = "Database was created successfully!";
        }
    }
    catch
    {
        // remove Settings.txt file if error.
        DataHelper.RemoveSettingsFile();
        ViewBag.Error = "Database connection string has a more few be failed!";
    }
    finally
    {
        DataHelper.ResetCache();
    }
    return View();
}       
Then, you must create a Model named InstallModel as follow:

using System.ComponentModel.DataAnnotations;

namespace Aaron.Web.Demo.Models
{
    publicclass InstallModel
    {
        [Display(Name="Windows authentication")]
        publicbool TrustedConnection { get; set; }

        [Required]
        [Display(Name = "Server name")]
        publicstring ServerName { get; set; }

        [Required]
        [Display(Name = "Database name")]
        publicstring DatabaseName { get; set; }

        [Display(Name = "User name")]
        publicstring UserName { get; set; }

        [Display(Name = "Password")]
        publicstring Password { get; set; }

        [Required]
        [Display(Name = "Web name")]
        publicstring WebName { get; set; }
    }
}
And now, in the View Index.cshtml file, you change a little here:

@model Aaron.Web.Demo.Models.InstallModel

@{
    ViewBag.Title = "Index";
}
<h2>Index</h2><scriptsrc="@Url.Content("~/Scripts/jquery.validate.min.js")"type="text/javascript"></script><scriptsrc="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"type="text/javascript"></script><spanstyle="color:Red;">@ViewBag.Error</span>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset><legend>Create Database</legend><divclass="editor-label">
            @Html.LabelFor(model => model.TrustedConnection)
        </div><divclass="editor-field">
            @Html.EditorFor(model => model.TrustedConnection, "Windows authentication")
            @Html.ValidationMessageFor(model => model.TrustedConnection)
        </div><divclass="editor-label">
            @Html.LabelFor(model => model.ServerName)
        </div><divclass="editor-field">
            @Html.EditorFor(model => model.ServerName)
            @Html.ValidationMessageFor(model => model.ServerName)
        </div><divclass="editor-label">
            @Html.LabelFor(model => model.DatabaseName)
        </div><divclass="editor-field">
            @Html.EditorFor(model => model.DatabaseName)
            @Html.ValidationMessageFor(model => model.DatabaseName)
        </div><divclass="editor-label">
            @Html.LabelFor(model => model.UserName)
        </div><divclass="editor-field">
            @Html.EditorFor(model => model.UserName)
            @Html.ValidationMessageFor(model => model.UserName)
        </div><divclass="editor-label">
            @Html.LabelFor(model => model.Password)
        </div><divclass="editor-field">
            @Html.EditorFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)
        </div><divclass="editor-label">
            @Html.LabelFor(model => model.WebName)
        </div><divclass="editor-field">
            @Html.EditorFor(model => model.WebName)
            @Html.ValidationMessageFor(model => model.WebName)
        </div><p><inputtype="submit"value="Create Database"/></p></fieldset>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
Finally, you just build web project and run it, you will see a web form as shown below:



When you see the red notice Database was created successfully!, you just open Microsoft SQL Server Management Studio, you will see the name of the database you created earlier. And when it would be opened, you will see two tables mentioned in the previous section.



I hope this tutorial will helpful with you! If you have problems, contact me to get more help.

Viewing all articles
Browse latest Browse all 20

Trending Articles