European ASP.NET MVC Hosting

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

ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Implement RoleManager in ASP.NET MVC 5?

clock December 11, 2015 00:34 by author Peter

There is something great included in ASP.NET MVC 5 that looks underutilized except by the ASP.NET MVC team. the rest of us seem to be ignoring it, that is apparent when gazing the solutions on StackOverflow (and blogs) for questions like “how do i use roles with ASP.NET MVC 5?” once I check out how identity is implemented in mvc, what stands out is that the dependency injection. And, that dependency injection seems to be missing in the answers to how to implement roles. Dependency is a great tool, it’s built into the OWIN implementation, so why not use it?

To implement the role manager in MVC 5, look for a file in App_Start called IdentityConfig.cs. If you don’t have this file, look for the file that contains the implementation of your ApplicationUserManager (derived from UserManager) and ApplicationSignInManager (derived from SignInManager). At the bottom of that file, within the namespace, add the subsequent class definition:
public class ApplicationRoleManager : RoleManager<IdentityRole>
{
public ApplicationRoleManager(IRoleStore<IdentityRole, string> store) : base(store)
{
}

public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
{
    var roleStore = new RoleStore<IdentityRole>(context.Get<AuthenticationDbContext>());
    return new ApplicationRoleManager(roleStore);
}
}


There are a couple of prototypes for the produce method. during this case, I needed to urge the database context from the OWIN context, so I used the more elaborate overload. If you don’t want to do that, you can use the Create(Func&lt;T&gt;) overload, which doesn’t take any parameters.  Now, to make sure OWIN knows about your ApplicationRoleManager class, go the ConfigureAuth method in your Startup partial class implementation in Startup.Auth.cs (also in App_Start).  Or, you'll also put what I’m getting ready to show you in the Configuration method of the OWIN startup class. This class is sometimes called Startup.cs and you’ll find it in the same directory as the root web.config.
public void ConfigureAuth(IAppBuilder app)
{
   // Configure the db context, user manager and signin manager to use a single instance per request
   app.CreatePerOwinContext(AuthenticationDbContext.Create);
   app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
   app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
   app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
   …
}

See how I just stuck that line for ApplicationRoleManager there next to the other authentication delegate registrations?  Now, we can just inject the role manager right into the AccountController or whatever other controller we need.
public AccountController(
    SendMailManager emailManager,
    ApplicationUserManager userManager,
    ApplicationSignInManager signInManager,
    ApplicationRoleManager roleManager)
{
    this.MailManager = emailManager;
    this.RoleManager = roleManager;
    this.SignInManager = signInManager;
    this.UserManager = userManager;
}

As you can see, I have already used the dependency injection to insert my own mail manager. AccountController should already be set up with this kind of structure. If it’s not, though, simply changing your constructor to look like this will cause MVC to inject those dependencies into your controller. Then, all you have to do is create a property to hold that ApplicationRoleManager thing and you’re all set!
private ApplicationRoleManager roleManager;
public ApplicationRoleManager RoleManager
{
    get
    {
        return this.roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
    }
    private set { this.roleManager = value; }
}

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.



European ASP.NET MVC 5 Hosting - UK :: Creating Custom Scaffold Templates in ASP.NET MVC

clock November 27, 2015 18:59 by author Scott

Microsoft provides a powerful scaffolding engine for models in ASP.NET MVC applications that use Entity Framework. Scaffolding relieves web developers from the mundane task of writing the create, read, update, and delete (CRUD) code over and over again. The scaffolding engine uses T4 templates to generate basic controllers and views for models. However, scaffolded code is just a starting point, since it often needs to be customized to meet specific business requirements or satisfy specific design patterns.

In this blog post, I’ll provide a walkthrough on how to create project-specific custom scaffold templates for ASP.NET MVC. This can be a huge time-saver in applications with a large number of controllers and views. I will use Visual Studio 2013, ASP.NET MVC 5, Entity Framework 6, and C#.

SETUP

To get started, create a new ASP.NET MVC web application and add a simple Product model with the properties shown below and build the project.

