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 5 Hosting - HostForLIFE.eu :: Friendly Errors In MVC 5

clock July 20, 2018 08:51 by author Peter

In this article, I will be explaining 3 different ways to handle exceptions and display a friendly error page to the end user. Friendly Error Pages are the pages that you design to show the end user when any kind of not handled exception happens in your application and your expected result is not achieved. So, instead of presenting your end user with technical information regarding the exception, you show him a friend page. Also, presenting your end user with technical information is not a security best practice.

So, let's see the three ways.

Method 1: Custom Exception Filter
Custom Exception Filter

It is a filter that is called every time an exception occurs in the applied methods.

Why would I use a custom exception filter?


Because with a custom exception filter, you can handle in a generic way every kind of exception thrown by your actions and/or controllers. You may use custom exception filters to log your exceptions.

Steps to achieve this:
Step 1

Create a new class named CustomExceptionFilter.
public class CustomExceptionFilter : FilterAttribute, IExceptionFilter   
{   
    public void OnException( ExceptionContext filterContext )   
    {   
        filterContext.Result = new RedirectResult( "Home/About" );   
        filterContext.ExceptionHandled = true;   
    }   
}   

What this custom exception does is to redirect to your About action in your Home Controller. Do not forget to set the ExceptionHandled equal to true; otherwise it will not take effect.

Step 2
Apply your custom exception filter to your controller/action.
public class HomeController : Controller 

    [CustomExceptionFilter] 
    public ActionResult Index() 
    { 
        throw new Exception(); 
        return View(); 
    } 
 
    public ActionResult About() 
    { 
        ViewBag.Message = "Your application thrown an exception"; 
 
        return View(); 
    } 
 
    public ActionResult Contact() 
    { 
        ViewBag.Message = "Your contact page."; 
        throw new Exception(); 
        return View(); 
    } 


You can see that the exception filter is applied only to your Index Action so if you access your Contact action, you will be able to see the non-handled exception page.

Method 2: Web.Config configuration
Why would I handle an exception by web.config configuration?

It is easy to configure and useful when you do not need to log or work on the exception.

Steps to achieve this:

Step 1
Include this in your web.config inside the system.web tag.
<customErrors defaultRedirect="Error.cshtml" mode="On"></customErrors> 

Step 2
Update your Controller.
public class HomeController : Controller 

    [HandleError] 
    public ActionResult Index() 
    { 
        throw new Exception(); 
        return View(); 
    } 
 
    public ActionResult About() 
    { 
        ViewBag.Message = "Your application description page."; 
 
        return View(); 
    } 
 
    public ActionResult Contact() 
    { 
        ViewBag.Message = "Your contact page."; 
        throw new Exception();
        return View(); 
    } 


Observation - Like the custom exception filter, you may choose if you want to handle the exceptions at the Controller or Action level. Also, here, the handled exception is applied only to your Index action, you may see the non-handled error in the Contact View.

Method 3: Global.Asax Application_error
What is the Application_error?

It is to override the global exception handler of the application.

Why would I handle an exception by global.asax Application_error?
You do not need to set the places that you would like to handle the errors like before where you had to set the actions and controllers to be handled. Here, every exception will hit and be handled.

Steps to Achieve this:

Step 1
Update  your global.asax.
protected void Application_Error( object sender, EventArgs e ) 
  { 
      Exception exception = Server.GetLastError(); 
      Server.ClearError(); 
      Response.Redirect( "/Home/About" ); 
  } 


Like the custom exception handlers, it is very important to ClearError() in the Server. What is done here is the redirection of non-handled exceptions to the About action in the Home Controller. Congratulation, you just learned three good ways of handling exceptions in your application and presenting friendly error pages to your end users.



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 5 Hosting - HostForLIFE.eu :: List Of Users With Roles In ASP.NET MVC Identity

clock July 13, 2018 11:21 by author Peter

In this article, we will learn how to list all users with Associated Roles in ASP.NET MVC 5 using Identity. ASP.NET MVC 5 does not come with an inbuilt feature to list users with associated roles by default. However ASP.NET MVC have inbuilt UserManager, SignManager and RoleManager to assist this.

We need this feature in each of our applications as users are to be maintained along with their associated roles. We can apply a number of ideas to do this. In this article, we will learn a very simple way to list users with their associated RoleName as in the figure below.

