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 Call A C# Function With jQuery AJAX In ASP.NET MVC?

clock July 27, 2018 11:42 by author Peter

jQuery AJAX method is a very powerful function for doing asynchronous operations from the Web pages. It helps to update parts of a Web page without reloading the whole page. This increases the Website's speed and reduces the load. It can be used with any Web technology like HTML, ASP.NET, ASP.NET MVC, PHP, Ruby or any other. With jQuery AJAX method, you can create high performance features in our Website. Let me show you how to use this method in  ASP.NET MVC page.

ASP.NET MVC Page
To understand the working of jQuery AJAX, I will create a login feature in ASP.NET MVC page. The page will have 2 input controls to enter the username and the password. There will also be a button to submit the two values for checking from the database.
When the username and password are correct, the secured information of the user is shown, else the “wrong username and password” is shown.
The main attraction here is that I will use jQuery AJAX method to check the username and the password. There will be no page reloading during checking.
To start learning jQuery AJAX method, I would suggest you check – jQuery AJAX. Also, look for the syntax and the key-value pairs that can be passed to this method.

The Controller Code
Start with creating a “Controller” in your ASP.NET MVC Application. Now, add a C# function “GetSecuredData” into the controller.
[HttpPost] 
public string GetSecuredData(string userName, string password) 

    string securedInfo = ""; 
    if ((userName == "admin") && (password == "admin")) 
        securedInfo = "Hello admin, your secured information is ......."; 
    else 
        securedInfo = "Wrong username or password, please retry."; 
    return securedInfo; 
}
 

The C# function given above will be called by jQuery AJAX method. As you can see, this function has 2 parameters, “username” and “password”. In these 2 parameters, it receives the username and the password values. It then checks them and shows the secured information, if they are the correct ones.

You can also change the code given above to include the database operation, where the username and the password are checked against the ones stored in the database.

The View code
Now, create a view for the Controller. This view will contain the two input controls for the username and password. There will be a button, which when clicked will call jQuery AJAX function.
<h3>Enter the Username and Password:</h3> 
(enter "admin" for both username and password) 
<input type="text" id="usernameInput" placeholder="Username" /> 
<input type="text" id="passwordInput" placeholder="Password" /> 
<button id="submit">Submit</button> 
<div id="dataDiv"></div> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> 
<script> 
    $(document).ready(function () { 
        $("#submit").click(function (e) { 
            if ($("#usernameInput").val() == "") 
                alert("Username cannot be empty"); 
            else if ($("#passwordInput").val() == "") 
                alert("Password cannot be empty"); 
            else { 
                $.ajax({ 
                    type: "POST", 
                    url: "/Home/GetSecuredData", 
                    contentType: "application/json; charset=utf-8", 
                    data: '{"userName":"' + $("#usernameInput").val() + '","password":"' + $("#passwordInput").val() + '"}', 
                    dataType: "html", 
                    success: function (result, status, xhr) { 
                        $("#dataDiv").html(result); 
                    }, 
                    error: function (xhr, status, error) { 
                        $("#dataDiv").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText) 
                    } 
                }); 
            } 
            return false; 
        }); 
    }); 
</script> 


The button click event will call jQuery AJAX event. We pass the “controller name/function name” to the URL field. The jQuery AJAX event will call the C# function which gets the username and password values in its parameters.

Finally in the success function we will show the returned value from the C# function.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Use Log4net In ASP.NET MVC Application

clock July 17, 2018 08:30 by author Peter

You may have read several articles on how to use log4net; however,  this article explains how you can use it without having to initialize several times. Log4Net is a framework for implementing logging mechanisms. It is an open source framework. Log4net provides a simple mechanism for logging information to a variety of sources. Information is logged via one or more loggers. These loggers are provided at the below levels of logging:

  • Debug
  • Information
  • Warnings
  • Error
  • Fatal

Now let’s begin with implementation.

Add log4net Package

For this, you need to install log4net from NuGet Package Manager  to your ASP.NET MVC project as per the below screen.

Add Global.asax for loading log4net  configuration
Once installation is done, you need to add the below code in Application_Start() of  Global.asax
log4net.Config.XmlConfigurator.Configure(); 

Add log4net in config file
Now open web.config and enter the following details.
<configSections> 
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" /> 
</configSections> 

<log4net> 
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender"> 
<file value="C:\Temp\nSightsLog.log" /> 
<appendToFile value="true" /> 
<maximumFileSize value="500KB" /> 
<maxSizeRollBackups value="2" /> 
<layout type="log4net.Layout.PatternLayout"> 
  <conversionPattern value="%date %level %logger - %message%newline" /> 
</layout> 
</appender> 
<root> 
<level value="All" /> 
<appender-ref ref="RollingFile" /> 
</root> 
</log4net> 


Implementing in specific file for accessing throughout application
Add a class Log.cs in the Utilities folder.
Now, in the constructor of this class, instantiate logs for monitoring and debugger loggers.
private Log() 

 monitoringLogger = LogManager.GetLogger("MonitoringLogger"); 
 debugLogger = LogManager.GetLogger("DebugLogger"); 


Here, you need to create Debug(), Error(), Info(), Warn(), Fatal() methods which will call respective methods from Log4 net.

Below is a sample.

