European ASP.NET MVC Hosting

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

European ASP.NET MVC 6 Hosting - HostForLIFE.eu :: New Configuration and AppSetings for ASP.NET MVC 6

clock January 17, 2017 10:35 by author Scott

There’s a new place to put the app settings for your MVC6 ASP.NET Core application. Web.config is gone but the new solution is great, you get a dependency injected POCO with strongly typed settings instead!

New Settings File - appsettings.json

Instead of web.config, all your settings are now located in appsettings.json. Here’s what the default one looks like, though I’ve also added an AppSettings section:

{
  "AppSettings": {
    "BaseUrls": {
      "API": "https://localhost:44307/",
      "Auth": "https://localhost:44329/",
      "Web": https://localhost:44339/
    },
    "AnalyticsEnabled": true
  },
  "Data": {
    "DefaultConnection": {
      "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-AppSettings1-ad2c59cc-294a-4e72-bc31-078c88eb3a99;Trusted_Connection=True;MultipleActiveResultSets=true"
    }
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Verbose",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

Notice that we’re using JSON instead of XML now. This is pretty great with one big exception, No Intellisense.

Create an AppSettings class

If you’re used to using ConfigurationManager.AppSettings["MySetting"] in your controllers then you’re out of luck, instead you need to setup a class to hold your settings. As you can see above I like to add an “AppSettings” section to the config that maps directly to an AppSettings POCO. You can even nest complex classes as deep as you like:

public class AppSettings
{
    public BaseUrls BaseUrls { get; set; }
    public bool AnalyticsEnabled { get; set; }
}

public class BaseUrls
{
    public string Api { get; set; }
    public string Auth { get; set; }
    public string Web { get; set; }
}  

Configure Startup.cs

Now that we have a class to hold our settings, lets map the data from our appsettings.json. You can do it in a couple of ways

Automatically bind all app settings:

public IServiceProvider ConfigureServices(IServiceCollection services)
{           
    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}

or if you need to alter or transform anything you can assign each property manually:

public IServiceProvider ConfigureServices(IServiceCollection services)
{           
    services.Configure<AppSettings>(appSettings =>
    {
        appSettings.BaseUrls = new BaseUrls()
        {
            // Untyped Syntax - Configuration[""]
            Api = Configuration["AppSettings:BaseUrls:Api"],
            Auth = Configuration["AppSettings:BaseUrls:Auth"],
            Web = Configuration["AppSettings:BaseUrls:Web"],
        };               

        // Typed syntax - Configuration.Get<type>("")
        appSettings.AnalyticsEnabled = Configuration.Get<bool>("AppSettings:AnalyticsEnabled");
    });
}

Using the settings

Finally we can access our settings from within our controllers. We’ll be using dependency injection, so if you’re unfamiliar with that, get ready to learn!

public class HomeController : Controller
{
    private readonly AppSettings _appSettings;

    public HomeController(IOptions<AppSettings> appSettings)
    {
        _appSettings = appSettings.Value;
    }

    public IActionResult Index()
    {
        var webUrl = _appSettings.BaseUrls.Web;

        return View();
    }
}

There are a few important things to note here:

The class we are injecting is of type IOptions<AppSettings>. If you try to inject AppSettings directly it won’t work.

Instead of using the IOptions class throughout the code, instead I set the private variable to just AppSettings and assign it in the constructor using the .Value property of the IOptions class.

By the way, the IOptions class is essentially a singleton. The instance we create during startup is the same throughout the lifetime of the application.

While this is a lot more setup than the old way of doing things, I think it forces developers to code in a cleaner and more modular way.



European ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Binding and Minification in SiteCore MVC

clock January 6, 2017 07:01 by author Scott

This is a quick blog post on how to implement bundling and minification in Sitecore MVC project.  During development phase, it is always good to have multiple Javascripts and CSS files for better readability and maintainability of code.  But multiple Javascripts and CSS files degrade the performance of production website and also increase the load time of webpages as it requires multiple HTTP requests from browser to server.  Bundling and minification reduce the size of Javascript and CSS files and bundle multiple files into a single file and make the site perform faster by making fewer HTTP requests. Below steps explain how to implement bundling and minification for Sitecore MVC project: 

1. Add Microsoft ASP.NET Web Optimization Framework to your solution from nuget or run the following command in the Package Manager Console to install Microsoft ASP.NET Web Optimization Framework.

PM> Install-Package Microsoft.AspNet.Web.Optimization

2. Create your CSS and Javascript bundles in “BundleConfig” class under App_Start folder and add reference of "System.Web.Optimization" namespace.

public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            //js bundling using wildcard character *
            bundles.Add(new ScriptBundle("~/bundles/js").Include("~/assets/js/*.js"));

            //css bundling using wildcard character *
            bundles.Add(new StyleBundle("~/bundles/css").Include("~/assets/css/*.css"));
        }
    }