Step 1
Create a View Model as Users-in-Role_ViewModel
public class Users_in_Role_ViewModel 
    { 
        public string UserId { get; set; } 
        public string Username { get; set; } 
        public string Email { get; set; } 
        public string Role { get; set; } 
    } 


Step 2
Add a new method called UsersWithRoles inside ManageUsersController and add the following codes.
public ActionResult UsersWithRoles() 
        { 
            var usersWithRoles = (from user in context.Users 
                                  select new 
                                  { 
                                      UserId = user.Id,                                       
                                      Username = user.UserName, 
                                      Email = user.Email, 
                                      RoleNames = (from userRole in user.Roles 
                                                   join role in context.Roles on userRole.RoleId  
                                                   equals role.Id 
                                                   select role.Name).ToList() 
                                  }).ToList().Select(p => new Users_in_Role_ViewModel() 
  
                                  { 
                                      UserId = p.UserId, 
                                      Username = p.Username, 
                                      Email = p.Email, 
                                      Role = string.Join(",", p.RoleNames) 
                                  }); 
  
  
            return View(usersWithRoles); 
        } 


Note - context.Users represents the table AspNetUsers which has navigation property roles which represent the AspNetUserInRoles table.

Step 3
Now, let’s add a View of UsersWithRoles method of ManageUsersController.
@model IEnumerable<MVC5Demo.UI.ViewModels.Users_in_Role_ViewModel> 
@{ 
    ViewBag.Title = "Users With Roles"; 
    Layout = "~/Views/Shared/_Layout.cshtml"; 

  
<div class="panel panel-primary"> 
    <div class="panel-heading"> 
        <h3 class="box-title"> 
            <b>Users with Roles</b> 
        </h3> 
    </div> 
    <!-- /.box-header --> 
    <div class="panel-body"> 
        <table class="table table-hover table-bordered table-condensed" id="UsersWithRoles"> 
            <thead> 
                <tr> 
                    <td><b>Username</b></td> 
                    <td><b>Email</b></td> 
                    <td><b>Roles</b></td> 
                </tr> 
            </thead> 
            @foreach (var user in Model) 
            { 
                <tr> 
                    <td>@user.Username</td> 
                    <td>@user.Email</td> 
                    <td>@user.Role</td> 
                     
                </tr> 
            } 
        </table> 
    </div> 
  
    <div class="panel-footer"> 
        <p class="box-title"><b>Total Users till @String.Format("{0 : dddd, MMMM d, yyyy}", DateTime.Now)  : </b><span class="label label-primary">@Model.Count()</span></p> 
    </div> 
</div> 
  
  
@section scripts{ 
    <script> 
        $(function () { 
            $('#UsersWithRoles').DataTable({ 
                "paging": true, 
                "lengthChange": true, 
                "searching": true, 
                "ordering": true, 
                "info": true, 
                "autoWidth": true 
            }); 
        }); 
    </script> 


Now, the above method and View will return the users to their roles.

n



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Project Modules In Treeview Using Angular And MVC

clock July 10, 2018 08:58 by author Peter

AngularJS is an MVC based framework. Google developed AngularJS. AngularJS is an open source project, which can be used freely, modified and shared by others.
Top features Of AngularJS

  • Two Way Data-Binding
    This means that any changes to the model update the view and any changes to the view updates the model.
  • Dependency Injection
    AngularJS has a built-in Dependency Injection, which makes application easier to develop, maintain and debug in addition to the test.
  • Testing
    Angular will test any of its code through both unit testing and end-to-end testing.
  • Model View Controller
    Split your application into MVC components. Maintaining these components and connecting them together means setting up Angular.
Prerequisites
  • Visual Studio 2017 Version 15.7.3
  • Microsoft .NET Framework Version 4.7
  • Microsoft SQL Server 2016
  • SQL Server Management Studio v17.7
In this project, the description is about the steps to create treeview structure of File and SubFile using AngularJS in MVC and This procedure can be implemented in case of Modules and related pages under each module in ERP type of project. So, here I show you a  project  which you can implement in a real-time scenario for better understanding of how many pages there are under respective Modules and the relation between Module and its corresponding pages.
Steps To Be Followed:
Step 1
Create a table named "Treeviewtbl".
Here I have a general script of Table creation with some dummy records inserted. You can find this SQL file inside the project folder named
"Treeviewtbl.sql"
Step 2
Then I have created an MVC application named "FileStructureAngular".
Step 3
Here I have added Entity Data Model named "SatyaModel.edmx" . 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 4
Inside HomeController I've added the following code.

Code Ref

 

    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web; 
    using System.Web.Mvc; 
     
    namespace FileStructureAngular.Controllers 
    { 
        public class HomeController : Controller 
        { 
            // 
            // GET: /Home/ 
            public ActionResult Index() 
            { 
                return View(); 
            } 
     
            public JsonResult GetFileStructure() 
            { 
                List<Treeviewtbl> list = new List<Treeviewtbl>(); 
                using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities()) 
                { 
                    list = dc.Treeviewtbls.OrderBy(a => a.FileName).ToList(); 
                } 
     
                List<Treeviewtbl> treelist = new List<Treeviewtbl>(); 
                if (list.Count > 0) 
                { 
                    treelist = BuildTree(list); 
                } 
     
                return new JsonResult { Data = new { treeList = treelist }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; 
            } 
      
            public void GetTreeview(List<Treeviewtbl> list, Treeviewtbl current, ref List<Treeviewtbl> returnList) 
            { 
                var childs = list.Where(a => a.ParentID == current.ID).ToList(); 
                current.Childrens = new List<Treeviewtbl>(); 
                current.Childrens.AddRange(childs); 
                foreach (var i in childs) 
                { 
                    GetTreeview(list, i, ref returnList); 
                } 
            } 
     
            public List<Treeviewtbl> BuildTree(List<Treeviewtbl> list) 
            { 
                List<Treeviewtbl> returnList = new List<Treeviewtbl>();   
                var topLevels = list.Where(a => a.ParentID == list.OrderBy(b => b.ParentID).FirstOrDefault().ParentID); 
                returnList.AddRange(topLevels); 
                foreach (var i in topLevels) 
                { 
                    GetTreeview(list, i, ref returnList); 
                } 
                return returnList; 
            } 
        } 
    } 

 

Code Description
Fetch data from the database and return it as a JSON result. 

    public JsonResult GetFileStructure()  
            {  
                List<Treeviewtbl> list = new List<Treeviewtbl>();  
                using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())  
                {  
                    list = dc.Treeviewtbls.OrderBy(a => a.FileName).ToList();  
                }  
      
                List<Treeviewtbl> treelist = new List<Treeviewtbl>();  
                if (list.Count > 0)  
                {  
                    treelist = BuildTree(list);  
                }  
      
                return new JsonResult { Data = new { treeList = treelist }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };  
            }  

I used a recursion method required for angularTreeview directive. Recursion method for recursively getting all child nodes and getting a child of the current item:
public void GetTreeview(List<Treeviewtbl> list, Treeviewtbl current, ref List<Treeviewtbl> returnList) 
        { 
            var childs = list.Where(a => a.ParentID == current.ID).ToList(); 
            current.Childrens = new List<Treeviewtbl>(); 
            current.Childrens.AddRange(childs); 
            foreach (var i in childs) 
            { 
                GetTreeview(list, i, ref returnList); 
            } 
        } 

To find top levels items:

    public List<Treeviewtbl> BuildTree(List<Treeviewtbl> list) 
            { 
                List<Treeviewtbl> returnList = new List<Treeviewtbl>(); 
                var topLevels = list.Where(a => a.ParentID == list.OrderBy(b => b.ParentID).FirstOrDefault().ParentID); 
                returnList.AddRange(topLevels); 
                foreach (var i in topLevels) 
                { 
                    GetTreeview(list, i, ref returnList); 
                } 
                return returnList; 
            } 

Step 5

Add a partial class of "Treeviewtbl" class for adding an additional field for holding child items. 
Code Ref

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
 
namespace FileStructureAngular 

    public partial class Treeviewtbl 
    { 
        public List<Treeviewtbl> Childrens { get; set; } 
    } 

Here is a field property "children" for identifying child nodes. So we need to add an additional field in our Model. So, I will add a partial class to add an additional field to hold child items. 

Step 6

Add required files into our project. In this article, I am going to use angularTreeview directive. This a very popular directive to render treeview from hierarchical data in AngularJS application.

  • angular.treeview.css
  • angular.treeview.js
  • image folder
The angular.treeview.css file is present in the Contents Folder. The angular.treeview.js file is present in Scripts Folder. I have added 3 png files for folder closed, folder opened, and files inside folders.

Here folders are the Modules and files are the pages under respective modules.

Step 7

I have added a Javascript file, where we will write AngularJS code for creating an Angular module and an Angular controller. 
In our application, I will add a Javascript file into the Scripts folder. Go to Solution Explorer > Right click on "Scripts" folder > Add > New Item > Select Javascript file under Scripts > Enter file name (here in my application it is "myApp.js") > and then click on Add button.

var app = angular.module('myApp', ['angularTreeview']); 
app.controller('myController', ['$scope', '$http', function ($scope, $http) { 
    $http.get('/home/GetFileStructure').then(function (response) { 
        $scope.List = response.data.treeList; 
    }) 
}]) 

Add a dependency to your application module.
var app = angular.module('myApp', ['angularTreeview']);   

Here I created a module named myApp and registered a controller named myController and then added GetFileStructure controller action method of HomeController for fetching data from the database and it returned as a JSON result.
$http.get('/home/GetFileStructure').then(function (response) {  
        $scope.List = response.data.treeList;  
    })  
Step 8
Add view for that (here index action) named "Index.cshtml".


    ViewBag.Title = "Satyaprakash - Website Modules In Treeview"; 

 
@*<h2>Website Modules In Treeview</h2>*@ 
 
<fieldset> 
    <legend style="font-family:Arial Black;color:blue">Website Modules In Treeview File Structure</legend> 
    <div ng-app="myApp" ng-controller="myController"> 
        <span style="font-family:Arial Black;color:forestgreen">Selected Node : <span style="font-family:Arial Black;color:red">{{mytree.currentNode.FileName}}</span> </span> 
        <br/> 
        <br/> 
        <div data-angular-treeview="true" 
             data-tree-id="mytree" 
             data-tree-model="List" 
             data-node-id="ID" 
             data-node-label="FileName" 
             data-node-children="Childrens"> 
        </div> 
    </div> 
 
    <link href="~/Content/angular.treeview.css" rel="stylesheet" /> 
    @section Scripts{ 
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script> 
        <script src="~/Scripts/angular.treeview.js"></script> 
        <script src="~/Scripts/myApp.js"></script> 
    } 
</fieldset> 

Here I have created a module name and registered a controller name under this module.

<div ng-app="myApp" ng-controller="myController">  

Copy the script and css into your project and add a script and link tag to your page.

<link href="~/Content/angular.treeview.css" rel="stylesheet" />  
  @section Scripts{  
      <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>  
      <script src="~/Scripts/angular.treeview.js"></script>  
      <script src="~/Scripts/myApp.js"></script>  
  }  

Attributes of angular treeview are below.

  • angular-treeview: the treeview directive.
  • tree-id : each tree's unique id.
  • tree-model : the tree model on $scope.
  • node-id : each node's id.
  • node-label : each node's label.
  • node-children: each node's children.
<div data-angular-treeview="true" 
    data-tree-id="mytree" 
    data-tree-model="List" 
    data-node-id="ID" 
    data-node-label="FileName" 
    data-node-children="Childrens"> 
</div> 

Then I mentioned a span tag for showing the text of selected folder and file name inside treeview.

<span style="font-family:Arial Black;color:forestgreen">Selected Node : <span style="font-family:Arial Black;color:red">{{mytree.currentNode.FileName}}</span> </span>  
TREE attribute

  • angular-treeview: the treeview directive
  • tree-id : each tree's unique id.
  • tree-model : the tree model on $scope.
  • node-id : each node's id
  • node-label : each node's label
  • node-children: each node's children



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Dynamic And Friendly URL Using ASP.NET MVC

clock March 1, 2017 08:29 by author Peter

This post will tell you about Dynamic And Friendly URL Using ASP.NET MVC. Dynamic URL is a great feature working with MVC. Friendly URLs are even better. The following approach, I think, is the best way to work with friendly URL. So, let's define some premises. The URLs must be stored in a Repository. This means, I want to change and create new URLs in my repository. One or more URLs can be pointed to the same Controller/Action. This means, I want to have alias for URLs;
If a URL does not exist in my Repository, try to resolve it using MVC Controller/Action default behavior. It means, the MVC default behavior will still work;
The URL cannot contain an ID at the end. It means that the last segment of those URLs can be a long ID number.

First of all, MVC does not have a built-in feature for dynamic and friendly URLs. You must write your own custom code.

For solution, we will need the following.

  • An MVC project;
  • A class to handle route requests;
  • A route repository;
  • Controllers and Views;

PS-  I will not use a database to store those URLs but I will use the repository pattern and dependency resolver to configure it. So, you can create a database repository in future.

Class that identifies a URL -

Handlers/UrlHandler.cs
public sealed class UrlHandler { 
public static UrlRouteData GetRoute(string url) { 
    url = url ? ? "/"; 
    url = url == "/" ? "" : url; 
    url = url.ToLower(); 

    UrlRouteData urlRoute = null; 

    using(var repository = DependencyResolver.Current.GetService < IRouteRepository > ()) { 
        var routes = repository.Find(url); 
        var route = routes.FirstOrDefault(); 
        if (route != null) { 
            route.Id = GetIdFromUrl(url); 
            urlRoute = route; 
            urlRoute.Success = true; 
        } else { 
            route = GetControllerActionFromUrl(url); 
            urlRoute = route; 
            urlRoute.Success = false; 
        } 
    } 

    return urlRoute; 


private static RouteData GetControllerActionFromUrl(string url) { 
    var route = new RouteData(); 

    if (!string.IsNullOrEmpty(url)) { 
        var segmments = url.Split('/'); 
        if (segmments.Length >= 1) { 
            route.Id = GetIdFromUrl(url); 
            route.Controller = segmments[0]; 
            route.Action = route.Id == 0 ? (segmments.Length >= 2 ? segmments[1] : route.Action) : route.Action; 
        } 
    } 

    return route; 


private static long GetIdFromUrl(string url) { 
    if (!string.IsNullOrEmpty(url)) { 
        var segmments = url.Split('/'); 
        if (segmments.Length >= 1) { 
            var lastSegment = segmments[segmments.Length - 1]; 
            long id = 0; 
            long.TryParse(lastSegment, out id); 

            return id; 
        } 
    } 

    return 0; 

}

Route Handler that handles all requests.

Handlers/UrlRouteHandler.cs
public IHttpHandler GetHttpHandler(RequestContext requestContext)  

var routeData = requestContext.RouteData.Values; 
var url = routeData["urlRouteHandler"] as string; 
var route = UrlHandler.GetRoute(url); 

routeData["url"] = route.Url; 
routeData["controller"] = route.Controller; 
routeData["action"] = route.Action; 
routeData["id"] = route.Id; 
routeData["urlRouteHandler"] = route; 

return new MvcHandler(requestContext); 
}

The route handler configuration.

App_Start/RouteConfig.cs

public class RouteConfig  

public static void RegisterRoutes(RouteCollection routes)  

    routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

    routes.MapRoute( 
        "IUrlRouteHandler", 
        "{*urlRouteHandler}").RouteHandler = new UrlRouteHandler(); 

}


Repository/IRouteRepository.cs
public interface IRouteRepository: IDisposable  

IEnumerable < RouteData > Find(string url); 
}

Repository/StaticRouteRepository.cs

public class StaticRouteRepository: IRouteRepository 

public void Dispose() { 



public IEnumerable < RouteData > Find(string url) { 
    var routes = new List < RouteData > (); 
    routes.Add(new RouteData() { 
        RoouteId = Guid.NewGuid(), 
            Url = "how-to-write-file-using-csharp", 
            Controller = "Articles", 
            Action = "Index" 
    }); 
    routes.Add(new RouteData() { 
        RoouteId = Guid.NewGuid(), 
            Url = "help/how-to-use-this-web-site", 
            Controller = "Help", 
            Action = "Index" 
    }); 

    if (!string.IsNullOrEmpty(url)) { 
        var route = routes.SingleOrDefault(r => r.Url == url); 
        if (route == null) { 
            route = routes.FirstOrDefault(r => url.Contains(r.Url)) ? ? routes.FirstOrDefault(r => r.Url.Contains(url)); 
        } 

        if (route != null) { 
            var newRoutes = new List < RouteData > (); 
            newRoutes.Add(route); 

            return newRoutes; 
        } 
    } 

    return new List < RouteData > (); 

}


I have created 2 URLs. One URL will point to the Help Controller while the other one to the Articles Controller. For dependency resolver configuration, I used Ninject.
App_Start/NinjectWebCommon.cs
private static void RegisterServices(IKernel kernel) 

kernel.Bind < Repository.IRouteRepository > ().To < Repository.StaticRouteRepository > (); 
}



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.



HostForLIFE.eu Proudly Launches Umbraco 7.5.7 Hosting

clock January 27, 2017 08:03 by author Peter

HostForLIFE.eu, a leading Windows web hosting provider with innovative technology solutions and a dedicated professional services team, today announced the support for Umbraco 7.5.7 hosting plan due to high demand of Umbraco users in Europe. The company has managed to build a strong client base in a very short period of time. It is known for offering ultra-fast, fully-managed and secured services in the competitive market.

 

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam, (NL), London, (UK), Washington, D.C. (US), Paris, (France), Frankfurt, (Germany), Chennai, (India), Milan, (Italy), Toronto, (Canada) and São Paulo, (Brazil) to guarantee 99.9% network uptime. All data centers feature redundancies in network connectivity, power, HVAC, security and fire suppression. All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee. HostForLIFE Umbraco hosting plan starts from just as low as €3.49/month only and this plan has supported ASP.NET Core 1.1, ASP.NET MVC 5/6 and SQL Server 2012/2014/2016.

Umbraco is a fully-featured open source content management system with the flexibility to run anything from small campaign or brochure sites right through to complex applications for Fortune 500's and some of the largest media sites in the world. Umbraco is strongly supported by both an active and welcoming community of users around the world, and backed up by a rock-solid commercial organization providing professional support and tools. Umbraco can be used in its free, open-source format with the additional option of professional tools and support if required.

Umbraco release that exemplifies our mission to continue to make Umbraco a bit simpler every day. The other change is that there's now a "ValidatingRequest" event you can hook into. This event allows you to "massage" any of the requests to ImageProcessor to your own liking. So if you'd want to never allow any requests to change BackgroundColor, you can cancel that from the event. Similarly if you have a predefined set of crops that are allowed, you could make sure that no other crop sizes will be processed than those ones you have defined ahead of time.

Further information and the full range of features Umbraco 7.5.7 Hosting can be viewed here: http://hostforlife.eu/European-Umbraco-757-Hosting



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Button Loader Integration in ASP.NET MVC

clock January 19, 2017 08:29 by author Peter

Today, I will write about Button Loader Integration in ASP.NET MVC. User interaction & responsiveness are major aspects in any application. It is always good to tell the user that is happening in the application i.e. whether they have to wait for certain processing or they can proceed with another action,  etc.

Today, I shall be demonstrating the integration of a simple button loader plugin called Ladda, you can explore it more by visiting the website.

You can download the complete source code for this tutorial from here or you can follow step by step discussion below. The sample code is developed in Microsoft Visual Studio 2013 Ultimate.

Create new MVC web project and name it "ButtonLoader".

Download the Ladda plugin and incorporate its related JavaScript & CSS files into the project.

Create new controller under "Controller" folder and name it "LoaderController.cs".

Open "RouteConfig.cs" file under "App_Start" folder and change the default controller to "Loader" and action to "Index" as shown below.
    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web; 
    using System.Web.Mvc; 
    using System.Web.Routing; 
    namespace ButtonLoader 
    { 
        public class RouteConfig 
        { 
            public static void RegisterRoutes(RouteCollection routes) 
            { 
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
                routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new 
                { 
                    controller = "Loader", action = "Index", id = UrlParameter.Optional 
                }); 
            } 
        } 
    } 

