European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How To Use C# To Send Emails with Mail Helper

clock February 27, 2016 00:28 by author Rebecca

In this post, I will create simple mail helper class for sending emails in ASP.NET MVC using C#.

IMPLEMENTATION

Step 1

Create a class name MailHelper and the add the following code:

public class MailHelper
    {
        private const int Timeout = 180000;
        private readonly string _host;
        private readonly int _port;
        private readonly string _user;
        private readonly string _pass;
        private readonly bool _ssl;

        public string Sender { get; set; }
        public string Recipient { get; set; }
        public string RecipientCC { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
        public string AttachmentFile { get; set; }

        public MailHelper()
        {
            //MailServer - Represents the SMTP Server
            _host = ConfigurationManager.AppSettings["MailServer"];
            //Port- Represents the port number
            _port = int.Parse(ConfigurationManager.AppSettings["Port"]);
            //MailAuthUser and MailAuthPass - Used for Authentication for sending email
            _user = ConfigurationManager.AppSettings["MailAuthUser"];
            _pass = ConfigurationManager.AppSettings["MailAuthPass"];
            _ssl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSSL"]);
        }

        public void Send()
        {
            try
            {

// We do not catch the error here... let it pass direct to the caller
                Attachment att = null;
                var message = new MailMessage(Sender, Recipient, Subject, Body) { IsBodyHtml = true };
                if (RecipientCC != null)
                {
                    message.Bcc.Add(RecipientCC);
                }
                var smtp = new SmtpClient(_host, _port);

                if (!String.IsNullOrEmpty(AttachmentFile))
                {
                    if (File.Exists(AttachmentFile))
                    {
                        att = new Attachment(AttachmentFile);
                        message.Attachments.Add(att);
                    }
                }

                if (_user.Length > 0 && _pass.Length > 0)
                {
                    smtp.UseDefaultCredentials = false;
                    smtp.Credentials = new NetworkCredential(_user, _pass);
                    smtp.EnableSsl = _ssl;
                }

                smtp.Send(message);

                if (att != null)
                    att.Dispose();
                message.Dispose();
                smtp.Dispose();
            }

            catch (Exception ex)
            {
            }
        }
    }

Step 2

Place the following code in the app settings of your application:

appSettings>
<add key=”MailServer” value=”smtp.gmail.com”/>
<add key=”Port” value=”587″/>
<add key=”EnableSSL” value=”true”/>
<add key=”EmailFromAddress” value=”[email protected]”/>
<add key=”MailAuthUser” value=”[email protected]”/>
<add key=”MailAuthPass” value=”xxxxxxxx”/>
</appSettings>

Step 3

If you don’t have authentication for sending emails you can pass the emtpy string in MailAuthUser and MailAuthPass.

<appSettings>
<add key=”MailServer” value=”smtp.gmail.com”/>
<add key=”Port” value=”587″/>
<add key=”EnableSSL” value=”true”/>
<add key=”EmailFromAddress” value=”[email protected]”/>
<add key=”MailAuthUser” value=””/>
<add key=”MailAuthPass” value=””/>
</appSettings>

USAGE

Add the following code snippet in your controller to call Mail Helper class for sending emails:

var MailHelper = new MailHelper
   {
      Sender = sender, //email.Sender,
      Recipient = useremail,
      RecipientCC = null,
      Subject = emailSubject,
      Body = messageBody
   };
 MailHelper.Send();

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How To Perform CSV Files (Upload & Read) in ASP.NET MVC

clock February 20, 2016 00:39 by author Rebecca

To read CSV file doesn’t mean to use String.Split(). CSV files may contain commas, carriage returns, speechmarks…etc within strings. In this post, we will learn how to upload and read CSV File in ASP.NET MVC WITHOUT using Jet/ACE OLEDB provider. It is helpful when you have to deploy your code on shared hosting, Azure website or any server where ACE Database engine is not available. In this post, we will use a fast CSV Reader.

Step 1

Create ASP.NET MVC Empty Project

Step 2

To install CSVReader, run the following command in the Package Manager Console:

Install-Package LumenWorksCsvReader

Step 3

Add New Controller say HomeController and add following action:

public ActionResult Upload()
       {
           return View();
       }

Step 4

Add View of Upload action and use following code:

@model System.Data.DataTable
@using System.Data;
 
<h2>Upload File</h2>
 
@using (Html.BeginForm("Upload", "Home", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()   
    @Html.ValidationSummary()
    
    <div class="form-group">
        <input type="file" id="dataFile" name="upload" />
    </div>
    
    <div class="form-group">
        <input type="submit" value="Upload" class="btn btn-default" />
    </div>
    
    if (Model != null)
    {
        <table>
            <thead>
                <tr>
                    @foreach (DataColumn col in Model.Columns)
                    {        
                        <th>@col.ColumnName</th>
                    }
                </tr>
            </thead>
            <tbody>
                @foreach (DataRow row in Model.Rows)
                {       
                    <tr>
                        @foreach (DataColumn col in Model.Columns)
                        {            
                            <td>@row[col.ColumnName]</td>
                        }
                    </tr>
                }
            </tbody>
        </table>
    }
}

We will read CSV file, get data in DataTable and show DataTable in View.

Step 5

Here's how to read submitted CSV file:

[HttpPost]
[ValidateAntiForgeryToken]
 public ActionResult Upload(HttpPostedFileBase upload)
{
    if (ModelState.IsValid)
    {
 
        if (upload != null && upload.ContentLength > 0)
        {                  
 
            if (upload.FileName.EndsWith(".csv"))
            {
                Stream stream = upload.InputStream;
                DataTable csvTable = new DataTable();
                using (CsvReader csvReader =
                    new CsvReader(new StreamReader(stream), true))
                {
                    csvTable.Load(csvReader);
                }
                return View(csvTable);
            }
            else
            {
                ModelState.AddModelError("File", "This file format is not supported");
                return View();
            }
        }
        else
        {
            ModelState.AddModelError("File", "Please Upload Your file");
        }
    }
    return View();
}

It is assumed the file will have column names in first row.

Output

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Connect an MVC Project to an SQL database?

clock February 18, 2016 19:59 by author Peter

I'm simply getting to grips with MVC linq etc and came across what sounds like a standard stumbling block. All the tutorials are either Code first examples or they create the information from scratch within the App_Data directory. All well and smart for a tutorial that require to be simply moveable to the readers computer, however not very useful when putting in a full scale MVC application. My first problem was my lack of knowledge of Linq to SQL. Finally, how to add an external SQL database to your MVC project:

  • Right click on "Models" folder, choose "Add New Item"
  • Add a "Link to SQL Classes" item
  • Open your "Server Explorer" pane (if you cant see it attempt "View" on the menu bar and "Server Explorer"
  • Right click on "Data Connections" and choose "Add Connection"
  • Follow the instructions.
  • almost there....
  • Expand your newly added database to look at the tables.
  • Drag the tables you wish over to the main pane of the "Link to SQL Classes" item you added at the start.
  • Hey presto, you have a database context you'll run Linq queries against.

Please bear in mind you will need to use the "Models" namespace to reference you database context objects.
And now back to highly sophisticated programming!

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How To Use ASP.NET MVC To Increase Website Performance

clock February 12, 2016 23:50 by author Rebecca

In this tutorial, we will discuss about how you can increase the performance of website using ASP.NET MVC.

1. Remove Unused view engines

protected void Application_Start()
{
    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(new RazorViewEngine());
}

2. Deploying Production Code in Release Mode

Make sure your production application always runs in release mode in the web.config
<compilation debug=”false”></compilation>

<configuration> <system.web> <deployment retail=”true”></deployment> </system.web> </configuration>

3. Use OutputCacheAttribute When Appropriate

MVC will not do any View Look-up Caching if you are running your application in Debug Mode

[OutputCache(VaryByParam = "none", Duration = 3600)]
public ActionResult Categories()
{
    return View(new Categories());
}

4. Use HTTP Compression

Add gzip (HTTP compression) and static cache (images, css, …) in your web.config:

<system.webserver><urlcompression dodynamiccompression=”true” dostaticcompression=”true” dynamiccompressionbeforecache=”true”></urlcompression>
</system.webserver>

5. Add an Expires or a Cache-Control Header

<configuration><system.webServer>
<staticContent>
<clientCache cacheControlMode=”UseExpires”
httpExpires=”Mon, 06 May 2013 00:00:00 GMT” />
</staticContent>
</system.webServer>
</configuration>

6. Uncontrolled Actions

protected override void HandleUnknownAction(string actionName)
{
       RedirectToAction("Index").ExecuteResult(this.ControllerContext);
}

7. Other Ways

  • Avoid passing null models to views
  • Remove unused HTTP Modules
  • Put repetitive code inside your PartialViews
  • Put Stylesheets at the Top
  • Put Scripts at the Bottom
  • Make JavaScript and CSS External
  • Minify JavaScript and CSS
  • Remove Duplicate Scripts
  • No 404s
  • Avoid Empty Image src
  • Use a Content Delivery Network
  • Use either Microsoft, Google CDN for referencing the Javascript or Css libraries
  • Use GET for AJAX Requests
  • Optimize Images

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Restricting HTTP Methods in ASP.NET MVC

clock February 11, 2016 20:21 by author Peter

HTTP methods are not often thought about once writing ASP.NET webforms applications. Links are GETs, buttons are POSTs and it all happens automatically. With Asp.NET MVC, and other MVC frameworks like Rails, the http method used is more obvious and developers are begining to care about which they use.

The problem is that GET requests tell visitors to your site, together with search engines, client-side web optimizers and other automatic tools, that it's safe to make the request. Which is a problem if your checkout button causes a GET. To quote Dave Thomas, paraphrasing Tim Berners-Lee, "Use GET requests to retrieve info from the server, and use POST requests to request a change of state on the server".

To help me correctly control which HTTP methods are used to access my controller actions I created an ActionFilterAttribute. ActionFilters provide a declarative way to access the executing context immediately prior to, and immediately following, the execution of an action. they're an excellent way to introduce aspect oriented programming to an asp.net mvc application. To use my action filter you attribute a controller action like this:
AllowedHttpMethods(AllowedMethods= new HttpMethods[] {HttpMethods.POST})]
public void Save()
{ ... }

The code for the Action Filter inherits from ActionFilterAttribute and overrides the OnActionExecuting event.
public class AllowedHttpMethodsAttribute : ActionFilterAttribute
    {
        public HttpMethods[] AllowedMethods { get; set; }

        public override void OnActionExecuting(FilterExecutingContext filterContext)
        {
            int count = AllowedMethods.Count(m => m.ToString().Equals(filterContext.HttpContext.Request.HttpMethod));
            if (count == 0) throw new Exception("Invalid http method: " + filterContext.HttpContext.Request.HttpMethod);
        }
    }

    public enum HttpMethods
    {
        GET,POST
    }


By adding the AllowedHttpMethods attribute to all of my controller actions I can assure that http methods are used correctly.

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Generate URLs with ASP.NET MVC

clock February 4, 2016 20:38 by author Peter

I have been operating with ASP.NET MVC for some time and yet I still had trouble making an attempt to get a URL in a view. URL generation is particularly important for ASP.NET MVC as a result of it uses a routing engine to map URLs to code. If we hard code a URL then we lose the ability to later vary our routing scheme. I have found 2 ways that currently (ASP.NET MVC preview 2) work to generate URLs in a view. the first uses the GetVirtualPath method and seems overly complicated - thus I wrapped it in a global helper:

public static string GenerateUrl(HttpContext context, RouteValueDictionary routeValues)
    {
        return RouteTable.Routes.GetVirtualPath(
            new RequestContext(new HttpContextWrapper2(context), new RouteData()),
            routeValues).ToString();
    }


But then I found that I could achieve a similar result additional simply using UrlHelper, accessible via the URL property of the view.
// link to a controller
Url.Action("Home");

// link to an action
Url.Action("Home", "Index");

// link to an action and send parameters
Url.Action("Edit", "Product", new RouteValueDictionary(new { id = p.Id }));


Or, if you want the url for a hyperlink you can get that in one step using the ActionLink method on the Html property:
Html.ActionLink<HomeController>(c => c.Index(),"Home")

So I no longer see a need for my GenerateUrl method and have removed it from my helper. All of this would be much easier if there was some documentation. Im sure there is a better way so if you can think of an improvement please leave it in the comments.

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How To Show The Progress of The Controller

clock January 22, 2016 23:52 by author Rebecca

Sometimes, the controller actions can trigger a long running background process. For example, when the user clicks a link in the page, a word document is generated in the background, and the properties of the word document is shown in the subsequent page. Generation of word documents can take anywhere between 3 seconds to 30 seconds. During this time, the user needs some feedback about the progress of the operation. This post shows how you can provide progress information to the page which triggered the long running background process.

Step 1

Consider a MVC application with two pages: Index.cshtml and Generate.cshtml. The Index.cshtml has a link - Generate. When the user clicks the link, the Generate page is shown. The Generate action is a long running operation that happens in the background. To execute long running operations from a MVC controller, we derive the controller from AsyncController. The following code snippet shows the HomeController with the background operations:

public class HomeController : AsyncController
{
    //
    // GET: /Home/

    private BackgroundWorker worker = default(BackgroundWorker);
    private static int progress = default(int);

    public ActionResult Index()
    {
        return View();
    }

    public void GenerateAsync()
    {
        worker = new BackgroundWorker();
        worker.WorkerReportsProgress = true;
        worker.DoWork += worker_DoWork;
        worker.ProgressChanged += worker_ProgressChanged;
        AsyncManager.OutstandingOperations.Increment();
        worker.RunWorkerAsync();
    }

    void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progress = e.ProgressPercentage;
    }

    void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        for (int i = 0; i < 100; i++)
        {
            Thread.Sleep(300);
            worker.ReportProgress(i+1);
        }

        AsyncManager.OutstandingOperations.Decrement();
    }

    public ActionResult GenerateCompleted()
    {
        return View();
    }

    public ActionResult GetProgress()
    {
        return this.Json(progress, JsonRequestBehavior.AllowGet);
    }
}