namespace CustomScaffoldingDemo.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public bool IsDeleted { get; set; }
        public DateTime CreatedDate { get; set; }
        public DateTime UpdatedDate { get; set; }
    }
}

SCAFFOLDING CONTROLLER AND VIEWS

First, let’s use default templates to scaffold a controller and CRUD views for the Product model so we can review the results. To do so, right-click the Controllers folder in Solution Explorer and click Add New Scaffolded Item. In the Add Scaffold dialog, choose the MVC 5 Controller with views, using Entity Framework. On the Add Controller dialog, create a new data context and choose appropriate options that serve as parameters for the scaffolding engine. Then hit the Add button.

The scaffolding engine will use the default T4 templates to generate code for the controller and five views and add them to the appropriate folders. At this point you have full CRUD functionality for the Product model and can run the application.

As you review the generated code, you may notice that the scaffolding engine is intelligent enough to treat the Product ID properly by not scaffolding the editor for this property on the Create or Edit forms. You may also realize that the default templates do not meet the functional specification or your desired design patterns. For example, you may want to achieve the following:

–  Created Date and Updated Date properties should be set automatically by the system on create or update action respectively, and thus should not be editable on the Create and Edit views.
–  Products should be soft-deleted, so the Delete action of the Product controller must be changed to set the IsDeleted property and updating the Product instead of deleting it from the database. Index action should only return Products with IsDeleted set to false.
–  None of the views should display the IsDeleted property.
–  Views should use @ViewBag.Title as the page header instead of the view name. 
–  You may be using a Unit of Work pattern, so all calls to save changes to the database may need to be tweaked. 

You can manually make changes to the generated code, which has several drawbacks, including:

–  Typically, you would want most, if not all, controllers and views to be consistent across all models in your application. Making similar manual changes to controllers and views for all models is not an efficient approach.
–  When you make changes to a model, you will either have to scaffold these files again and lose your manual changes or manually update all views to match the updated model.

The best way to avoid manual changes and enforce consistency is to customize the scaffold templates.

CUSTOMIZING SCAFFOLD TEMPLATES

The original T4 templates used by the scaffolding engine are located in this folder: %programfiles%\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Microsoft\Web\Mvc\Scaffolding\Templates.

While you can directly edit these templates, this will affect scaffolding for all future projects, which is not recommended. Instead, you can create project-specific copies of these templates so you can customize them. To do so, copy these templates into your MVC project’s CodeTemplates folder, following the same sub-folder structure. You only need to copy either C# or VB.NET templates, based on your project. The template filenames include the language they use. The convention is that the scaffolding engine uses the templates in the CodeTemplates project folder, if one exists, instead of the global templates.

Now you can modify these custom scaffold templates, which would affect scaffolded code only for this project. T4 templates are simply text files and can be edited directly in Visual Studio. Unfortunately, Visual Studio 2013 does not include a good T4 editor—there’s no syntax highlighting or IntelliSense. Fortunately, there are some third party add-on products that provide this functionality. Below is a screenshot of how the templates look in Visual Studio 2013. You can see I modified the header on line 26 to use @ViewBag.Title instead of the view name. 

