European ASP.NET MVC 4 and MVC 5 Hosting

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

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



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: CRUD Example with ASP.NET MVC and SQL Server

clock September 6, 2016 19:44 by author Peter

Today, let me show you a CRUD example with ASP.NET MVC and SQL Server. This sample demonstrates how to use the CRUD (Create, Read, Update delete) record in MVC in Visual Studio. We are using SQL server database for this demo.

CrudController .cs
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using CurdMvc.Models; 
using System.Data; 
using System.Configuration; 
using System.Data.SqlClient; 
namespace CurdMvc.Controllers 

    public class CurdController: Controller 
    { 
        // 
        // GET: /Curd/ 
        SqlConnection con = new SqlConnection("Data Source=BITS-PC;Initial Catalog=TestDB;Integrated Security=True"); 
        public ActionResult Index() 
            { 
                List < CurdModel > lstRecord = new List < CurdModel > (); 
                SqlDataReader dr = null; 
                SqlCommand command = new SqlCommand("GetAllRecordSP", con); 
                command.CommandType = CommandType.StoredProcedure; 
                con.Open(); 
                dr = command.ExecuteReader(); 
                while (dr.Read()) 
                { 
                    CurdModel mdl = new CurdModel(); 
                    mdl.id = Convert.ToInt32(dr["Id"]); 
                    mdl.email = dr["Email"].ToString(); 
                    mdl.name = dr["Name"].ToString(); 
                    lstRecord.Add(mdl); 
                } 
                con.Close(); 
                return View(lstRecord); 
            } 
            [HttpGet] 
        public ActionResult Add(int ? id) 
            { 
                CurdModel mdl = new CurdModel(); 
                if (id != null) 
                { 
 
                    SqlCommand cmd = new SqlCommand("GetRecordByIdSP", con); 
                    cmd.CommandType = CommandType.StoredProcedure; 
                    cmd.Parameters.Add("@Id", SqlDbType.Int).Value = id; 
                    SqlDataReader dr = null; 
                    con.Open(); 
                    dr = cmd.ExecuteReader(); 
 
                    DataTable dt = new DataTable(); 
                    dt.Load(dr); 
 
                    mdl.id = Convert.ToInt32(dt.Rows[0][0].ToString()); 
                    mdl.name = dt.Rows[0][1].ToString(); 
                    mdl.email = dt.Rows[0][2].ToString(); 
                    con.Close(); 
                    return View(mdl); 
                } 
                return View(); 
            } 
            [HttpPost] 
        public ActionResult add(CurdModel model) 
        { 
            if (model.id > 0) 
            { 
                SqlCommand command = new SqlCommand("UpdateRecordByIdSP", con); 
                command.CommandType = CommandType.StoredProcedure; 
                // add parameters    
                command.Parameters.Add("@Name", SqlDbType.VarChar).Value = model.name; 
                command.Parameters.Add("@Email", SqlDbType.VarChar).Value = model.email; 
                command.Parameters.Add("@Id", SqlDbType.Int).Value = model.id; 
                con.Open(); 
                int iRetVal = command.ExecuteNonQuery(); 
 
 
            } 
            else 
            { 
                SqlCommand command = new SqlCommand("AddNewRecordSP", con); 
                command.CommandType = CommandType.StoredProcedure; 
                // add parameters    
                command.Parameters.Add("@Name", SqlDbType.VarChar).Value = model.name; 
                command.Parameters.Add("@Email", SqlDbType.VarChar).Value = model.email; 
                command.Parameters.Add("@Id", SqlDbType.Int).Direction = ParameterDirection.Output; 
                con.Open(); 
                int iRetVal = command.ExecuteNonQuery(); 
                con.Close(); 
            } 
            return RedirectToAction("Index", "curd"); 
        } 
 
        public ActionResult Delete(int id) 
        { 
            SqlCommand command = new SqlCommand("DeleteRecordByIdSP", con); 
            command.CommandType = CommandType.StoredProcedure; 
            // add parameters   
 
            command.Parameters.Add("@Id", SqlDbType.Int).Value = id; 
            con.Open(); 
            command.ExecuteNonQuery(); 
            con.Close(); 
 
            return RedirectToAction("Index", "curd"); 
        } 
        public ActionResult Details(int id) 
        { 
            CurdModel mdl = new CurdModel(); 
            SqlCommand cmd = new SqlCommand("GetRecordByIdSP", con); 
            cmd.CommandType = CommandType.StoredProcedure; 
            cmd.Parameters.Add("@Id", SqlDbType.Int).Value = id; 
            SqlDataReader dr = null; 
            con.Open(); 
            dr = cmd.ExecuteReader(); 
 
            DataTable dt = new DataTable(); 
            dt.Load(dr); 
 
            mdl.id = Convert.ToInt32(dt.Rows[0][0].ToString()); 
            mdl.name = dt.Rows[0][1].ToString(); 
            mdl.email = dt.Rows[0][2].ToString(); 
 
            con.Close(); 
            return View(mdl); 
 
        } 
    } 

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 ASP.NET Core 1.0 RC2 Hosting

clock June 4, 2016 01:07 by author Peter

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 ASP.NET Core 1.0 RC2 hosting in their entire servers environment.

ASP.NET is Microsoft's dynamic website technology, enabling developers to create data-driven websites using the .NET platform and the latest version is 5 with lots of awesome features. ASP.NET Core 1.0 RC2 is a lean .NET stack for building modern web apps. Microsoft built it from the ground up to provide an optimized development framework for apps that are either deployed to the cloud or run on-premises. It consists of modular components with minimal overhead.

A key change that occurred between RC1 and RC2 is the introduction of the .NET command-line interface.  This tool replaces the dnvm, dnx, and dnu utilities with a single tool that handles the responsibilities of these tools. In RC1 an ASP.NET application was a class library that contained a Startup.cs class. When the DNX toolchain run your application ASP.NET hosting libraries would find and execute the Startup.cs, booting your web application. Whilst the spirit of this way of running an ASP.NET Core application still exists in RC2, it is somewhat different. As of RC2 an ASP.NET Core application is a .NET Core Console application that calls into ASP.NET specific libraries. What this means for ASP.NET Core apps is that the code that used to live in the ASP.NET Hosting libraries and automatically run your startup.cs now lives inside a Program.cs.

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 ASP.NET Core 1.0 RC2 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 ASP.NET Core 1.0 RC2 hosting installation to all their new and existing customers. The customers can simply deploy their ASP.NET Core 1.0 RC2 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 ASP.NET Core 1.0 RC2 Hosting can be viewed here http://hostforlife.eu



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

clock March 30, 2016 23:25 by author Peter

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

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

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

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

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

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

}


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

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

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


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

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



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

clock February 18, 2016 19:59 by author Peter

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

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

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

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



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

clock February 11, 2016 20:21 by author Peter

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

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

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

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

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

    public enum HttpMethods
    {
        GET,POST
    }


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

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



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

clock February 4, 2016 20:38 by author Peter

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

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


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

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

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


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

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

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



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