The three main action methods in the above controller are - Index(), GenerateAsync(), GetProgress(). Index() displays the Index page. GenerateAsync() triggers the background operation. The background operation loops 100 times and sleeps for 300 ms in each iteration. At the end of each iteration, it reports progress as a percentage.

Step 2

The GetProgress() action gets the reported progress which is stored as a static variable. The GetProgress() is triggered when the user clicks the link. The javascript in the Index page shows how the GetProgress() action method is called:

$(document).ready(
    function () {
        $("#genLink").click(
            function (e) {
                setInterval(
                    function () {
                        $.get("/Home/GetProgress",
                            function (data) {
                                $("#progress").text(data);
                        });
                    }, 1000);
            });
    });

Here's the HTML

<body>
    <h1>Progress</h1>
    <h2 id="progress"></h2>
    <div>
        @Html.ActionLink("Generate", "Generate", null,
            new { id = "genLink" })
    </div>
</body>

On clicking the link, you have caledl the setInterval() function that is triggered every second. In the recurring function, we call the action method - GetProgress(). You have displayed the progress data in the page in the progress tag.

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Implement RoleManager in ASP.NET MVC 5?

clock December 11, 2015 00:34 by author Peter

There is something great included in ASP.NET MVC 5 that looks underutilized except by the ASP.NET MVC team. the rest of us seem to be ignoring it, that is apparent when gazing the solutions on StackOverflow (and blogs) for questions like “how do i use roles with ASP.NET MVC 5?” once I check out how identity is implemented in mvc, what stands out is that the dependency injection. And, that dependency injection seems to be missing in the answers to how to implement roles. Dependency is a great tool, it’s built into the OWIN implementation, so why not use it?