&lt;#@ template language="C#" HostSpecific="True" #&gt;
&lt;#@ output extension=".cshtml" #&gt;
&lt;#@ include file="Imports.include.t4" #&gt;
@model &lt;#= ViewDataTypeName #&gt;
&lt;#
// The following chained if-statement outputs the file header code and
// markup for a partial view, a view using a layout page, or a regular view.
if(IsPartialView) {
#&gt; 

&lt;#
} else if(IsLayoutPageSelected) {
#&gt; 

@{
    ViewBag.Title = "&lt;#= ViewName#&gt;";
&lt;#
if (!String.IsNullOrEmpty(LayoutPageFile)) {
#&gt;
    Layout = "&lt;#= LayoutPageFile#&gt;";
&lt;#
}
#&g
t;
}

@ViewBag.Title

To learn more about scaffolding check out this walkthrough from Microsoft. To learn more about T4 templates in general, start by reading this MSDN article



European ASP.NET MVC 5 Hosting :: How to Use AngularJS in ASP.NET MVC

clock November 12, 2015 20:18 by author Scott

In this short tutorial, I will show how to use AngularJS in ASP.NET MVC. I hope that you enjoy this short tutorial and this is helpful.

Application Inception

While Angular is a framework for the modern Single Page App, I have found that a lot of our MVC applications call for a collection of these “ng-apps”. In this instance they typically don’t include the client side routing.

Please See Sample Application

The image to the right is the file structure for a sample airplane scheduling app. There are three sections:

  Home (simple js) - A simple calendar showing flights
  Details (angular) - Information about a single flight
  Manage (angular) - A place for settings, pilots, etc...

Bundle Configuration

While asset bundling is a great feature of ASP.Net, it is easy to get carried away. When I came on there were a lot of projects that just included all the js files for the entire application in a single ScriptBundle. This was one of the first places I set my sights.

I decided that a lot of the services would be shared, so they could go in their own Angular module and in their own ASP Bundle. Then each mini-app could get it’s own module and bundle. Lets take a look at theBundleConfiguration.cs file.

using System.Web.Optimization;

namespace Jobney.App.Web
{
    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/js-base").Include(
                        "~/Scripts/libs/jquery-{version}.js",
                        "~/Scripts/libs/bootstrap.js",
                        "~/Scripts/libs/select2.js",
                        "~/Scripts/libs/bootstrap-datepicker.js",
                        "~/Scripts/libs/respond.js",
                        "~/Scripts/libs/lodash.js",
                        "~/Scripts/endless.js"
                        ));

            bundles.Add(new ScriptBundle("~/bundles/ng-base").Include(
                        "~/Scripts/libs/angular/angular.js",
                        "~/Scripts/libs/angular/ui-router.js",
                        "~/Scripts/libs/angular/ui-bootstrap-custom-0.9.0.js",
                        "~/Scripts/libs/angular/ui-bootstrap-custom-tpls-0.9.0.js",
                        "~/Scripts/libs/angular/angular-animate.js",
                        "~/Scripts/libs/angular/toaster.js"
                        ));

            bundles.Add(new ScriptBundle("~/bundles/ng-shared-services")
                .IncludeDirectory("~/Scripts/apps/shared/", "*.js"));

            bundles.Add(new ScriptBundle("~/bundles/ng-manage-app")
                .IncludeDirectory("~/Scripts/apps/manage/","*.js"));

            bundles.Add(new ScriptBundle("~/bundles/ng-tripinfo-app")
                .Include(
                    "~/Scripts/libs/jquery-ui.js",
                    "~/Scripts/libs/angular/sortable.js",
                    "~/Scripts/libs/angular/select2.js",
                    "~/Scripts/libs/angular/ngAutocomplete.js"
                )
                .IncludeDirectory("~/Scripts/apps/tripinfo/", "*.js"));

            bundles.Add(new StyleBundle("~/Content/css/base").Include(
                      "~/Content/css/bootstrap.css",
                      "~/Content/css/datepicker3.css",
                      "~/Content/css/select2.css",
                      "~/Content/css/toaster.css",
                      "~/Content/css/select2-bootstrap.css",
                      "~/Content/css/font-awesome.css"
                    ));
            bundles.Add(new StyleBundle("~/Content/css/custom").Include(
                      "~/Content/css/endless.css",
                      "~/Content/css/endless-skin.css",
                      "~/Content/css/site.css"));
        }
    }
}

Then using the bundles, say in the manage app, it would look like this:

@model Jobney.Casm.Web.Models.ManageDataBootstrapper
<div data-ng-app="Jobney.Casm.ManageApp" data-ng-controller="ManageAppCtrl">
    <ul class="tab-bar grey-tab">
        <!-- content here -->
    </ul>

    <div data-ui-view></div>
</div>