Create new file "LoaderViewModels.cs" under "Models" folder and place the following code in it:
    using System.ComponentModel.DataAnnotations; 
    namespace ButtonLoader.Models 
    { 
        public class LoaderViewModel 
        { 
            [Required] 
            [Display(Name = "Text")] 
            public string Text 
            { 
                get; 
                set; 
            } 
        } 
    } 

Here, we have created a simple model for observing our loader effect.
Now, open "LoaderController.cs" file under "Controller" folder and replace it with the following code:
    //-----------------------------------------------------------------------  
    // <copyright file="LoaderController.cs" company="None"> 
    // Copyright (c) Allow to distribute this code.  
    // </copyright> 
    // <author>Asma Khalid</author> 
    //-----------------------------------------------------------------------  
    namespace ButtonLoader.Controllers 
    { 
        using System; 
        using System.Collections.Generic; 
        using System.Linq; 
        using System.Security.Claims; 
        using System.Threading; 
        using System.Threading.Tasks; 
        using System.Web; 
        using System.Web.Mvc; 
        using ButtonLoader.Models; 
        /// <summary> 
        /// Loader controller class.  
        /// </summary> 
        public class LoaderController: Controller 
        { 
            #region Index view method.#region Get: /Loader/Index 
            method. 
                /// <summary> 
                /// Get: /Loader/Index method.  
                /// </summary> 
                /// <returns>Return index view</returns> 
            public ActionResult Index() 
            { 
                try 
                {} 
                catch (Exception ex) 
                { 
                    // Info  
                    Console.Write(ex); 
                } 
                // Info.  
                return this.View(); 
            }#endregion# region POST: /Loader/Index 
                /// <summary> 
                /// POST: /Loader/Index  
                /// </summary> 
                /// <param name="model">Model parameter</param> 
                /// <returns>Return - Loader content</returns> 
                [HttpPost] 
                [AllowAnonymous] 
                [ValidateAntiForgeryToken] 
            public ActionResult Index(LoaderViewModel model) 
            { 
                try 
                { 
                    // Verification  
                    if (ModelState.IsValid) 
                    { 
                        // Sleep.  
                        Thread.Sleep(5000); // 5 sec.  
                        // Info.  
                        return this.Json(new 
                        { 
                            EnableSuccess = true, SuccessTitle = "Success", SuccessMsg = model.Text 
                        }); 
                    } 
                } 
                catch (Exception ex) 
                { 
                    // Info  
                    Console.Write(ex); 
                } 
                // Sleep.  
                Thread.Sleep(5000); // 5 sec.  
                // Info  
                return this.Json(new 
                { 
                    EnableError = true, ErrorTitle = "Error", ErrorMsg = "Something goes wrong, please try again later" 
                }); 
            }#endregion# endregion 
        } 
    } 