To implement the role manager in MVC 5, look for a file in App_Start called IdentityConfig.cs. If you don’t have this file, look for the file that contains the implementation of your ApplicationUserManager (derived from UserManager) and ApplicationSignInManager (derived from SignInManager). At the bottom of that file, within the namespace, add the subsequent class definition:
public class ApplicationRoleManager : RoleManager<IdentityRole>
{
public ApplicationRoleManager(IRoleStore<IdentityRole, string> store) : base(store)
{
}

public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
{
    var roleStore = new RoleStore<IdentityRole>(context.Get<AuthenticationDbContext>());
    return new ApplicationRoleManager(roleStore);
}
}


There are a couple of prototypes for the produce method. during this case, I needed to urge the database context from the OWIN context, so I used the more elaborate overload. If you don’t want to do that, you can use the Create(Func&lt;T&gt;) overload, which doesn’t take any parameters.  Now, to make sure OWIN knows about your ApplicationRoleManager class, go the ConfigureAuth method in your Startup partial class implementation in Startup.Auth.cs (also in App_Start).  Or, you'll also put what I’m getting ready to show you in the Configuration method of the OWIN startup class. This class is sometimes called Startup.cs and you’ll find it in the same directory as the root web.config.
public void ConfigureAuth(IAppBuilder app)
{
   // Configure the db context, user manager and signin manager to use a single instance per request
   app.CreatePerOwinContext(AuthenticationDbContext.Create);
   app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
   app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
   app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
   …
}