public class Log 

    private static readonly Log _instance = new Log(); 
    protected ILog monitoringLogger; 
    protected static ILog debugLogger; 

    private Log() 
    { 
        monitoringLogger = LogManager.GetLogger("MonitoringLogger"); 
        debugLogger = LogManager.GetLogger("DebugLogger"); 
    } 



    /// <summary> 
    /// Used to log Debug messages in an explicit Debug Logger 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    public static void Debug(string message) 
    { 
        debugLogger.Debug(message); 
    } 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    /// <param name="exception">The exception to log, including its stack trace </param> 
    public static void Debug(string message, System.Exception exception) 
    { 
        debugLogger.Debug(message, exception); 
    } 


    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    public static void Info(string message) 
    { 
        _instance.monitoringLogger.Info(message); 
    } 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    /// <param name="exception">The exception to log, including its stack trace </param> 
    public static void Info(string message, System.Exception exception) 
    { 
        _instance.monitoringLogger.Info(message, exception); 
    } 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    public static void Warn(string message) 
    { 
        _instance.monitoringLogger.Warn(message); 
    } 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    /// <param name="exception">The exception to log, including its stack trace </param> 
    public static void Warn(string message, System.Exception exception) 
    { 
        _instance.monitoringLogger.Warn(message, exception); 
    } 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    public static void Error(string message) 
    { 
        _instance.monitoringLogger.Error(message); 
    } 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    /// <param name="exception">The exception to log, including its stack trace </param> 
    public static void Error(string message, System.Exception exception) 
    { 
        _instance.monitoringLogger.Error(message, exception); 
    } 


    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    public static void Fatal(string message) 
    { 
        _instance.monitoringLogger.Fatal(message); 
    } 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    /// <param name="exception">The exception to log, including its stack trace </param> 
    public static void Fatal(string message, System.Exception exception) 
    { 
        _instance.monitoringLogger.Fatal(message, exception); 
    } 

     


Now, you need to call the logger class that logs directly into your action method.

public ActionResult Login() 
  { 
      //This is for example , we need to remove this code later 
      Log.Info("Login-page started..."); 

      // Boolean msg = CheckSetupType(); 
      return View(); 
  }  

 



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Database Image Bank In ASP.NET MVC

clock February 2, 2017 08:41 by author Peter

The goal is to use a database to store images and use MVC to call those images, using custom routes. The premises are,
The URL must be something like this: “imagebank/sample-file” or “imagebank/32403404303“.
The MVC Controller/Action will get the image by an ID “sample-file” or “32403404303” and find out on some cache and/or database to display the image. If it exists in cache, get from cache if not get from database. So in HTML, we can call the image like this.

    <img src="~/imagebank/sample-file" />   

If you want to use another URL, for instance “foo/sample-file”, you can change the image bank route name in web.config.
If you do not want to display the image and just download the file, use - “imagebank/sample-file/download“.

So, let's get started!

The image bank route configuration

App_Start\RouteConfig.cs
public class RouteConfig 
    { 
        public static void RegisterRoutes(RouteCollection routes) 
        { 
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
 
            routes.MapRoute( 
                name: "ImageBank", 
                url: GetImageBankRoute() + "/{fileId}/{action}", 
                defaults: new { controller = "ImageBank", action = "Index" } 
            ); 
 
            routes.MapRoute( 
                name: "Default", 
                url: "{controller}/{action}/{id}", 
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
            ); 
        } 
 
        private static string GetImageBankRoute() 
        { 
            var key = "imagebank:routeName"; 
            var config = ConfigurationManager.AppSettings.AllKeys.Contains(key) ? ConfigurationManager.AppSettings.Get(key) : ""; 
 
            return config ?? "imagebank"; 
        } 
    } 


The Image Bank Controller

Controllers\ImageBankController.cs 
public class ImageBankController : Controller 
    { 
        public ImageBankController() 
        { 
            Cache = new Cache(); 
            Repository = new Repository(); 
        } 
         
        public ActionResult Index(string fileId, bool download = false) 
        { 
            var defaultImageNotFound = "pixel.gif"; 
            var defaultImageNotFoundPath = $"~/content/img/{defaultImageNotFound}"; 
            var defaultImageContentType = "image/gif"; 
 
            var cacheKey = string.Format("imagebankfile_{0}", fileId); 
            Models.ImageFile model = null; 
 
            if (Cache.NotExists(cacheKey)) 
            { 
                model = Repository.GetFile(fileId); 
 
                if (model == null) 
                { 
                    if (download) 
                    { 
                        return File(Server.MapPath(defaultImageNotFoundPath), defaultImageContentType, defaultImageNotFound); 
                    } 
 
                    return File(Server.MapPath(defaultImageNotFoundPath), defaultImageContentType); 
                } 
                 
                Cache.Insert(cacheKey, "Default", model); 
            } 
            else 
            { 
                model = Cache.Get(cacheKey) as Models.ImageFile; 
            } 
 
            if (download) 
            { 
                return File(model.Body, model.ContentType, string.Concat(fileId, model.Extension)); 
            } 
 
            return File(model.Body, model.ContentType); 
        } 
 
        public ActionResult Download(string fileId) 
        { 
            return Index(fileId, true); 
        } 
 
        private Repository Repository { get; set; } 
 
        private Cache Cache { get; set; } 
    } 


The above code has two actions - one for displaying the image and the other for downloading it.

The database repository

Repository.cs
public class Repository 
    { 
        public static Models.ImageFile GetFile(string fileId) 
        { 
            //Just an example, use you own data repository and/or database 
            SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ImageBankDatabase"].ConnectionString); 
 
            try 
            { 
                connection.Open(); 
                var sql = @"SELECT *  
                            FROM    dbo.ImageBankFile  
                            WHERE   FileId = @fileId  
                                    OR ISNULL(AliasId, FileId) = @fileId"; 
 
                var command = new SqlCommand(sql, connection); 
                command.Parameters.Add("@fileId", SqlDbType.VarChar).Value = fileId; 
                command.CommandType = CommandType.Text; 
                var ada = new SqlDataAdapter(command); 
                var dts = new DataSet(); 
                ada.Fill(dts); 
 
                var model = new Models.ImageFile(); 
                model.Extension = dts.Tables[0].Rows[0]["Extension"] as string; 
                model.ContentType = dts.Tables[0].Rows[0]["ContentType"] as string; 
                model.Body = dts.Tables[0].Rows[0]["FileBody"] as byte[]; 
 
                return model; 
            } 
            catch  
            { 
 
            } 
            finally 
            { 
                if (connection != null) 
                { 
                    connection.Close(); 
                    connection.Dispose(); 
                    connection = null; 
                } 
            } 
 
            return null; 
        } 
    } 


The repository is very simple. This code is just for demonstration. You can implement your own code. 

The image bank model class

Models\ImageFile.cs
public class ImageFile 
    { 
        public byte[] Body { get; set; } 
 
        public string ContentType { get; set; } 
 
        public string Extension { get; set; } 
    }  