@section scripts
{
    <!-- Start ng-base -->
    @Scripts.Render("~/bundles/ng-base")

    <!-- Start ng-shared-services -->
    @Html.Partial("_SharedServices")

    <!-- Start ng-manage-app -->
    @Html.Partial("_ManageAppSetup", Model)
}

Services Need Data And Data Needs Urls

As an ASP.Net MVC developer, you are probably used to letting the routing engine create urls for you when you need them. And why not? Who knows what crazy routing constraints the client/pm/other developers decided needed to be in your application. And with Razor helpers, this is pretty easy. Angular shouldn’t have to try hard to figure out those rules. So how do we combine these two worlds?

@section scripts
{
    app.constant('RouteConfig', {
        base: '@Url.Content("~/")',
        project: {
            all: '@Url.Action("All", "Project")',
            details: '@Url.Action("Details", "Project")',
            post: '@Url.Action("Post", "Project")'
        },
        vendor: {
            category: '@Url.Action("GetByCategory", "Vendor")',
            details: '@Url.Action("GetById", "Vendor")',
            getProductRating: '@Url.Action("GetByProduct", "Rating")'
        },
        resolve: function (url) {
            return this.base + url;
        }
    });
}

Such http. Many calls.

In the manage app we are going to need some data. When the situation calls for it, I don’t mind sending that data down with the app. I think I took this idea from John Papa or one of those PluralSight authors. Basically, I just use JSON.Net to serialize my dataset on the page. Let’s take a look at it.

@model Jobney.Casm.Web.Models.ManageDataBootstrapper

<script>
    (function () {
        'use strict';

        var app = angular.module('Jobney.Casm.ManageApp', [
            'ui.router',
            'ui.bootstrap',
            'Jobney.Casm.SharedServices'
        ]);

        app.factory('BootstrappedData', [function() {
            var service = {};

            service.pilots = @Html.Raw(Model.Pilots);
            service.passengers = @Html.Raw(Model.Passengers);
            service.airplanes = @Html.Raw(Model.Airplanes);
            service.settings = @Html.Raw(Model.Settings);

            return service;
        }]);       

    })();
</script>

@Scripts.Render("~/bundles/ng-manage-app")

 



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Moving Your Data From ListBox to other ListBox with JQuery in ASP.NET MVC

clock October 30, 2015 00:48 by author Peter

Now, we will discussed about Moving Your Data From ListBox to other ListBox with JQuery in ASP.NET MVC. A list box is a graphical control element that allows the user to select one or more items from a list contained within a static, multiple line text box. First step, write the following code:
namespace Mvc2.Controllers
{
public class MovieController : Controller
{
    public ActionResult MoveDateinListBox()
  {
      return View();
  }
  }
}

In View
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
MoveDateinListBox
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h5>
    MVC:How to Move data between two ListBoxes using JQuery</h5>
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
<script language="javascript" type="text/javascript">
    $(function () {
        $("#MoveToRight,#MoveToLeft").click(function (event) {
            var id = $(event.target).attr("id");
            var selectFrom = id == "MoveToRight" ? "#SelectLeftItem" : "#SelectRightItem";
            var moveTo = id == "MoveToRight" ? "#SelectRightItem" : "#SelectLeftItem";
            var selectedItems = $(selectFrom + " option:selected").toArray();
            $(moveTo).append(selectedItems);
            selectedItems.remove;
        });
    });
</script>
<form method="get" action="" runat="server">
 <select id="SelectLeftItem" multiple="multiple" style="height: 100px">
    <option value="1">ASP.NET</option>
    <option value="2">C#.NET</option>
    <option value="3">SQL Server</option>
    <option value="4">VB.NET</option>
</select>
<input id="MoveToRight" type="button" value=" >> " style="font-weight: bold" />
<input id="MoveToLeft" type="button" value=" << " style="font-weight: bold" />
<select id="SelectRightItem" multiple="multiple" style="height: 100px">
    <option value="1">MVC</option>
    <option value="2">WCF</option>
    <option value="3">WPF</option>
    <option value="4">Silverlight</option>