See how I just stuck that line for ApplicationRoleManager there next to the other authentication delegate registrations?  Now, we can just inject the role manager right into the AccountController or whatever other controller we need.
public AccountController(
    SendMailManager emailManager,
    ApplicationUserManager userManager,
    ApplicationSignInManager signInManager,
    ApplicationRoleManager roleManager)
{
    this.MailManager = emailManager;
    this.RoleManager = roleManager;
    this.SignInManager = signInManager;
    this.UserManager = userManager;
}

As you can see, I have already used the dependency injection to insert my own mail manager. AccountController should already be set up with this kind of structure. If it’s not, though, simply changing your constructor to look like this will cause MVC to inject those dependencies into your controller. Then, all you have to do is create a property to hold that ApplicationRoleManager thing and you’re all set!
private ApplicationRoleManager roleManager;
public ApplicationRoleManager RoleManager
{
    get
    {
        return this.roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
    }
    private set { this.roleManager = value; }
}

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



European ASP.NET MVC 5 Hosting - UK :: Creating Custom Scaffold Templates in ASP.NET MVC

clock November 27, 2015 18:59 by author Scott

Microsoft provides a powerful scaffolding engine for models in ASP.NET MVC applications that use Entity Framework. Scaffolding relieves web developers from the mundane task of writing the create, read, update, and delete (CRUD) code over and over again. The scaffolding engine uses T4 templates to generate basic controllers and views for models. However, scaffolded code is just a starting point, since it often needs to be customized to meet specific business requirements or satisfy specific design patterns.