Create table script

USE [ImageBankDatabase] 
GO 
 
/****** Object:  Table [dbo].[ImageBankFile]    Script Date: 11/16/2016 12:36:56 ******/ 
SET ANSI_NULLS ON 
GO 
 
SET QUOTED_IDENTIFIER ON 
GO 
 
SET ANSI_PADDING ON 
GO 
 
CREATE TABLE [dbo].[ImageBankFile]( 
    [FileId] [nvarchar](50) NOT NULL, 
    [AliasId] [nvarchar](100) NULL, 
    [FileBody] [varbinary](max) NULL, 
    [Extension] [nvarchar](5) NULL, 
    [ContentType] [nvarchar](50) NULL, 
 CONSTRAINT [PK_ImageBankFile] PRIMARY KEY CLUSTERED  

    [FileId] ASC 
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY] 
) ON [PRIMARY] 
 
GO 
 
SET ANSI_PADDING OFF 
GO  

The Cache provider class

Cache.cs

public class Cache 
    { 
        public Cache() 
        { 
            _config = ConfigurationManager.GetSection("system.web/caching/outputCacheSettings") as OutputCacheSettingsSection; 
        } 
         
        private OutputCacheSettingsSection _config; 
         
        private OutputCacheProfile GetProfile(string profile) 
        { 
            return !string.IsNullOrEmpty(profile) ? _config.OutputCacheProfiles[profile] : new OutputCacheProfile("default"); 
        } 
         
        private object GetFromCache(string id) 
        { 
            if (string.IsNullOrEmpty(id)) throw new NullReferenceException("id is null"); 
            if (System.Web.HttpRuntime.Cache != null) 
            { 
                lock (this) 
                { 
                    return System.Web.HttpRuntime.Cache[id]; 
                } 
            } 
 
            return null; 
        } 
         
        public Cache Insert(string id, string profile, object obj) 
        { 
            if (System.Web.HttpRuntime.Cache != null) 
            { 
                if (string.IsNullOrEmpty(id)) 
                { 
                    throw new ArgumentNullException("id", "id is null"); 
                } 
 
                if (string.IsNullOrEmpty(profile)) 
                { 
                    throw new ArgumentNullException("profile", string.Format("profile is null for id {0}", id)); 
                } 
 
                var objProfile = GetProfile(profile); 
                if (objProfile == null) 
                { 
                    throw new NullReferenceException(string.Format("profile is null for id {0} and profile {1}", id, profile)); 
                } 
 
                lock (this) 
                { 
                    System.Web.HttpRuntime.Cache.Insert(id, obj, null, DateTime.Now.AddSeconds(objProfile.Duration), TimeSpan.Zero); 
                } 
            } 
 
            return this; 
        } 
         
        public bool NotExists(string id) 
        { 
            return GetFromCache(id) == null; 
        } 
         
        public Cache Remove(string id) 
        { 
            if (System.Web.HttpRuntime.Cache != null) 
            { 
                lock (this) 
                { 
                    System.Web.HttpRuntime.Cache.Remove(id); 
                } 
            } 
 
            return this; 
        } 
         
        public object Get(string id) 
        { 
            return GetFromCache(id); 
        } 
    } 

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 :: Star Rating in MVC Using AngularUI

clock December 7, 2016 10:17 by author Peter

In this tutorial, i will show you how to make a Star Rating in MVC Using AngularUI. You may have seen in many websites, that they ask for feedback in the form of rating stars. No problem --  it very easy to implement. Just follow the below steps to create a StarRating system in your Web Application.

Implementing StarRating in MVC using AngularUI

Create a Web Application using the MVC template (Here, I am using Visual studio 2015).
It is better (Recommended) to implement an Application in Visual studio 2015 because VS2015 shows intelligence for Angular JS. This feature is not present in the previous versions.

And here is the final output:

 

1. Add Controller and View
Add a controller and name it (Here, I named it HomeController).
Create an Index Action method and add view to it.
Now, add the script ,given below, and reference file to an Index page.
    <script src="~/Scripts/angular.js"></script> 
        <script src="~/Scripts/angular-animate.js"></script> 
        <script src="~/Scripts/angular-ui/ui-bootstrap-tpls.js"></script> 
        <script src="~/Scripts/app.js"></script><!--This is application script we wrote--> 
        <link href="~/Content/bootstrap.css" rel="stylesheet" /> 


2. Add Angular Script file
Now, create another script file for Angular code to implement StarRating in the Application.
Replace the Java Script file, with the code, given below:
    angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap']); 
    angular.module('ui.bootstrap.demo').controller('RatingDemoCtrl', function ($scope) { 
        //These are properties of the Rating object 
        $scope.rate = 7;    //gets or sets the rating value 
        $scope.max = 10;    //displays number of icons(stars) to show in UI 
        $scope.isReadonly = false;  //prevents the user interaction if set to true. 
        $scope.hoveringOver = function (value) { 
            $scope.overStar = value; 
            $scope.percent = 100 * (value / $scope.max); 
        }; 
        //Below are the rating states 
        //These are array of objects defining properties for all icons.  
        //In default template below 'stateOn&stateOff' properties are used to specify icon's class. 
        $scope.ratingStates = [ 
          { stateOn: 'glyphicon-ok-sign', stateOff: 'glyphicon-ok-circle' }, 
          { stateOn: 'glyphicon-star', stateOff: 'glyphicon-star-empty' }, 
          { stateOn: 'glyphicon-heart', stateOff: 'glyphicon-ban-circle' }, 
          { stateOn: 'glyphicon-heart' }, 
          { stateOff: 'glyphicon-off' } 
        ]; 
    }); 