</select>
</form>
</asp:Content>


And here 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 France - HostForLIFE.eu :: How To Clear Thumbnails After It Has Uploaded

clock October 24, 2015 00:23 by author Rebecca

Sometimes, we need to clear the thumbnails from dropzone.js after the file is uploaded. In this article, I will tell you how to do it.

You need to call addedfile function once the file is uploaded. After that, you have to to generate remove button for the thumbnail.

Look at this example code:

Step 1: File Upload response from the server

Dropzone.options.dropzoneForm = {
maxFiles: 2,
init: function () {
this.on("maxfilesexceeded", function (data) {
var res = eval('(' + data.xhr.responseText + ')');

});
this.on("addedfile", function (file) {

Step 2: Create the remove/clear button

var removeButton = Dropzone.createElement("
<button>Remove file</button>
");

Step 3: Capturing the Dropzone.js instance as closure

var _this = this;

Step 4: Listen to the click event

removeButton.addEventListener("click", function (e) {

Make sure the button click doesn't submit the form:

e.preventDefault();
e.stopPropagation();

Step 5: Remove the file preview

_this.removeFile(file);

If you want to the delete the file on the server as well, you can do the AJAX request here:

});

Step 6: Add the button to the file preview element

file.previewElement.appendChild(removeButton);
});
}
};

That's it! Simple right?

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 Italy - HostForLIFE.eu :: How to Use Dapper.NET ORM in ASP.NET MVC ?

clock October 22, 2015 23:36 by author Peter

In this tutorial, let me explain you how to use Dapper.NET ORM in ASP.NET MVC 6. Dapper is a simple object mapper for .NET. Dapper is a file you can drop in to your project that will extend your IDbConnection interface. A key feature of dapper is performance. the subsequent metrics show how long it takes to execute five hundred select statements against a db and map the data returned to objects.

Now,  Install dapper using Nuget Package Manager
PM> Install-Package Dapper

After that, Create a project in ASP.NET MVC and then Add a folder named Dapper inside it as you can see on the following picture:

Next step: Create User and Address classes
public class Address
{
public int AddressID { get; set; }
public int UserID { get; set; }
public string AddressType { get; set; }
public string StreetAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
}

public class User
{
public User()
{
this.Address = new List<Address>();
}

public int UserID { get; set; }

public string FirstName { get; set; }

public string LastName { get; set; }

public string Email { get; set; }

public List<Address> Address { get; set; }
}

Now Create IUserRepository.cs interface  and UserRepository.cs classes for data access.
public interface IUserRepository
{
List < User > GetAll();
User Find(int id);
User Add(User user);
User Update(User user);
void Remove(int id);
User GetUserInformatiom(int id);
}
public class UserRepository : IUserRepository
{
private IDbConnection _db = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
public List<User> GetAll()
{
return this._db.Query<User>("SELECT * FROM Users").ToList();
}

public User Find(int id)
{
return this._db.Query<User>("SELECT * FROM Users WHERE UserID = @UserID", new { id }).SingleOrDefault();
}

public User Add(User user)
{
var sqlQuery = "INSERT INTO Users (FirstName, LastName, Email) VALUES(@FirstName, @LastName, @Email); " + "SELECT CAST(SCOPE_IDENTITY() as int)";
var userId = this._db.Query<int>(sqlQuery, user).Single();
user.UserID = userId;
return user;
}
public User Update(User user)
{
var sqlQuery =
    "UPDATE Users " +
    "SET FirstName = @FirstName, " +
    "    LastName  = @LastName, " +
    "    Email     = @Email " +
    "WHERE UserID = @UserID";
this._db.Execute(sqlQuery, user);
return user;
}

public void Remove(int id)
{
throw new NotImplementedException();
}

public User GetUserInformatiom(int id)
{
using (var multipleResults = this._db.QueryMultiple("GetUserByID", new { Id = id }, commandType: CommandType.StoredProcedure))
{
    var user = multipleResults.Read<User>().SingleOrDefault();

    var addresses = multipleResults.Read<Address>().ToList();
    if (user != null && addresses != null)
    {
        user.Address.AddRange(addresses);
    }

    return user;
}
}
}


Now use the above repository in the HomeController.cs
Create an instance for UserRepository class
private IUserRepository _repository = new UserRepository();

For Get All User write the following code:
public ActionResult Index()
{
return View(_repository.GetAll());
}

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 France - HostForLIFE.eu :: How to Avoid XSS (Cross Site-Scripting) in MVC Project

clock October 16, 2015 11:09 by author Rebecca

Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications. XSS enables attackers to inject client-side script into web pages viewed by other users. Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise trusted web sites. In this article, I will show you how to avoid XSS while allowing only the HTML that you want to accept. In example, only <b> and <u> tags.

Firstly, let's filter the user input, and accept only <b></b> and <u></u> tags.

Step 1: Disables input validation

Step 2: Encodes all the input that is coming from the user

Step 3: Replace the encoded html with the HTML elements that you want to allow

Here is the full code snippet:

[HttpPost]
// Input validation is disabled, so the users can submit HTML
[ValidateInput(false)]
public ActionResult Create(Comment comment)
{
    StringBuilder sbComments = new StringBuilder();
   
    // Encode the text that is coming from comments textbox
    sbComments.Append(HttpUtility.HtmlEncode(comment.Comments));
   
    // Only decode bold and underline tags
    sbComments.Replace("&lt;b&gt;", "<b>");
    sbComments.Replace("&lt;/b&gt;", "</b>");
    sbComments.Replace("&lt;u&gt;", "<u>");
    sbComments.Replace("&lt;/u&gt;", "</u>");
    comment.Comments = sbComments.ToString();

    // HTML encode the text that is coming from name textbox
    string strEncodedName = HttpUtility.HtmlEncode(comment.Name);
    comment.Name = strEncodedName;

    if (ModelState.IsValid)
    {
        db.Comments.AddObject(comment);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(comment);
}

This is just one example. Only filtering the user input can't guarantee XSS elimination. XSS can happen in different ways and forms.

Hope you did it!

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



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Use Different Actions to Show A Single View

clock October 2, 2015 12:39 by author Rebecca

In this article, you will learn how use different actions to show a single view in ASP.NET MVC.  It’s common situation in project development where you don’t want to create view for each and every action of certain controller. In this situation, we have to use concept of shared view. The solution is very simple, you just have to keep the view in shared folder. Like below:

Now, The question is why need to keep in shared folder? The reason is when you run any controller, by default it check its own directory or shared directory. Every controller will look in shared directory, if it not available in it’s own directory. Let’s have a look on below code, let's create very simple controller class:

sing System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace MVC3.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Action1()
        {
          
            ViewBag.Controller = "Action1";
            return View("_Common");
        }
        public ActionResult Action2()
        {
          
            ViewBag.Controller = "Action2";
            return View("_Common");
        }
 
    }

Both Action1() and Action2() is calling _Common view and as the view is placed in shared folder, both can able to access. Before calling to view we are assigning action name in ViewBag. From view we can detect which action has invoked it. Here is code for view:

<%@ Page
Language="C#"
Inherits="System.Web.Mvc.ViewPage<MVC3.Models.customer>"
%>
<!DOCTYPE html>
<html>
<head runat="server">
    <title>_Common</title>
</head>
<body>
    <div>
        <% var ActionName = ViewBag.ActionName; %>
        <% if (ActionName == "Action1")
           {%>
          
              This view is called from Action 1
           <%}
           else
           {%>
          
              This view is Called from Action 2
           <%} %>
    </div>
</body>
</html>

 
Here is the output:

Now, the other question my show “Is it possible to call one view from different controller”? Yes, you can call. In below example, you will see how to do that.

You can call one view from different controller. This is your first controller Home1:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace MVC3.Controllers
{
    public class Home1Controller : Controller
    {
        public ActionResult Action()
        {
          
            ViewBag.Controller = "Home1";
            return View("_Common");
        }
    }
}

And here is the output.



And for the Home2 controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace MVC3.Controllers
{
    public class Home2Controller : Controller
    {
        public ActionResult Action()
        {
          
            ViewBag.Controller = "Home2";
            return View("_Common");
        }
 
    }
}

Here is the output:

 

It’s clear that both Action() (they are in different controller) are calling same view.

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




ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Show SQL Server Database Update in ASP.NET MVC

clock September 22, 2015 12:19 by author Rebecca

In this post, you will learn how to display real time updates from the SQL Server by using SignalR and SQL Dependency in ASP.NET MVC.

The following are the steps that we need to enable in the SQL Server first.

Step 1- Enable Service Broker on the database

The following is the query that need to enable the service broker

ALTER DATABASE BlogDemos SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE ;


Step 2 - Add Connection string to the Web.Config file

<add name=”DefaultConnection” connectionString=”Server=servername;Database=databasename;User Id=userid;Password=password;” providerName=”System.Data.SqlClient” />
 

Step 3 - Enable SQL Dependency

In Global.asax start the SQL Dependency in App_Start() event and Stop SQL dependency in the Application_End() event

public class MvcApplication : System.Web.HttpApplication
    {
        string connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            GlobalConfiguration.Configure(WebApiConfig.Register);
            //Start SqlDependency with application initialization
            SqlDependency.Start(connString);
        }

        protected void Application_End()
        {
            //Stop SQL dependency
            SqlDependency.Stop(connString);
        }
    }