In this blog post, I’ll provide a walkthrough on how to create project-specific custom scaffold templates for ASP.NET MVC. This can be a huge time-saver in applications with a large number of controllers and views. I will use Visual Studio 2013, ASP.NET MVC 5, Entity Framework 6, and C#.

SETUP

To get started, create a new ASP.NET MVC web application and add a simple Product model with the properties shown below and build the project.

namespace CustomScaffoldingDemo.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public bool IsDeleted { get; set; }
        public DateTime CreatedDate { get; set; }
        public DateTime UpdatedDate { get; set; }
    }
}

SCAFFOLDING CONTROLLER AND VIEWS

First, let’s use default templates to scaffold a controller and CRUD views for the Product model so we can review the results. To do so, right-click the Controllers folder in Solution Explorer and click Add New Scaffolded Item. In the Add Scaffold dialog, choose the MVC 5 Controller with views, using Entity Framework. On the Add Controller dialog, create a new data context and choose appropriate options that serve as parameters for the scaffolding engine. Then hit the Add button.

The scaffolding engine will use the default T4 templates to generate code for the controller and five views and add them to the appropriate folders. At this point you have full CRUD functionality for the Product model and can run the application.

As you review the generated code, you may notice that the scaffolding engine is intelligent enough to treat the Product ID properly by not scaffolding the editor for this property on the Create or Edit forms. You may also realize that the default templates do not meet the functional specification or your desired design patterns. For example, you may want to achieve the following:

–  Created Date and Updated Date properties should be set automatically by the system on create or update action respectively, and thus should not be editable on the Create and Edit views.
–  Products should be soft-deleted, so the Delete action of the Product controller must be changed to set the IsDeleted property and updating the Product instead of deleting it from the database. Index action should only return Products with IsDeleted set to false.
–  None of the views should display the IsDeleted property.
–  Views should use @ViewBag.Title as the page header instead of the view name. 
–  You may be using a Unit of Work pattern, so all calls to save changes to the database may need to be tweaked. 

You can manually make changes to the generated code, which has several drawbacks, including:

–  Typically, you would want most, if not all, controllers and views to be consistent across all models in your application. Making similar manual changes to controllers and views for all models is not an efficient approach.
–  When you make changes to a model, you will either have to scaffold these files again and lose your manual changes or manually update all views to match the updated model.

The best way to avoid manual changes and enforce consistency is to customize the scaffold templates.

CUSTOMIZING SCAFFOLD TEMPLATES

The original T4 templates used by the scaffolding engine are located in this folder: %programfiles%\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Microsoft\Web\Mvc\Scaffolding\Templates.

While you can directly edit these templates, this will affect scaffolding for all future projects, which is not recommended. Instead, you can create project-specific copies of these templates so you can customize them. To do so, copy these templates into your MVC project’s CodeTemplates folder, following the same sub-folder structure. You only need to copy either C# or VB.NET templates, based on your project. The template filenames include the language they use. The convention is that the scaffolding engine uses the templates in the CodeTemplates project folder, if one exists, instead of the global templates.

Now you can modify these custom scaffold templates, which would affect scaffolded code only for this project. T4 templates are simply text files and can be edited directly in Visual Studio. Unfortunately, Visual Studio 2013 does not include a good T4 editor—there’s no syntax highlighting or IntelliSense. Fortunately, there are some third party add-on products that provide this functionality. Below is a screenshot of how the templates look in Visual Studio 2013. You can see I modified the header on line 26 to use @ViewBag.Title instead of the view name. 

&lt;#@ template language="C#" HostSpecific="True" #&gt;
&lt;#@ output extension=".cshtml" #&gt;
&lt;#@ include file="Imports.include.t4" #&gt;
@model &lt;#= ViewDataTypeName #&gt;
&lt;#
// The following chained if-statement outputs the file header code and
// markup for a partial view, a view using a layout page, or a regular view.
if(IsPartialView) {
#&gt; 

&lt;#
} else if(IsLayoutPageSelected) {
#&gt; 

@{
    ViewBag.Title = "&lt;#= ViewName#&gt;";
&lt;#
if (!String.IsNullOrEmpty(LayoutPageFile)) {
#&gt;
    Layout = "&lt;#= LayoutPageFile#&gt;";
&lt;#
}
#&g
t;
}

@ViewBag.Title

To learn more about scaffolding check out this walkthrough from Microsoft. To learn more about T4 templates in general, start by reading this MSDN article



European ASP.NET MVC 5 Hosting :: How to Use AngularJS in ASP.NET MVC

clock November 12, 2015 20:18 by author Scott

In this short tutorial, I will show how to use AngularJS in ASP.NET MVC. I hope that you enjoy this short tutorial and this is helpful.

Application Inception

While Angular is a framework for the modern Single Page App, I have found that a lot of our MVC applications call for a collection of these “ng-apps”. In this instance they typically don’t include the client side routing.

Please See Sample Application

The image to the right is the file structure for a sample airplane scheduling app. There are three sections:

  Home (simple js) - A simple calendar showing flights
  Details (angular) - Information about a single flight
  Manage (angular) - A place for settings, pilots, etc...

Bundle Configuration

While asset bundling is a great feature of ASP.Net, it is easy to get carried away. When I came on there were a lot of projects that just included all the js files for the entire application in a single ScriptBundle. This was one of the first places I set my sights.

I decided that a lot of the services would be shared, so they could go in their own Angular module and in their own ASP Bundle. Then each mini-app could get it’s own module and bundle. Lets take a look at theBundleConfiguration.cs file.

using System.Web.Optimization;

namespace Jobney.App.Web
{
    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/js-base").Include(
                        "~/Scripts/libs/jquery-{version}.js",
                        "~/Scripts/libs/bootstrap.js",
                        "~/Scripts/libs/select2.js",
                        "~/Scripts/libs/bootstrap-datepicker.js",
                        "~/Scripts/libs/respond.js",
                        "~/Scripts/libs/lodash.js",
                        "~/Scripts/endless.js"
                        ));

            bundles.Add(new ScriptBundle("~/bundles/ng-base").Include(
                        "~/Scripts/libs/angular/angular.js",
                        "~/Scripts/libs/angular/ui-router.js",
                        "~/Scripts/libs/angular/ui-bootstrap-custom-0.9.0.js",
                        "~/Scripts/libs/angular/ui-bootstrap-custom-tpls-0.9.0.js",
                        "~/Scripts/libs/angular/angular-animate.js",
                        "~/Scripts/libs/angular/toaster.js"
                        ));

            bundles.Add(new ScriptBundle("~/bundles/ng-shared-services")
                .IncludeDirectory("~/Scripts/apps/shared/", "*.js"));

            bundles.Add(new ScriptBundle("~/bundles/ng-manage-app")
                .IncludeDirectory("~/Scripts/apps/manage/","*.js"));

            bundles.Add(new ScriptBundle("~/bundles/ng-tripinfo-app")
                .Include(
                    "~/Scripts/libs/jquery-ui.js",
                    "~/Scripts/libs/angular/sortable.js",
                    "~/Scripts/libs/angular/select2.js",
                    "~/Scripts/libs/angular/ngAutocomplete.js"
                )
                .IncludeDirectory("~/Scripts/apps/tripinfo/", "*.js"));

            bundles.Add(new StyleBundle("~/Content/css/base").Include(
                      "~/Content/css/bootstrap.css",
                      "~/Content/css/datepicker3.css",
                      "~/Content/css/select2.css",
                      "~/Content/css/toaster.css",
                      "~/Content/css/select2-bootstrap.css",
                      "~/Content/css/font-awesome.css"
                    ));
            bundles.Add(new StyleBundle("~/Content/css/custom").Include(
                      "~/Content/css/endless.css",
                      "~/Content/css/endless-skin.css",
                      "~/Content/css/site.css"));
        }
    }
}