3. Create UI
Replace and add the code, given below, in the Index.cshtml page.
    @{ 
        Layout = null; 
    } 
    <h2>Star Rating in Angualr UI</h2> 
    <!doctype html> 
    <html ng-app="ui.bootstrap.demo"> 
    <head>    
        <title>www.mitechdev.com</title> 
        <script src="~/Scripts/angular.js"></script> 
        <script src="~/Scripts/angular-animate.js"></script> 
        <script src="~/Scripts/angular-ui/ui-bootstrap-tpls.js"></script> 
        <script src="~/Scripts/app.js"></script><!--This is application script we wrote--> 
        <link href="~/Content/bootstrap.css" rel="stylesheet" /> 
    </head> 
    <body style="margin-left:30px;"> 
        <div ng-controller="RatingDemoCtrl"> 
            <!--Angular element that shows rating images--> 
            <uib-rating ng-model="rate" max="max" 
                        read-only="isReadonly"  
                        on-hover="hoveringOver(value)" 
                        on-leave="overStar = null" 
                        titles="['one','two','three']"  
                        aria-labelledby="default-rating"> 
            </uib-rating> 
            <!--span element shows the percentage of select--> 
            <span class="label" ng-class="{'label-warning': percent<30, 'label-info': percent>=30 && percent<70, 'label-success': percent>=70}" 
                  ng-show="overStar && !isReadonly">{{percent}}%</span> 
            <!--This element shows rating selected,Hovering and IS hovering or not(true/false)--> 
            <pre style="margin:15px 0;width:400px;">Rate: <b>{{rate}}</b> - Readonly is: <i>{{isReadonly}}</i> - Hovering over: <b>{{overStar || "none"}}</b></pre> 
            <!--button clears all the values in above <pre> tag--> 
            <button type="button" class="btn btn-sm btn-danger" ng-click="rate = 0" ng-disabled="isReadonly">Clear</button> 
            <!--this button toggles the selection of star rating--> 
            <button type="button" class="btn btn-sm btn-default" ng-click="isReadonly = ! isReadonly">Toggle Readonly</button> 
            <hr /> 
            <div>Mitechdev.com Application-2016</div> 
        </div> 
    </body> 

    </html>


Here, we need to talk about some expressions used in <uib-rating> tag.

  •     on-hover: This expression is called, when the user places the mouse at the particular icon. In the above code hoveringOver() is called.
  •     on-leave: This expression is called when the user leaves the mouse at the particular icon.
  •     titles: Using this expression, we can assign an array of the titles to each icon.

 

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 :: Using Filters and Attribute Class In ASP.NET MVC

clock November 22, 2016 07:26 by author Peter

In this post, I will explain you about using filters and attribute class in ASP.NET MVC. ASP.NET MVC provides an easy way to inject your piece of code or logic either before or after an action is executed. this will be achieved by using filters and attribute classes.

Types of Filters
The ASP.NET MVC framework provides five types of filters and executes in the same order as given below,

    Authentication filters
    Authorization filters
    Action filters
    Result filters
    Exception filters

Build an action method in HomeController and declare Attribute classes Above Action Method.
    public class HomeController: Controller 
     
    { 
        [CustomAuthorizationAttribute] 
        [CustomActionAttribute] 
        [CustomResultAttribute] 
        [CustomExceptionAttribute] 
     
        public ActionResult Index()  
        { 
     
            ViewBag.Message = "Index Action of Home controller is being called."; 
            return View(); 
        } 
    } 

Now, build a Filters Folder in your application and add the following attribute classes.

    CustomAuthorizationAttribute.cs
        public class CustomAuthorizationAttribute: FilterAttribute, IAuthorizationFilter 
         
        { 
            void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)  
            { 
                filterContext.Controller.ViewBag.OnAuthorization = "IAuthorizationFilter.OnAuthorization filter called"; 
            } 
        } 
    CustomActionAttribute.cs
        public class CustomActionAttribute: FilterAttribute, IActionFilter  
        { 
            void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)  
            { 
                filterContext.Controller.ViewBag.OnActionExecuting = "IActionFilter.OnActionExecuting filter called"; 
            } 
            void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)  
            { 
                filterContext.Controller.ViewBag.OnActionExecuted = "IActionFilter.OnActionExecuted filter called"; 
            } 
        }
    CustomResultAttribute.cs
        public class CustomResultAttribute: FilterAttribute, IResultFilter 
        { 
            void IResultFilter.OnResultExecuting(ResultExecutingContext filterContext)  
            { 
                filterContext.Controller.ViewBag.OnResultExecuting = "IResultFilter.OnResultExecuting filter called"; 
            } 
            void IResultFilter.OnResultExecuted(ResultExecutedContext filterContext)  
            { 
                filterContext.Controller.ViewBag.OnResultExecuted = "IResultFilter.OnResultExecuted filter called"; 
            } 
        } 
    CustomExceptionAttribute.cs
        public class CustomExceptionAttribute: FilterAttribute, IExceptionFilter  
        { 
            void IExceptionFilter.OnException(ExceptionContext filterContext)  
            { 
                filterContext.Controller.ViewBag.OnException = "IExceptionFilter.OnException filter called"; 
            } 
        } 


View
Index.cshtml
    @{ 
    ViewBag.Title = "Index"; 
    } 
    <h2> 
    Index</h2> 
    <ul> 
    <li>@ViewBag.OnAuthorization</li> 
    <li>@ViewBag.OnActionExecuting</li> 
    <li>@ViewBag.OnActionExecuted</li> 
    <li>@ViewBag.OnResultExecuting</li> 
    <li>@ViewBag.OnResultExecuted</li> 
    <li>@ViewBag.Message</li> 
    </ul> 


The following image is the 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 Hosting - HostForLIFE.eu :: Configuring ELMAH In ASP.NET MVC

clock June 13, 2016 21:35 by author Anthony

In this article, I will integrate and setup ELMAH to asp.net MVC project. I will finish whole article in 5 different steps. ELMAH stands for Error Logging Modules and Handlers providing application wide error logging facilities. ELMAH is pluggable and easy to implement without changing single line of code. ELMAH work as interceptor of unhandled dotnet exceptions, that display over yellow screen of death. As per Author you can dynamically add ELMAH on running asp.net application without recompile or re-deploy whole application.You can download ELMAH binaries from google code or if you are using nuget then visit ELMAH nuget page.

Install

The best way to install any module to Asp.net MVC project is to use Nuget package Console. You can visit ELMAH nuget page for get latest version command.