Step 4 - Install SignalR from the nuget

Run the following command in the Package Manager Console:

Install-Package Microsoft.AspNet.SignalR

Step 5 - Create SignalR Hub Class

Create MessagesHub class in the Hubs folder:

public class MessagesHub : Hub
    {
        private static string conString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
        public void Hello()
        {
            Clients.All.hello();
        }


        [HubMethodName("sendMessages")]
        public static void SendMessages()
        {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MessagesHub>();
            context.Clients.All.updateMessages();
        }  
    }

Step 6 - Get the  Data from the Repository

Create MessagesRepository to get the messages from the database when data is updated.

public class MessagesRepository
    {
        readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

        public IEnumerable<Messages> GetAllMessages()
        {
            var messages = new List<Messages>();
            using (var connection = new SqlConnection(_connString))
            {
                connection.Open();
                using (var command = new SqlCommand(@"SELECT [MessageID], [Message], [EmptyMessage], [Date] FROM [dbo].[Messages]", connection))
                {
                    command.Notification = null;

                    var dependency = new SqlDependency(command);
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

                    if (connection.State == ConnectionState.Closed)
                        connection.Open();

                    var reader = command.ExecuteReader();

                    while (reader.Read())
                    {
                        messages.Add(item: new Messages { MessageID = (int)reader["MessageID"], Message = (string)reader["Message"], EmptyMessage =  reader["EmptyMessage"] != DBNull.Value ? (string) reader["EmptyMessage"] : "", MessageDate = Convert.ToDateTime(reader["Date"]) });
                    }
                }
             
            }
            return messages;
          
           
        }

        private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            if (e.Type == SqlNotificationType.Change)
            {
                MessagesHub.SendMessages();
            }
        }
    }