In the above code snippet, we have created a simple "HttpGet" & "HttpPost" methods to observer the behavior of the button loader. We have also placed a 5 sec delay in the post method at every response to observer the behavior of the button loader from server side as well.

Now, in "Views->Loader" folder create a new page called "Index.cshtml" and place the following code in it:
    @using ButtonLoader.Models  
    @model ButtonLoader.Models.LoaderViewModel  
    @{  
    ViewBag.Title = "ASP.NET MVC5 C#: Button Loader Integration";  
    }  
     
    <div class="row"> 
        <div class="panel-heading"> 
            <div class="col-md-8"> 
                <h3> 
                    <i class="fa fa-file-text-o"></i> 
                    <span>Bootstrap Modal with ASP.NET MVC5 C#</span> 
                </h3> 
            </div> 
        </div> 
    </div> 
    <div class="row"> 
        <section class="col-md-4 col-md-push-4"> 
            @using (Ajax.BeginForm("Index", "Loader", new AjaxOptions { HttpMethod = "POST", OnSuccess = "onLoaderSuccess" }, new { @id = "LoaderformId", @class = "form-horizontal", role = "form" }))  
            {  
                @Html.AntiForgeryToken()  
     
            <div class="well bs-component"> 
                <br /> 
                <div class="row"> 
                    <div class="col-md-12 col-md-push-2"> 
                        <div class="form-group"> 
                            <div class="col-md-10 col-md-pull-1"> 
                                @Html.TextBoxFor(m => m.Text, new { placeholder = Html.DisplayNameFor(m => m.Text), @class = "form-control" })  
                                @Html.ValidationMessageFor(m => m.Text, "", new { @class = "text-danger custom-danger" })  
                            </div> 
                        </div> 
                        <div class="form-group"> 
                            <div class="col-md-18"></div> 
                        </div> 
                        <div class="form-group"> 
                            <div class="col-md-4 col-md-push-2"> 
                                <div > 
                                    <button type="submit"  
                                        class="btn btn-warning ladda-button"  
                                        value="Process"  
                                        data-style="slide-down"> 
                                        <span class="ladda-label">Process</span> 
                                    </button> 
                                </div> 
                            </div> 
                        </div> 
                    </div> 
                </div> 
            </div> 
    }  
     
        </section> 
    </div> 