3. Register bundle in the Application_Start method in the Global.asax file. If you are using Multi-site instance of Sitecore MVC then recommend way to implement bundling logic is by creating a new processor into the initialize pipeline. 

protected void Application_Start(object sender, EventArgs e)
        {
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

We can override the value of the debug attribute in code by using EnableOptimizations property of the BundleTable class.

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            EnableBundleOptimizations();
        }

        private void EnableBundleOptimizations()
        {
            string debugMode = Request.QueryString["debug"];
            if (!string.IsNullOrEmpty(debugMode) && string.Equals(debugMode, "true", StringComparison.InvariantCultureIgnoreCase))
            {
                BundleTable.EnableOptimizations = false;
            }
            else
            {
                BundleTable.EnableOptimizations = true;
            }
        }

Here in Application_BeginRequest method of Global.asax I am calling one custom method EnableBundleOptimizations() which sets the value of EnableOptimizations property to true or false based on value of querystring “debug”. Main idea behind this logic is that we can check/debug CSS or Javascript file on production by passing querystring parameter debug as true. 

5. Replace Javascripts and CSS references in layout or rendering view with below code:

@Styles.Render("~/bundles/css")
@Styles.Render("~/bundles/js")

6. In web.config set an ignore url prefix for your bundle so that Sitecore won’t try to resolve the URL to the bundle. Update setting IgnoreUrlPrefixes according to your bundle name:

<setting name="IgnoreUrlPrefixes" value="/sitecore/default.aspx|/trace.axd|/webresource.axd|/sitecore/shell/Controls/Rich Text Editor/Telerik.Web.UI.DialogHandler.aspx|/sitecore/shell/applications/content manager/telerik.web.ui.dialoghandler.aspx|/sitecore/shell/Controls/Rich Text Editor/Telerik.Web.UI.SpellCheckHandler.axd|/Telerik.Web.UI.WebResource.axd|/sitecore/admin/upgrade/|/layouts/testing|/bundles/js|/bundles/css"/>

7. Now compile your solution and verify that bundling and minification is enabled by checking view source of webpage.

Pass querystring as debug=true in url and now verify view source of webpage. Bundling and minification is not enabled. This enables us to debug Javascript and CSS files in production website. 



European ASP.NET MVC Hosting - HostForLIFE.eu :: Custom Model Binders in ASP.NET MVC

clock December 22, 2016 06:31 by author Scott

In ASP.NET MVC, our system is built such that the interactions with the user are handled through Actions on our Controllers. We select our actions based on the route the user is using, which is a fancy way of saying that we base it on a pattern found in the URL they’re using. If we were on a page editing an object and we clicked the save button we would be sending the data to a URL somewhat like this one.

Notice that in our route that we have specified the name of the object that we’re trying to save. There is a default Model Binder for this in MVC that will take the form data that we’re sending and bind it to a CLR objects for us to use in our action. The standard Edit action on a controller looks like this.