Step 7 - Register SignalR at startup class

Add the following code:

app.MapSignalR();

Step 8 - View Page

Create div messagesTable that will append the table data from the database:

<div class="row">
    <div class="col-md-12">
       <div id="messagesTable"></div>
    </div>
</div>

Now Add the SignalR related scripts in the page:

<script src="/Scripts/jquery.signalR-2.1.1.js"></script>
 <!--Reference the autogenerated SignalR hub script. -->
    <script src="/signalr/hubs"></script>

<script type="text/javascript">
    $(function () {
        // Declare a proxy to reference the hub.
        var notifications = $.connection.messagesHub;
      
        //debugger;
        // Create a function that the hub can call to broadcast messages.
        notifications.client.updateMessages = function () {
            getAllMessages()
          
        };
        // Start the connection.
        $.connection.hub.start().done(function () {
            alert("connection started")
            getAllMessages();
        }).fail(function (e) {
            alert(e);
        });
    });


    function getAllMessages()
    {
        var tbl = $('#messagesTable');
        $.ajax({
            url: '/home/GetMessages',
            contentType: 'application/html ; charset:utf-8',
            type: 'GET',
            dataType: 'html'
        }).success(function (result) {
            tbl.empty().append(result);
        }).error(function () {
           
        });
    }
</script>