Then using the bundles, say in the manage app, it would look like this:

@model Jobney.Casm.Web.Models.ManageDataBootstrapper
<div data-ng-app="Jobney.Casm.ManageApp" data-ng-controller="ManageAppCtrl">
    <ul class="tab-bar grey-tab">
        <!-- content here -->
    </ul>

    <div data-ui-view></div>
</div>

@section scripts
{
    <!-- Start ng-base -->
    @Scripts.Render("~/bundles/ng-base")

    <!-- Start ng-shared-services -->
    @Html.Partial("_SharedServices")

    <!-- Start ng-manage-app -->
    @Html.Partial("_ManageAppSetup", Model)
}

Services Need Data And Data Needs Urls

As an ASP.Net MVC developer, you are probably used to letting the routing engine create urls for you when you need them. And why not? Who knows what crazy routing constraints the client/pm/other developers decided needed to be in your application. And with Razor helpers, this is pretty easy. Angular shouldn’t have to try hard to figure out those rules. So how do we combine these two worlds?

@section scripts
{
    app.constant('RouteConfig', {
        base: '@Url.Content("~/")',
        project: {
            all: '@Url.Action("All", "Project")',
            details: '@Url.Action("Details", "Project")',
            post: '@Url.Action("Post", "Project")'
        },
        vendor: {
            category: '@Url.Action("GetByCategory", "Vendor")',
            details: '@Url.Action("GetById", "Vendor")',
            getProductRating: '@Url.Action("GetByProduct", "Rating")'
        },
        resolve: function (url) {
            return this.base + url;
        }
    });
}

Such http. Many calls.

In the manage app we are going to need some data. When the situation calls for it, I don’t mind sending that data down with the app. I think I took this idea from John Papa or one of those PluralSight authors. Basically, I just use JSON.Net to serialize my dataset on the page. Let’s take a look at it.

@model Jobney.Casm.Web.Models.ManageDataBootstrapper

<script>
    (function () {
        'use strict';

        var app = angular.module('Jobney.Casm.ManageApp', [
            'ui.router',
            'ui.bootstrap',
            'Jobney.Casm.SharedServices'
        ]);

        app.factory('BootstrappedData', [function() {
            var service = {};

            service.pilots = @Html.Raw(Model.Pilots);
            service.passengers = @Html.Raw(Model.Passengers);
            service.airplanes = @Html.Raw(Model.Airplanes);
            service.settings = @Html.Raw(Model.Settings);

            return service;
        }]);       

    })();
</script>

@Scripts.Render("~/bundles/ng-manage-app")

 



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in