In the above code snippet, we have created a simple text input box and a button, for Ladda plugin to work however, you have to use following structure on button i.e.
    <button type="submit" class="btn btn-warning ladda-button" value="Process" data-style="slide-down"> 
        <span class="ladda-label">Process</span> 
    </button> 
Unfortunately, Ladda plugin does not work with input type buttons.

Under "Scripts" folder, create a new script called "custom-loader.js" and place the following code in it:
    $(document).ready(function() 
    { 
        Ladda.bind('.ladda-button'); 
        $("#LoaderformId").submit(function(event) 
        { 
            var dataString; 
            event.preventDefault(); 
            event.stopImmediatePropagation(); 
            var action = $("#LoaderformId").attr("action"); 
            // Setting.  
            dataString = new FormData($("#LoaderformId").get(0)); 
            contentType = false; 
            processData = false; 
            $.ajax( 
            { 
                type: "POST", 
                url: action, 
                data: dataString, 
                dataType: "json", 
                contentType: contentType, 
                processData: processData, 
                success: function(result) 
                { 
                    // Result.  
                    onLoaderSuccess(result); 
                }, 
                error: function(jqXHR, textStatus, errorThrown) 
                { 
                    //do your own thing  
                    alert("fail"); 
                    // Stop Button Loader.  
                    Ladda.stopAll(); 
                } 
            }); 
        }); //end .submit()  
    }); 
    var onLoaderSuccess = function(result) 
    { 
        if (result.EnableError) 
        { 
            // Clear.  
            $('#ModalTitleId').html(""); 
            $('#ModalContentId').html(""); 
            // Setting.  
            $('#ModalTitleId').append(result.ErrorTitle); 
            $('#ModalContentId').append(result.ErrorMsg); 
            // Show Modal.  
            $('#ModalMsgBoxId').modal( 
            { 
                backdrop: 'static', 
                keyboard: false 
            }); 
        } 
        else if (result.EnableSuccess) 
        { 
            // Clear.  
            $('#ModalTitleId').html(""); 
            $('#ModalContentId').html(""); 
            // Setting.  
            $('#ModalTitleId').append(result.SuccessTitle); 
            $('#ModalContentId').append(result.SuccessMsg); 
            // Show Modal.  
            $('#ModalMsgBoxId').modal( 
            { 
                backdrop: 'static', 
                keyboard: false 
            }); 
            // Resetting form.  
            $('#LoaderformId').get(0).reset(); 
        } 
        // Stop Button Loader.  
        Ladda.stopAll(); 
    } 