Configure

After installing ELMAH , it will automatically update Web.Config file. If it's not so you can add following code to Web.Config file.

<configuration>
<configSections>
    <sectionGroup name="elmah">
      <section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah" />
      <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" />
      <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" />
      <section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah" />
    </sectionGroup>
</configSections>

<system.web>   
    <httpModules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
    </httpModules>
</system.web>

<system.webServer>
<modules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" />
</modules>
</system.webServer>
<elmah>
    <security allowRemoteAccess="false" />
    <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="YourConnectionStringName" />
</elmah>
    <location path="elmah.axd" inheritInChildApplications="false">
    <system.web>
      <httpHandlers>
        <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
      </httpHandlers>
      <!--
      <authorization>
        <allow roles="admin" />
        <deny users="*" /> 
      </authorization>
      --> 
    </system.web>
    <system.webServer>
      <handlers>
        <add name="ELMAH" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode" />
      </handlers>
    </system.webServer>
  </location>
</configuration>
Usage Now, It's time to use and test elmah for application. Generate exception in Home Controller
public ActionResult Index()
{
   throw new Exception("This is test Exception");
          
   return View();
}


after generating exception check your elmah like http://www.example.com/elmah.axd
Here is our output

integrate-elmah-in-aspnet-mvc

integrate elmah in asp. net mvc

Security

In addition ELMAH provides seamless security feature to prevent unauthorized access. Please read our next article to make your elmah secure.

Filtering

ELMAH identify and store exceptions in different category, you can make or edit ELMAH error screen with different filters which we will discuss in our next ELMAH series.

Notification

You can setup ELMAH email notification when any exception occurs. To unable notification option you must include below code

Add ErrorMail module
<httpModules>
    <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah"/>
</httpModules>


Add SMTP Setting
<system.net>
    <mailSettings>
        <smtp deliveryMethod="network">
            <network host="..." port="25" userName="..." password="..." />
        </smtp>
    </mailSettings>
</system.net>
 

or
<elmah>
<errorMail from="..." to="..."  async="true" smtpServer="..." smtpPort="25" userName="..." password="..." />
</elmah>

 

 


HostForLIFE.eu ASP.NET MVC 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 Hosting - HostForLIFE.eu :: How To Make Simple Application In ASP.NET MVC Using Select2?

clock June 6, 2016 23:46 by author Anthony

In this tutorial, I will show you how to make simple application in ASP.NET MVC using Select2. The infinite scrolling feature has also been implemented with server side options population. Select2 is very useful for dropdown lists with large datasets.

Why Select2 :

  • Using this jQuery plugin for dropdown lists, you can implement features such as option grouping, searching, infinite scrolling, tagging, remote data sets and other highly used features.
  • To use select2 in web projects, you just have to include JavaScript and CSS files of Select2 in your website.
  • Current version of select2 is 4.0.0. You can easily include these files by installation of NuGet package ‘Select2.js’ from NuGet package manager.

Steps of Implementation:
1. Create a blank ASP.NET MVC project, and install NuGet packages Select2.js, jQuery and jQuery Unobtrusive.
2. Add one controller with the name ‘HomeController’ and add view for default method ‘Index’.
3. Create new class in Models folder ‘IndexViewModel.cs as shown below:

public class IndexViewModel
{
   [Required(ErrorMessage="Please select any option")]
   public string OptionId { get; set; }
}

4. Bind ‘Index.cshtml’ view with IndexViewModelClass as model, by adding the following line in Index view:

@model Select2InMvcProject.Models.IndexViewModel

5. In ‘Index.cshtml’, include the css and js files below:

<link href="~/Content/css/select2.css" rel="stylesheet" />
<script src="~/Scripts/jquery-2.1.4.js"></script>
<script src="~/Scripts/select2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>


6. Write the following code in the Index view for creation of select list:

@using (Html.BeginForm())
{
   <br /><br />
   @Html.DropDownListFor(n => n.OptionId, Enumerable.Empty<SelectListItem>(), new { @id = "txtOptionId", @style = "width:300px;" })
//Created selectlist with empty enumerable of SelectListItem and given //id as “txtOptionId”
   @Html.ValidationMessageFor(n => n.OptionId)
//Adds span of validation error message
   <br /><br />
<button type="submit">Submit</button>
   <br /><br />
}


7. For applying Select2 to the dropdown list created above, fetching data from server side and for infinite scroll, use the jQuery code below in Index view:

<script type="text/javascript">
   $(document).ready(function () {
       var pageSize = 20;
       var optionListUrl = '@Url.Action("GetOptionList", "Home")';
//Method which is to be called for populating options in dropdown //dynamically
       $('#txtOptionId').select2(
       {
           ajax: {
               delay: 150,
               url: optionListUrl,
               dataType: 'json',
               data: function (params) {
                   params.page = params.page || 1;
                   return {
                       searchTerm: params.term,
                       pageSize: pageSize,
                       pageNumber: params.page
                   };
               },
               processResults: function (data, params) {
                   params.page = params.page || 1;
                  return {
                       results: data.Results,
                       pagination: {
                           more: (params.page * pageSize) < data.Total
                       }
                   };
               }
           },
           placeholder: "-- Select --",
           minimumInputLength: 0,
           allowClear: true,
   });
});
</script>


8. Create new class in Models folder with name ‘Select2OptionModel’ and add the two classes below:

public class Select2OptionModel
{
       public string id { get; set; }
       public string text { get; set; }
}
public class Select2PagedResult
{
       public int Total { get; set; }
       public List<Select2OptionModel> Results { get; set; }
}


9. Create one new folder with name ‘Repository’ in the solution, and add new class in that folder with name ‘Select2Repository. The functions in this class are mentioned below:

public class Select2Repository
   {
       IQueryable<Select2OptionModel> AllOptionsList;
public Select2Repository()
{
           AllOptionsList = GetSelect2Options();
}
IQueryable<Select2OptionModel> GetSelect2Options()
                  {
                                     string cacheKey = "Select2Options";
                                     //check cache
                                     if (HttpContext.Current.Cache[cacheKey] != null)
                                     {
return (IQueryable<Select2OptionModel>)HttpContext.Current.Cache[cacheKey];
                                     }
                                     var optionList = new List<Select2OptionModel>();
                                     var optionText = "Option Number ";
                                     for (int i = 1; i < 1000; i++)
                                     {
                                     optionList.Add(new Select2OptionModel
                                     {
                                               id = i.ToString(),
                                               text = optionText + i
                                     });
                                   }
                                   var result = optionList.AsQueryable();
                                     //cache results
                                     HttpContext.Current.Cache[cacheKey] = result;
                                     return result;}
 
List<Select2OptionModel> GetPagedListOptions(string searchTerm, int pageSize, int pageNumber, out int totalSearchRecords)
                  {
                                     var allSearchedResults = GetAllSearchResults(searchTerm);
                                     totalSearchRecords = allSearchedResults.Count;
return allSearchedResults.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList();
                  }
                  List<Select2OptionModel> GetAllSearchResults(string searchTerm)
                  {

                                     var resultList = new List<Select2OptionModel>();
                                      if (!string.IsNullOrEmpty(searchTerm))
resultList = AllOptionsList.Where(n => n.text.ToLower().Contains(searchTerm.ToLower())).ToList();
                                     else
                                     resultList = AllOptionsList.ToList();
                                     return resultList;
                  }
                  public Select2PagedResult GetSelect2PagedResult(string searchTerm, int pageSize, int pageNumber)
                  {
                                     var select2pagedResult = new Select2PagedResult();
                                     var totalResults = 0;
                                     select2pagedResult.Results = GetPagedListOptions(searchTerm,
pageSize, pageNumber, out totalResults);
                                     select2pagedResult.Total = totalResults;
                                     return select2pagedResult;
}
}

10.  In HomeController class, create new method as shown below:

public JsonResult GetOptionList(string searchTerm, int pageSize, int pageNumber)
{
     var select2Repository = new Select2Repository();
     var result = select2Repository.GetSelect2PagedResult(searchTerm, pageSize, pageNumber);
     return Json(result, JsonRequestBehavior.AllowGet);
}

11. Once you are done with coding, you can build and run the project. The output will be shown as below:

dropdown1.png

dropdown2.png


HostForLIFE.eu ASP.NET MVC 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 Create Google Maps Sample App ASP.NET MVC And AngularJS

clock May 30, 2016 21:03 by author Anthony

Today I am going to explain how to create Google Maps Sample App with AngularJS and asp.net MVC. In one of the previous article, we have seen How to display google map in asp.net application andHow to load GMap Direction from database in ASP.NET using google map.

In order to use the Google Maps in our application, we need to add the following resources: 

  • angular.js
  • lodash.js - Loadash is a dependency of angular-google-maps library.
  • angular-google-maps.js - Angular Google Maps is a set of directives which integrate Google Maps in an AngularJS applications.

Just follow the following steps in order to create a sample google app with AngularJS and asp.net MVC:

Step - 1: Create New Project.

Go to File > New > Project > Select asp.net MVC4 web application > Entry Application Name > Click OK > Select Basic > Select view engine Razor > OK 

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add. Here I have added a database for store some location information in our database for show in the google map.  

Step-3: Create a table.

Here I will create 1 table (as below) for store location information. Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok. 

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add. A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next > Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish. 

Step-5: Create a Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add. Here I have created a controller "HomeController" 

Step-6: Add new action into the controller to get the view where we will show google map

Here I have added "Index" Action into "Home" Controller. Please write this following code 

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

Step-7: Add another action (here "GetAllLocation") for fetch all the location from the database.

