European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC 5 Hosting - HostForLIFE.eu :: How to Make ASP.NET MVC 5 Run in Ubuntu?

clock March 31, 2016 18:04 by author Anthony

ASP.NET is a programming framework to create web application server side. ASP.NET using C # code is well structured so it is easy to understand and repair. C # also provides a variety of code hint, hint error before the code is executed. C # is executed using JIT system, so it may be able to run faster than interpreted languages like PHP.

But until a few years ago ASP.NET can only run on windows platform. Because there are some who still is Microsoft's patents, these projects difficult to run optimally and tend to be limited compatibility, even dotGNU project to a halt in 2012. So today I will discuss about how to run ASP.NET MVC 5 on Ubuntu Linux.

Before that some things need to be prepared, such as:

  • Computers with 14:04 LTS Ubuntu operating system.
  • ASP.NET MVC 5 that has been published.
  • Internet connection.

How to Make ASP.NET MVC 5 Run in Ubuntu?

  • Make sure that your operating system has been updated by running the following command:
    sudo apt-get update && sudo apt-get dist-upgrade
  • Install apache2 package by running the command:
    sudo apt-get install apache2
  • Input Mono into the system package list, this needs to be done so that the mono version that will be installed up to date. make sure you run the code below line by line.
    sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
    sudo echo "deb http://download.mono-project.com/repo/debian wheezy main" | sudo tee /etc/apt/sources.list.d/mono-xamarin.list
    sudo echo "deb http://download.mono-project.com/repo/debian wheezy-apache24-compat main" | sudo tee -a /etc/apt/sources.list.d/mono-xamarin.list
    sudo echo "deb http://download.mono-project.com/repo/debian alpha main" | sudo tee /etc/apt/sources.list.d/mono-xamarin-alpha.list
    sudo apt-get update && sudo apt-get dist-upgrade
  • Install mono-complete package
    sudo apt-get install mono-complete
  • Install libapache2-mod-mono package
    sudo apt-get install libapache2-mod-mono
    sudo a2enmod mod_mono_auto
  • Set apache2, so that the apache2 folder using mono. This procedure must be repeated for each new application
    sudo nano /etc/apache2/sites-available/testasp.conf
  • Copy-paste the following lines into the console, adjust the path and name if necessary. click ctrl + o, enter the ctrl + x to save the file.
    Alias /testasp "/var/www/html/testasp"
    MonoServerPath inventory "/usr/bin/mod-mono-server4"
    MonoDebug inventory true
    MonoSetEnv inventory MONO_IOMAP=all
    MonoApplications inventory "/testasp:/var/www/html/testasp"
    <Location "/testasp">
    Allow from all
    Order allow,deny
    MonoSetServerAlias inventory
    SetHandler mono
    SetOutputFilter DEFLATE
    SetEnvIfNoCase Request_URI "\.(?:gif|jpe?g|png)$" no-gzip dont-vary
    </Location>
    <IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/javascript
    </IfModule>

  • Create a new folder in the / var / www / html / testasp, adjust permissions folder if necessary. Asp.net files will be stored here.
    sudo mkdir /var/www/html/testasp
  • Enable configuration site that have been created.
    sudo a2ensite testasp
    sudo service apache2 restart
  • Upload or copy the files you want to run ASP.NET MVC into the folder / var / www / html / testasp.
  • Test sites in the browser, adjust your url with IP engine.
  • Done. You have been successfully run ASP.NET MVC 5 on the Linux operating system.

 

HostForLIFE.eu ASP.NET MVC 5 Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They
offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Create & Update Cookie in ASP.NET MVC?

clock March 30, 2016 23:25 by author Peter