I have also combined modal here to display server response. The following piece of code will bind the button loader plugin with the button i.e.
    Ladda.bind('.ladda-button');  
So, whenever, I click the button the button loader will start. The following piece of code will stop the button loader effect whenever I receive a response from the server side:
    // Stop Button Loader.  
    Ladda.stopAll();  

   
Now, execute the application. I hope it works for you!

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.

   

 



HostForLIFE.eu Proudly Launches Visual Studio 2017 Hosting

clock December 2, 2016 07:22 by author Peter

European leading web hosting provider, HostForLIFE.eu announces the launch of Visual Studio 2017 Hosting

HostForLIFE.eu was established to cater to an underserved market in the hosting industry; web hosting for customers who want excellent service. HostForLIFE.eu - a cheap, constant uptime, excellent customer service, quality, and also reliable hosting provider in advanced Windows and ASP.NET technology. HostForLIFE.eu proudly announces the availability of the Visual Studio 2017 hosting in their entire servers environment.

The smallest install is just a few hundred megabytes, yet still contains basic code editing support for more than twenty languages along with source code control. Most users will want to install more, and so customer can add one or more 'workloads' that represent common frameworks, languages and platforms - covering everything from .NET desktop development to data science with R, Python and F#.

System administrators can now create an offline layout of Visual Studio that contains all of the content needed to install the product without requiring Internet access. To do so, run the bootstrapper executable associated with the product customer want to make available offline using the --layout [path] switch (e.g. vs_enterprise.exe --layout c:\mylayout). This will download the packages required to install offline. Optionally, customer can specify a locale code for the product languages customer want included (e.g. --lang en-us). If not specified, support for all localized languages will be downloaded.

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam (NL), London (UK), Paris (FR), Frankfurt(DE) and Seattle (US) to guarantee 99.9% network uptime. All data center feature redundancies in network connectivity, power, HVAC, security, and fire suppression. All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee. The customers can start hosting their Visual Studio 2017 site on their environment from as just low €3.00/month only.

HostForLIFE.eu is a popular online ASP.NET based hosting service provider catering to those people who face such issues. The company has managed to build a strong client base in a very short period of time. It is known for offering ultra-fast, fully-managed and secured services in the competitive market.

HostForLIFE.eu offers the latest European Visual Studio 2017 hosting installation to all their new and existing customers. The customers can simply deploy their Visual Studio 2017 website via their world-class Control Panel or conventional FTP tool. HostForLIFE.eu is happy to be offering the most up to date Microsoft services and always had a great appreciation for the products that Microsoft offers.

Further information and the full range of features Visual Studio 2017 Hosting can be viewed here http://hostforlife.eu/European-Visual-Studio-2017-Hosting



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