[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
    try
    {
        // TODO: Add update logic here
 
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

If we were to flesh some of this out the way it’s set up here, we would have code that looked a bit like this.

[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
    try
    {
        Profile profile = _profileRepository.GetProfileById(id);

        profile.FavoriteColor = collection["favorite_color"];
        profile.FavoriteBoardGame = collection["FavoriteBoardGame"];

        _profileRepository.Add(profile);

        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

What is bad about this is that we are accessing the FormCollection object which is messy and brittle. Once we start testing this code it means that we are going to be repeating code similar to this elsewhere. In our tests we will need to create objects using these magic strings. What this means is that we are now making our code brittle. If we change the string that is required for this we will have to go through our code correcting them. We will also have to find them in our tests or our tests will fail. This is bad. What we should do instead is have these only appear on one place, our model binder. Then all the code we test is using CLR objects that get compile-time checking. To create our Custom Model Binder this is all we need to do is write some code like this.

public class ProfileModelBinder : IModelBinder
{
    ProfileRepository _profileRepository = new ProfileRepository();

    public object BindModel(ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
        int id = (int)controllerContext.RouteData.Values["Id"];
        Profile profile = _profileRepository.GetProfileById(id);

        profile.FavoriteColor = bindingContext
            .ValueProvider
            .GetValue("favorite_color")
            .ToString();


        profile.FavoriteBoardGame = bindingContext
            .ValueProvider
            .GetValue("FavoriteBoardGame")
            .ToString();

        return profile;
    }
}

Notice that we are using the form collection here, but it is limited to this one location. When we test we will just have to pass in the Profile object to our action, which means that we don’t have to worry about these magic strings as much, and we’re also not getting into the situation where our code becomes so brittle that our tests inhibit change. The last thing we need to do is tell MVC that when it is supposed to create a Profile object that it is supposed to use this model binder. To do this, we just need to Add our binder to the collection of binders in the Application_Start method of our GLobal.ascx.cs file. It’s done like this. We say that this binder is for objects of type Profile and give it a binder to use.

ModelBinders.Binders.Add(typeof (Profile), new ProfileModelBinder());

Now we have a model binder that should let us keep the messy code out of our controllers. Now our controller action looks like this.

[HttpPost]
public ActionResult Edit(Profile profile)
{
    try
    {
        _profileRepository.Add(profile);

        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

That looks a lot cleaner to me, and if there were other things I needed to do during that action, I could do them without all of the ugly binding logic.

 



European ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Implement Sessions in ASP.NET MVC 6

clock December 15, 2016 07:36 by author Scott

Imagine you have created an MVC project and you are all set to create a session object in order to save your current user Email but after few minutes, you realize that the session object is not working, as it was before.

Oh! Why is it so?

It is because .NET team has created a NuGet package for Session, which is nothing but a very fresh ASP.NET 5 Session State middleware.

OK. So, how to get it?

To install Microsoft.AspNet.Session, run the command, given below, in the Package Manager Console. 

We need to update the startup.cs file, as shown below:

public void ConfigureServices(IServiceCollection services) {  
    // Adds a default in-memory implementation of IDistributedCache  
    services.AddCaching();  
    services.AddSession();  
    //// This Method may contain other code as well  
}  
and in Configure method write below code: public void Configure(IApplicationBuilder app) {  
    app.UseSession();  
    //// This Method may contain other code as well  
}  

How to get and set session?

Let's take some examples.

1. Suppose, you want to use Session in your controller class. For it, you simply have to write Context.Session to access Session.

Set Session syntax:

public IActionResult Index() {  
    ////Context.Session.SetString("First", "I am first!"); ////Before Beta 8  
    HttpContext.Session.SetString("First""I am first!"); ////From Beta 8 onwards  
    return View();  
}  
Get Session syntax: public IActionResult Index() {  
    ////var myValue = Context.Session.GetString("First"); ////Before Beta 8  
    var myValue = HttpContext.Session.GetString("First"); ////From Beta 8 onwards  
    return View();  
}  

2. Suppose, you want to use Session in a normal class. If you’re not in a Controller, you can still access the HttpContext by injecting IHttpContextAccessor, as shown below:

private readonly IHttpContextAccessor _httpContextAccessor;  
public SessionUtility(IHttpContextAccessor httpContextAccessor) {  
    _httpContextAccessor = httpContextAccessor;  
}  
Set Session syntax: public void SetSession(string key, string value) {  
    HttpContextAccessor.HttpContext.Session.SetString(key, value);  
}  
Get Session syntax: public string GetSession(string key) {  
    return HttpContextAccessor.HttpContext.Session.GetString(key);  
}  
So, whole SessionUtility would be as below: public class SessionUtility {  
    private readonly IHttpContextAccessor HttpContextAccessor;  
    public SessionUtility(IHttpContextAccessor httpContextAccessor) {  
        HttpContextAccessor = httpContextAccessor;  
    }  
    public void SetSession(string key, string value) {  
        HttpContextAccessor.HttpContext.Session.SetString(key, value);  
    }  
    public string GetSession(string key) {  
        return HttpContextAccessor.HttpContext.Session.GetString(key);  
    }  
}  

and it would be registered as:

services.AddTransient<SessionUtility>();  

Here, SessionUtility should be registered only as Transient or Scoped and not Singleton as HttpContext is per-request based.

Please note, I have used it with the key value pair of the string, but you can create the same SessionUtility for the complex scenarios.

Now, suppose you want to check how many times a visitor has visited your site.

For it, you need to add the code, given below, in your startup.cs:

public void Configure(IApplicationBuilder app) {  
    app.UseSession();  
    app.Map("/session", subApp => {  
        subApp.Run(async context => {  
            int visits = 0;  
            visits = context.Session.GetInt32("visits") ? ? 0;  
            context.Session.SetInt32("visits", ++visits);  
            await context.Response.WriteAsync("Counting: You have visited our page this many times: " + visits);  
        });  
    });  
}  

Important!

If you have followed the steps, given above and you still can't get success, you might need a look in your project.json file for the following piece of the code. Well, it should be there.

"frameworks": {  
"dnx451": { },  
"dnxcore50": { } // <-- Remove this if it is in your project.json file.  
},  

Why?

ASP.NET5 Sessions aren’t supported by the DNX Core Runtime.

NuGet package site: https://www.nuget.org/packages/Microsoft.AspNet.Session/

Session is still in its beta versions. Thus, some changes might come, which I will update in this post.

Stay tuned for more updates!

 



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



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Persistant Cookies in ASP.NET MVC 6

clock December 1, 2016 08:05 by author Peter

As with the most things in ASP.NET MVC 6, just about everything is handled within your Startup.cs file. With this tutorial, you will set up all your necessary routing, services, dependency injection, and more. And setting an expiration for a persistent cookie, turns out to be no different.
 

To set your persistent cookie expiration, you will need to associate the cookie to your current Identity provider. This is handled within the ConfigureServices method of the previously mentioned Startup.cs file, as you can see on the following code:
    public void ConfigureServices(IServiceCollection services)   
    { 
                // Add Entity Framework services to the services container along 
                // with the necessary data contexts for the application 
                services.AddEntityFramework() 
                        .AddSqlServer() 
                        .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration["Data:IdentityConnection:ConnectionString"])) 
                        .AddDbContext<YourOtherContext>(options => options.UseSqlServer(Configuration["Data:DataConnection:ConnectionString"])); 
     
                // Add Identity services to the services container 
                services.AddIdentity<ApplicationUser, IdentityRole>(i => { 
                            i.SecurityStampValidationInterval = TimeSpan.FromDays(7); 
                        }) 
                        .AddEntityFrameworkStores<ApplicationDbContext>()                    
                        .AddDefaultTokenProviders(); 
     
                // Other stuff omitted for brevity 
    } 


You might have noticed after a quick peek at this code what exactly you need to be setting. That's right. The SecurityStampValidationInterval property:
    // This will allow you to set the duration / expiration of your 
    // authentication token 
    i.SecurityStampValidationInterval = TimeSpan.FromDays(7); 


This example would only require the users to re-validate if they have not logged into the application within seven days. You can simply adjust this interval value to suit your needs.

 

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 6 Hosting - HostForLIFE.eu :: Dynamic Auto Complete in MVC for any Table of DataBase

clock October 25, 2016 09:14 by author Peter

Today, I will tell you about Dynamic Auto Complete in MVC for any Table of DataBase. With the following code, we can file record of product code on the basis of product name. Now write the code below:

View
@model string < input type = "hidden" 
id = "TableName_@Model" 
value = "@Model" / > @Html.TextBox("txtCode_" + @Model) 
@Html.TextBox("txtName_" + @Model) < script type = "text/javascript" > $(function () 

    $('#txtName_@Model').autocomplete( 
    { 
        source: function (request, response) 
        { 
            alert("hi"); 
            var id = $('#TableName_@Model').val(); 
            $.ajax( 
            { 
                url: "/Common/AutocompleteName/" + id + "?name=" + $('#txtName_@Model').val(), 
                dataType: "json", 
                type: 'POST', 
                data: 
                { 
                    name: request.term 
                }, 
                success: function (data) 
                { 
                    response(data); 
                } 
            }); 
        }, 
        autoFocus: true, 
        select: function (event, ui) 
        { 
            var id = $('#TableName_@Model').val(); 
            var mData; 
            var unit; 
            $.ajax( 
            { 
                url: "/Common/GetCodeName/" + id, 
                type: 'POST', 
                data: 
                { 
                    codeName: ui.item.value, 
                    mPara: 'N' 
                }, 
                success: function (_result) 
                { 
                    // alert(_result); 
                    mData = _result.UserName; 
                    unit = _result.unitdata; 
                    setTimeout(function () 
                    { 
                        $('#txtCode_@Model').val(mData); 
                    }, 1000); 
                    $('#Description_@Model').val(mData); 
                    $('#Units_@Model').html(unit); 
                } 
            }); 
        }, 
        minLength: 1 
    }); 
    $('#txtCode_@Model').autocomplete( 
    { 
        source: function (request, response) 
        { 
            var id = $('#TableName_@Model').val(); 
            $.ajax( 
            { 
                url: "/Common/AutocompleteCode/" + id + "?code=" + $('#txtCode_@Model').val(), 
                dataType: "json", 
                data: 
                { 
                    code: request.term 
                }, 
                success: function (data) 
                { 
                    response(data); 
                }, 
                type: 'POST' 
            }); 
        }, 
        autoFocus: true, 
        select: function (event, ui) 
        { 
            var id = $('#TableName_@Model').val(); 
            var mData; 
            var unit; 
            $.ajax( 
            { 
                url: "/Common/GetCodeName/" + id, 
                type: 'POST', 
                data: 
                { 
                    codeName: ui.item.value, 
                    mPara: 'C' 
                }, 
                success: function (_result) 
                { 
                    unit = _result.unitdata; 
                    mData = _result.UserName; 
                    setTimeout(function () 
                    { 
                        $('#txtName_@Model').val(mData); 
                    }, 1000); 
                    $('#Units_@Model').html(unit); 
                    $('#Description_@Model').val(mData); 
                } 
            }); 
        }, 
        minLength: 1 
    }); 
}); < /script> 
Controller-- -- -- -- -- -- -- -- -- -- -- --[HttpPost] 
public JsonResult AutocompleteName(string id, string name) 

    var TblSet = Core.CoreCommon.GetTableData(id); 
    var output = TblSet.AsQueryable().ToListAsync().Result.ToList(); 
    Dal.TFAT_WEBERPEntities context = new Dal.TFAT_WEBERPEntities(); 
    return Json(from m in output where m.GetType().GetProperty("Name").GetValue(m).ToString().Contains(name) select m.GetType().GetProperty("Name").GetValue(m).ToString()); 
    } 
    [HttpPost] 
public JsonResult AutocompleteCode(string id, string code) 
    { 
        var TblSet = Core.CoreCommon.GetTableData(id); 
        var output = TblSet.AsQueryable().ToListAsync().Result.ToList(); 
        return Json(from m in output where m.GetType().GetProperty("Code").GetValue(m).ToString().Contains(code) select m.GetType().GetProperty("Code").GetValue(m).ToString()); 
    } 
    [HttpPost] 
public ActionResult GetCodeName(string id, string codeName, string mPara) 

    var TblSet = Core.CoreCommon.GetTableData(id); 
    var output = TblSet.AsQueryable().ToListAsync().Result.ToList(); 
    Dal.TFAT_WEBERPEntities context = new Dal.TFAT_WEBERPEntities(); 
    string UserName = ""; 
    string unitdata = ""; 
    string Product = ""; 
    if (mPara == "C") 
    { 
        var query = (from m in output where m.GetType().GetProperty("Code").GetValue(m).ToString().Contains(codeName) select m.GetType().GetProperty("Name").GetValue(m).ToString()); 
        if (id == "ItemMaster") 
        { 
            var query1 = (from m in output where m.GetType().GetProperty("Code").GetValue(m).ToString().Contains(codeName) select m.GetType().GetProperty("Unit").GetValue(m).ToString()); 
            var NewQuery = (from c in output where c.GetType().GetProperty("Code").GetValue(c).ToString().Contains(codeName) select c.GetType().GetProperty("Name").GetValue(c).ToString()); 
            if (query1 != null) 
            { 
                unitdata = query1.First().ToString(); 
            } 
            if (NewQuery != null) 
            { 
                Product = NewQuery.First().ToString(); 
            } 
        } 
        if (query != null) 
        { 
            UserName = query.First().ToString(); 
        } 
    } 
    else 
    { 
        var query = (from m in output where m.GetType().GetProperty("Name").GetValue(m).ToString().Contains(codeName) select m.GetType().GetProperty("Code").GetValue(m).ToString()); 
        if (query != null) 
        { 
            UserName = query.First().ToString(); 
        } 
    } 
    return Json(new 
    { 
        UserName, 
        unitdata, 
        Product 
    }); 
    // return Content(UserName); 

Common Class-- -- -- -- -- -- -- -- -- - public class CoreCommon 

    public static object GetTableObject(string TableName) 
    { 
        Type mType = BuildManager.GetType(string.Format("TFATERPWebApplication.Dal.{0}", TableName), true); 
        return System.Activator.CreateInstance(mType); 
    } 
    public static Type GetTableType(string TableName) 
    { 
        return BuildManager.GetType(string.Format("TFATERPWebApplication.Dal.{0}", TableName), true); 
    } 
    public static DbSet GetTableData(string tablename) 
    { 
        var mType = BuildManager.GetType(string.Format("TFATERPWebApplication.Dal.{0}", tablename), true); 
        TFAT_WEBERPEntities ctx = new TFAT_WEBERPEntities(); 
        return ctx.Set(mType); 
    } 
    public static string GetString(string[] col) 
    { 
        StringBuilder sb = new StringBuilder(); 
        foreach(string s in col) 
        { 
            sb.Append(s); 
            sb.Append(","); 
        } 
        return sb.ToString().Substring(0, sb.Length - 1); 
    } 

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 Registering Custom Directories For Views In ASP.NET MVC?

clock October 11, 2016 20:54 by author Peter

In this post, I will show you how to Registering Custom Directories For Views In ASP.NET MVC 6. In ASP.NET MVC by default or convention is when we create application, our Views reside in Views directory for our Controller actions. For Example, by default it create Home controller with Index action, and if we see in Solution Explorer in Views directory we can see directory Views, Home, then Index.cshtml and we have it's action like the following code snippet:

    publicclassHomeController: Controller 
    { 
        public ActionResult Index() 
        { 
            return View(); 
        } 
    } 

And we have this action's Views in Views folder as in the following screen:

Now by default it will first look for Index.cshtml file in Views/Home folder and if it is unable to find it there then it will find in View/Shared folder. If it do not find there, then an exception will be thrown that view file is not found. Here is the exception text which is thrown:

The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
    ~/Views/Home/Index.aspx
    ~/Views/Home/Index.ascx
    ~/Views/Shared/Index.aspx
    ~/Views/Shared/Index.ascx
    ~/Views/Home/Index.cshtml
    ~/Views/Home/Index.vbhtml
    ~/Views/Shared/Index.cshtml
    ~/Views/Shared/Index.vbhtml


See:

The same is the case for partial view when we call return PartialView(), it first looks in the respective controller's Views/Home directory in the case of HomeController and in case of failure it looks in the View/Shared folder.

Now what if we had made a separate directory for partial views in my Views folder and Shared folder like:

Views/Home/Partials and Views/Shared/Partial then we have to tell the ViewEngineto look in that directory as well by writing the following code in Gloabl.asaxfileinApplication_Startevent.

For example, we have this code and we are returning _LoginPartial.cshtml from Index action of HomeController, now what will happen it will look in View/Home directory first and in failure it will look in View/Shared, but this time we have my partial views in separate directory named Partial for every controller and for shared as well, In this case HomeController partial views are in Views/Home/Partials and in Views/Shared/Partials:

    publicclassHomeController: Controller 
    { 
        public ActionResult Index() 
        { 
            return View(); 
        } 
    } 


In this case also we will get the same exception as Engine will not be able to find the View file _LoginPartial.cshtml.
 
The beauty of asp.net mvc framework is the  extensiblity which you can do according to your needs and business requirements, one of them is that  if you want your own directories structure for organizing your views you can register those directories with razor view engine, doing that will make your life easy as you will not have to specify fully qualified path of the view, as razor will know that it needs to look for the view in those directories as well which you have registered with it.
 
So what we have to do is to register this directory pattern in the application so that every time we call any View it should look in those directories as well in which we have placed the View files. So here is the code for that.

    publicclassMvcApplication: System.Web.HttpApplication 
    { 
        protectedvoidApplication_Start() 
        { 
            AreaRegistration.RegisterAllAreas(); 
            WebApiConfig.Register(GlobalConfiguration.Configuration); 
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
            RouteConfig.RegisterRoutes(RouteTable.Routes); 
            BundleConfig.RegisterBundles(BundleTable.Bundles); 
            AuthConfig.RegisterAuth(); 
            RazorViewEnginerazorEngine = ViewEngines.Engines.OfType < RazorViewEngine > ().FirstOrDefault(); 
            if (razorEngine != null) 
            { 
                varnewPartialViewFormats = new [] 
                { 
                    "~/Views/{1}/Partials/{0}.cshtml", 
                    "~/Views/Shared/Partials/{0}.cshtml" 
                }; 
                razorEngine.PartialViewLocationFormats = razorEngine.PartialViewLocationFormats.Union(newPartialViewFormats).ToArray(); 
            } 
        } 
    } 

Now whenever we will call return PartialView("SomeView") it will look in that Controller Views directory's subdirectory named Partials as well and in case it not finds there it will look in both Views/Shared and Views/Shared/Partials.

The same way you can register other directories or your own Custom directory structure if you need to, so doing this way you will not need to specify complete path for like return View("~/Views/Shared/Paritals/Index.cshtml"), instead you can just write then return View() if you want to load Index View and your action name is also Index which is being called, or if you want some other view to be rendered or some other action is invoked and you want to return Index view then you can write return View("Index").

 

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



About HostForLIFE

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

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in