Today, we will explain you about how to create and update cookie in ASP.NET MVC. An HTTP cookie (also called web cookie, Internet cookie, browser cookie or simply cookie), is a small piece of data sent from a website and stored in the user's web browser while the user is browsing. Every time the user loads the website, the browser sends the cookie back to the server to notify the user's previous activity. Cookies were designed to be a reliable mechanism for websites to remember stateful information (such as items added in the shopping cart in an online store) or to record the user's browsing activity (including clicking particular buttons, logging in, or recording which pages were visited in the past). Cookies can also store passwords and form content a user has previously entered, such as a credit card number or an address.

The output of the index.aspx runs over the Home Controller:
public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";
        string cookie = "There is no cookie!";
        if(this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Cookie"))
        {
            cookie = "Yeah - Cookie: " + this.ControllerContext.HttpContext.Request.Cookies["Cookie"].Value;
        }
        ViewData["Cookie"] = cookie;
        return View();
    }

Here it is detected if a cookie exists and if yes than it will be out given.
These two Links guide you to the CookieController:
public class CookieController : Controller
{

    public ActionResult Create()
    {
        HttpCookie cookie = new HttpCookie("Cookie");
        cookie.Value = "Hello Cookie! CreatedOn: " + DateTime.Now.ToShortTimeString();

        this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
        return RedirectToAction("Index", "Home");
    }

    public ActionResult Remove()
    {
        if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Cookie"))
        {
            HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["Cookie"];
            cookie.Expires = DateTime.Now.AddDays(-1);
            this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
        }
        return RedirectToAction("Index", "Home");
    }

}


With the create method it´s quite simple to create a Cookie and lay it down into the response and afterwards it turns back to the Index View.

The remove method controls if a cookie exists and if the answer is positive the Cookie will be deleted directly.

Beware while deleting cookies:
This way to delete a cookie doesn´t work:
this.ControllerContext.HttpContext.Response.Cookies.Clear();


The cookie has to go back to the remove (like it is given in the Cookie Controller) and an expiry date should be given. I´m going to set it on yesterday so the browser has to refuse it directly.

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 5 Hosting - HostForLIFE.eu :: How to Create ASP.NET MVC 5 Page

clock March 29, 2016 18:31 by author Anthony

Here we will give an example of how to create ASP.NET MVC 5 page with examples, they can be seen on ASP.NET MVC framework to be displayed on the web browser. We are going on to describe some things about the basics of ASP.NET MVC that should be known.

You need to know what is included on the MVC Pattern Architectural Pattern. And software design pattern that is used in ASP.NET MVC is Front Controller, which means that the control will be concentrated in a class alone. While ASP.NET Web Forms is different because it has a controller on each page.

Here's how the MVC, can be seen in the following figure

 

In ASP.NET MVC 5, the address will be written in the address bar on your web browser does not show as physical files, because of the configuration and routing processes that can be seen in Global.asax.cs and RouteConfig.cs file (folder App_start).

Global.asax file can also be found on the project ASP.NET Web Forms, this file serves as an application file that is responsible for the events at the application level is raised by ASP.NET or HttpModules. At the time the application is run, namely on Application_Start method, can be seen there are file event handling. Then it can be seen on these methods belong to the class RouteConfig. Here is the content of the class RouteConfig residing on file in the folder App_Start RouteConfig.cs.

It can be seen that the name of the default controller is used in this application is Home. This means that if you follow the code needs to be created with the name of the Home controller class, and then save it in a folder Controllers.

To add this class please right click on the folder and select Add Controller > Controller

Select the MVC Controller 5 - Empty and then click the Add button.

It will display a window Add Controller that serves to give the name of the controller class that will be created. For example, assign a name to the Home Controller Controller name column, then click the Add button.

Here is the content of the class controller of HomeController that have been made :

Then make special view for HomeController class in Home folder with index.cshtml. Then right click on the Home folder, then choose Add > New Item. After that, Choose MVC 5 View Page, give a name as you desire, click Add button.

Then you can modify Index.cshtml file like this :

You can try it on your web browser, then this will be the result

HostForLIFE.eu ASP.NET MVC 5 Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



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.



About HostForLIFE

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in