Step 9 - Create Partial View Page

Create a partial view _MessagesList.cshtml that returns all the messages.

@model IEnumerable<SignalRDbUpdates.Models.Messages>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>@Html.DisplayNameFor(model => model.MessageID)</th>
        <th>
            @Html.DisplayNameFor(model => model.Message)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.EmptyMessage)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.MessageDate)
        </th>
       
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.MessageID)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Message)
        </td>
        <th>
            @Html.DisplayFor(modelItem => item.EmptyMessage)
        </th>
        <td>
            @Html.DisplayFor(modelItem => item.MessageDate)
        </td>
       
    </tr>
}
</table>

Step 10 - Set Up the Database

Create the database called blogdemos and run the following script:

USE [BlogDemos]
GO

/****** Object:  Table [dbo].[Messages]    Script Date: 10/16/2014 12:43:55 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Messages](
    [MessageID] [int] IDENTITY(1,1) NOT NULL,
    [Message] [nvarchar](50) NULL,
    [EmptyMessage] [nvarchar](50) NULL,
    [Date] [datetime] NULL,
 CONSTRAINT [PK_Messages] PRIMARY KEY CLUSTERED
(
    [MessageID] 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

ALTER TABLE [dbo].[Messages] ADD  CONSTRAINT [DF_Messages_Date]  DEFAULT (getdate()) FOR [Date]
GO

Step 11 - Run the project

Whenever data is inserted into the table the dependency_OnChange method will fire.

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 Italy - HostForLIFE.eu :: How to create Multi-Select Dropdown With Checkbox in ASP.NET MVC?

clock September 14, 2015 06:18 by author Peter

Today, I will show you how to creat Multi-Select Dropdown With Checkbox in ASP.NET MVC.
1. MVC set Viewdata in controller inside save get method using foreach loop.

2. Within view write foreach loop for multiselect dropdown with checkboxlist. And now, write the following code:
<div id="divStudentlist" style="height: 100px; overflow: auto; border: solid; width: 150px;"> 
@foreach (var items in ViewData["Items"] as List 
<SelectListItem>) { 
    <table width="100%"> 
    <tr> 
        <td width="20px"> 
            <input type="checkbox" value="@items.Value" class="chkclass" /> 
        </td> 
        <td width="100px"> 
            @items.Text 
        </td> 
    </tr> 
    </table> 
    } 
</div> 

3. Now the question arises, how will you send your chosen items values to controller as a result of once you get the values into the controller, you'll be able to do something like save into database. therefore let’s perceive the subsequent jQuery code. Before that, you must place @Html.Hidden("idlist") within Ajax.BeginForm and currently write jQuery code as you can see below:
var idslist = ""; 
$("input:checkbox[class=chkclass]").each(function() { 
if ($(this).is(":checked")) { 
    var userid = $(this).attr("value"); 
    idslist = idslist + userid + ','; 

}); 
$("#idlist").val(idslist); 


4. Inside controller add/save post technique ought to have the subsequent parameter: (FormCollection frm) and then write the subsequent c# code:
string[] i1; 
string items = frm["idlist"]; 
if (items != null) { 
i1 = items.Split(new [] { 
    "," 
}, StringSplitOptions.RemoveEmptyEntries); 
for (int i = 0; i < i1.Length; i++) { 
    string s = i1[i]; /*Inside string type s variable should contain items values */ 

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