public JsonResult GetAllLocation()
{   
using (MyDatabaseEntities dc = new MyDatabaseEntities())   
{       
var v = dc.Locations.OrderBy(a => a.Title).ToList();      
return new JsonResult { Data = v, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}

Step-8: Add 1 more action (here "GetMarkerInfo") for getting google marker information from the database to show in the map.

public JsonResult GetMarkerInfo(int locationID)
{    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {        Location l = null;
        l = dc.Locations.Where(a => a.LocationID.Equals(locationID)).FirstOrDefault();
        return new JsonResult { Data = l, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}

Step-9: Add a new javascript file, will contain all the necessary logic to implement our Google Map.

Right Click on Action Method (here right click on Index action) > Add View... > Enter View Name > Select View Engine (Razor) > Add. 

var app = angular.module('myApp', ['uiGmapgoogle-maps']);
app.controller('mapController', function ($scope, $http) {
     //this is for default map focus when load first time
    $scope.map = { center: { latitude: 22.590406, longitude: 88.366034 }, zoom: 16 }
     $scope.markers = [];
    $scope.locations = [];
    //Populate all location
    $http.get('/home/GetAllLocation').then(function (data) {
        $scope.locations = data.data;
    }, function () {
        alert('Error');
    });
    //get marker info
    $scope.ShowLocation = function (locationID) {
        $http.get('/home/GetMarkerInfo', {
            params: {
                locationID: locationID
            }
        }).then(function (data) {
            //clear markers
            $scope.markers = [];
            $scope.markers.push({
                id: data.data.LocationID,
                coords: { latitude: data.data.Lat, longitude: data.data.Long },
                title: data.data.title,               
                address: data.data.Address,                               
                image : data.data.ImagePath           
});
            //set map focus to center
            $scope.map.center.latitude = data.data.Lat;
            $scope.map.center.longitude = data.data.Long;
        }, function () {
            alert('Error');
        });
    }
    //Show / Hide marker on map
    $scope.windowOptions = {
        show: true
    };
}); 

Step-10: Add view for the action (here "Index") & design.

Right Click on Action Method (here right click on Index action) > Add View... > Enter View Name > Select View Engine (Razor) > Add. HTML Code 

@{    ViewBag.Title = "Index";
}
<h2>Index</h2>
<div ng-app="myApp" ng-controller="mapController">
    <div class="locations">
        <ul>
            <li ng-repeat="l in locations" ng-click="ShowLocation(l.LocationID)">{{l.Title}}</li>
        </ul>
    </div>
    <div class="maps">
        <!-- Add directive code (gmap directive) for show map and markers-->
        <ui-gmap-google-map center="map.center" zoom="map.zoom">
            <ui-gmap-marker ng-repeat="marker in markers" coords="marker.coords" options="marker.options" events="marker.events" idkey="marker.id">
                <ui-gmap-window options="windowOptions" show="windowOptions.show">
                    <div style="max-width:200px">
                        <div class="header"><strong>{{marker.title}}</strong></div>
                        <div id="mapcontent">
                            <p>
                                <img ng-src="{{marker.image}}" style="width:200px; height:100px" />
                                <div>{{marker.address}}</div>
                            </p>
                        </div>
                    </div>
                </ui-gmap-window>
            </ui-gmap-marker>
        </ui-gmap-google-map>
    </div>
</div>
@* Now here we need to some css and js *@
<style>
    .angular-google-map-container {
        height:300px;
    }
    .angular-google-map {
        width:80%;
        height:100%;
        margin:auto 0px;
    }
    .locations {
        width: 200px;
        float: left;
    }
    .locations ul {
        padding: 0px;
        margin: 0px;
        margin-right: 20px;
    }
    .locations ul li {
        list-style-type: none;
        padding: 5px;
        border-bottom: 1px solid #f3f3f3;
        cursor: pointer;
    }
</style>
@section Scripts{
    @* AngularJS library *@
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.js"></script>
    @* google map directive js *@
    <script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>
    <script src="//rawgit.com/angular-ui/angular-google-maps/2.0.X/dist/angular-google-maps.js"></script>
    @* here We will add our created js file *@
    <script src="~/Scripts/ngMap.js"></script>
}

Step-11: Run Application.


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 Make ASP.NET MVC 6 View Injection?

clock May 5, 2016 00:10 by author Anthony

ASP.NET MVC 6, a new feature called view components has been introduced. View components are similar to child actions and partials views, allowing you to create reusable components with (or without) logic. Here's the summary from the ASP.NET documentation:


View components include the same separation-of-concerns and testability benefits found between a controller and view. You can think of a view component as a mini-controller—it’s responsible for rendering a chunk rather than a whole response. You can use view components to solve any problem that you feel is too complex with a partial.


Before ASP.NET Core, you would've probably used a child action to create a reusable component that requires some code for its logic. ASP.NET MVC 6, however, doesn't have child actions anymore. You can now choose between a partial view or a view component, depending on the requirements for the feature you're implementing.

Writing A Simple View Component

Let's implement a simple dynamic navigation menu as a view component. We want to be able to display different navigation items based on some conditional logic (e.g. the user's claims or the hosting environment). Like controllers, view components must be public, non-nested, and non-abstract classes that either

  • derive from the ViewComponent class,
  • are decorated with the [ViewComponent] attribute, or
  • have a name that ends with the "ViewComponent" suffix.

We'll choose the base class approach because ViewComponent provides a bunch of helper methods that we'll be calling to return and render a chunk of HTML.


ASP.NET MVC 6 Dependency Injection using a simple container that is bundled with ASP.NET MVC 6. This is great for injecting dependencies into controllers, filters, etc. In this tutorial I mention the new inject keyword that can be added to razor views for injecting dependencies into views.


Registering Service

First, we have to register the service with the IoC container built into ASP.NET MVC 6.

public void ConfigureServices(IServiceCollection services) {
    ...
    services.AddTransient<ITestService, TestService>();
}

This is no different from the previous example: ASP.NET MVC 6 Dependency Injection.

Inject Keyword for Razor Views


Next we can inject the the service for use in the razor view using the new inject keyword.

@inject ITestService testService


Now the service is available to our view and can be used appropriately anywhere in the view.

@using Sample.Services
@inject ITestService testService
<p>So I looked down and said... @testService.WhatAreThose()</p>

Conclusion

Injecting dependencies in ASP.NET MVC 6 views using the new inject keyword can make things quite a bit easier. Now that ASP.NET MVC 6 has a basic IoC container we'll probably see more people start to use dependency injection not only in their views, but also in their controllers, filters, services, etc.




ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Get Started With React Using TypeScript and ASP.NET MVC 6?

clock April 4, 2016 20:18 by author Anthony

All of the major frameworks (Web API, forms, and MVC) have been rolled out under the umbrella of a single unified programming model. There’s a new built-in dependency framework, and there are Tag Helpers. All this has had a major impact on development. A lot has changed in the world of ASP.NET 5 and MVC 6. But In this tutorial, I will explain about how to get started with React using TypeScript and ASP.NET 5 MVC 6.

But before we start, there are few things you will need to install :

  • Microsoft Visual Studio 2015 (Community Edition is free and it’s open source!)
  • TypeScript (included in VS2015)
  • Node.js and NPM (included in VS2015


    Deprecated, use Typings:
  • Typings. Run npm install typings -g to install globally.
  • Webpack. Run npm install webpack -g to install globally.

 

Create a New ASP.NET MVC 6 Project

First create a new ASP.NET Web Application project. In the next dialog choose Empty template under ASP.NET 5 Templates. This is to keep things simple and we will only be adding add the stuff we actually need.

Install ReactJS.NET

Next you’ll need to modify your project.json file so open it up. To work with React in .NET we’ll be using a library called ReactJS.NET. It will allow you to do server side (or isomorphic) rendering which is cool but more on that later.

Before installing ReactJS.NET we’ll need to remove "dnxcore50": { } line from project.json to make it work. Then add "React.AspNet": "2.1.2" and "Microsoft.AspNet.Mvc": "6.0.0-rc1-final" under dependencies and save the file. Both ASP.NET MVC 6 and ReactJS.NET should get immediately installed.

Your project.json should now look something like this:

{
  "version": "1.0.0-*",
  "compilationOptions": {
    "emitEntryPoint": true
  },

  "dependencies": {
    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
    "React.AspNet": "2.1.2"
  },

  "commands": {
    "web": "Microsoft.AspNet.Server.Kestrel"
  },

  "frameworks": {
    "dnx451": { }
  },

  "exclude": [
    "wwwroot",
    "node_modules"
  ],
  "publishExclude": [
    "**.user",
    "**.vspscc"
  ]
}


Create a new folder called app under your project. This is where we’ll be hosting all our React components. Right-click that folder and add a new item. Search for a TypeScript JSX file template and name your file HelloWorld.tsx. Add the following lines.

/// <reference path="../../../typings/main/ambient/react/index.d.ts" />
import React = require('react');

// A '.tsx' file enables JSX support in the TypeScript compiler,
// for more information see the following page on the TypeScript wiki:
// https://github.com/Microsoft/TypeScript/wiki/JSX

interface HelloWorldProps extends React.Props<any> {
    name: string;
}

class HelloMessage extends React.Component<HelloWorldProps, {}> {
    render() {
        return <div>Hello {this.props.name}</div>;
    }
}
export = HelloMessage;

You’ll see that the react.d.ts cannot be resolved. To fix this you’ll need to run typings install react --ambient --save in the Package Manager console to install the TypeScript definitions for react. Visual Studio will still complain about the --module flag that must be provied. To fix this add a tsconfig.json in the app folder with the following content:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "jsx": "preserve"
  }
}

Note : If the JSX isn’t being generated make sure that you have enabled TypeScript compilation in Visual Studio. To do this check the Automatically compile TypeScript files which are not part of the project under Tools -> Options -> TypeScript -> Project -> General in Visual Studio.

 

Set Up Web Pack

We’ll be using Webpack although you could use any other module bundler as well. You should have installed Webpack already but if you haven’t check out the beginning of this post on how to do it.

In the app folder create index.js:

module.exports = {
    // All the components you'd like to render server-side
    HelloMessage: require('./HelloWorld')
};

This will be used to tell Webpack which components to bundle together for server and client side rendering. Right now we only have the HelloWorld component.

Next in your wwwroot folder add two files called client.js and server.js. They both share the same content for this project:


// All JavaScript in here will be loaded client/server -side.
// Expose components globally so ReactJS.NET can use them
var Components = require('expose?Components!./../app');

The last thing that’s left is a Webpack configuration file. Create webpack.config.js under your project:

var path = require('path');
module.exports = {
    context: path.join(__dirname, 'wwwroot'),
    entry: {
        server: './server',
        client: './client'
    },
    output: {
        path: path.join(__dirname, 'wwwroot/build'),
        filename: '[name].bundle.js'
    },
    module: {
        loaders: [
            // Transform JSX in .jsx files
            { test: /\.jsx$/, loader: 'jsx-loader?harmony' }
        ],
    },
    resolve: {
        // Allow require('./blah') to require blah.jsx
        extensions: ['', '.js', '.jsx']
    },
    externals: {
        // Use external version of React (from CDN for client-side, or
        // bundled with ReactJS.NET for server-side)
        react: 'React'
    }
};


Webpack will need some additional modules to do the bundling. Right-click the project and select “Add item”. In the dialog choose NPM Configuration file and name it package.json:

{
    "version": "1.0.0",
    "name": "ASP.NET",
    "private": true,
    "devDependencies": {
        "webpack": "1.12.9",
        "expose-loader": "0.7.1",
        "jsx-loader": "0.13.2"
    }
}


Once again saving the file will execute NPM and install the three packages.

Finally open command prompt and browse to the project’s folder (where webpack.config.js is located). Then type webpack, press enter and Webpack should beautifully build two JavaScript bundles under wwwroot/build. Of these client.bundle.js should be included client side and server.bundle.js should be included server side. Remember to run webpack each time you have modified your React components or add this step to your build process.

Add a controller and a view

Next, do the obvious thing of creating a controller and a view so that we can host our fancy React component somewhere. Create a folder called Controllers under the project and add a new controller called HomeController under the folder. The controller should have only one GET Index method like so:

using Microsoft.AspNet.Mvc;
namespace React.MVC6.Sample.Controllers
{
    public class HomeController : Controller
    {
        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }
    }
}

After that add a folder called Views under the project. Under Views add a new folder called Shared. Create a layout file called _Layout.cshtml there with the following content:

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <div>
        @RenderBody()
    </div>
</body>
</html>

Then add a few defaults for our views. In the Views folder add a new file called _ViewImports.cshtml with just the following content. This will ensure that ReactJS.NET is by default available in all our views.

@using React.AspNet


Create another file called _ViewStart.cshtml under Views folder with this content:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Finally create a new folder called Home under Views and create a file called Index.cshtml in there. Place the following in there to render your React component with initial data:

@{
    ViewBag.Title = "Index";
}

<h1>Hello World</h1>

@Html.React("Components.HelloMessage", new { name = "Sam" })

<script src="https://fb.me/react-0.14.0.min.js"></script>
<script src="https://fb.me/react-dom-0.14.0.min.js"></script>
<script src="@Url.Content("/build/client.bundle.js")"></script>

@Html.ReactInitJavaScript()

Including the javascripts in the view like this isn’t very pretty but you’ll get the idea. The name that we pass to the component could as well come from a model passed down from the controller.

Configure the Web Application

Then we will need to make sure that ASP.NET MVC 6 and React get loaded properly when the application starts up. So open up your startup.cs file and replace the contents with this:

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.StaticFiles;
using Microsoft.Extensions.DependencyInjection;
using React.AspNet;

namespace React.MVC6.Sample
{
    public class Startup
    {
        // Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddReact(); // Add React to the IoC container
            services.AddMvc();
        }

        // Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app)
        {
            app.UseIISPlatformHandler();

            // Initialise ReactJS.NET. Must be before static files.
            app.UseReact(config =>
            {
                config
                    .SetReuseJavaScriptEngines(true)
                    .AddScriptWithoutTransform("~/build/server.bundle.js");
            });

            app.UseStaticFiles(new StaticFileOptions
            {
                ServeUnknownFileTypes = true
            });

            app.UseMvc(r =>
            {
                r.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" }
                );
            });
        }

        // Entry point for the application.
        public static void Main(string[] args) => WebApplication.Run<Startup>(args);
    }
}

 

HostForLIFE.eu ASP.NET MVC 6 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.



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