
December 11, 2015 00:34 by
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<T>) 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.


October 30, 2015 00:48 by
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.


October 22, 2015 23:36 by
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.


September 14, 2015 06:18 by
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.


September 7, 2015 12:36 by
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 4.6 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 4.6 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.
According to Microsoft officials, With the .NET Framework 4.6, you'll enjoy better performance with the new 64-bit "RyuJIT" JIT and high DPI support for WPF and Windows Forms. ASP.NET provides HTTP/2 support when running on Windows 10 and has more async task-returning APIs. There are also major updates in Visual Studio 2015 for .NET developers, many of which are built on top of the new Roslyn compiler framework. The .NET languages -- C# 6, F# 4, VB 14 -- have been updated, too.There are many great features in the .NET Framework 4.6. Some of these features, like RyuJIT and the latest GC updates, can provide improvements by just installing the .NET Framework 4.6.
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 4.6 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 4.6 hosting installation to all their new and existing customers. The customers can simply deploy their ASP.NET 4.6 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 4.6 Hosting can be viewed here http://hostforlife.eu/European-ASPNET-46-Hosting

August 6, 2015 09:09 by
Peter
In this article, we will learn how to create SignalR database update notifications using SQL dependency in ASP.NET MVC 6. The following are the steps that we want to enable within the SQL Server first.
1. Enable Service Broker on the database
The following is the query that require to enable the service broker:
ALTER DATABASE BlogDemos SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE;

2. Now Add Connection string to the Web.Config file and the following code:
<add name=”DefaultConnection” connectionString=”Server=servername;Database=databasename;User Id=userid;Password=password;” providerName=”System.Data.SqlClient” />
3. Next step, Enable the SQL Dependency
In Global.asax start the SQL Dependency in App_Start() event and Stop SQL dependency in the Application_End() event and write the following code:
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);
}
}
4. Install SignalR from the Nuget
Run the following command in the Package Manager Console
Install-Package Microsoft.AspNet.SignalR
5. And then, Make a SignalR Hub Class
Make 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();
}
}
6. Get the Data from the Repository
Make 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();
}
}
7. Next step, you must Register SignalR at startup class
Write the following code:
app.MapSignalR();
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.
getAllMessages is a function that return the partialview data and bind it into the messagesTable div.
<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>
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>
10. Set Up the Database
Create the database called blogdemos and run the following script:
USE [BlogDemos]
GO
/****** Object: Table [dbo].[Messages] ******/
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
11. Let's Run the project
When eve data is inserted into the table the dependency_OnChange method will fire.

July 14, 2015 09:22 by
Peter
In this tutorial, I will show you How to Bind & Sort Grid with Jquery in ASP.NET MVC 6. You can sort by clicking on column names & paging by selecting the page size and the click on arrows first arrow is to move to first page,click on arrows second arrow is to move to previous page,click on arrows third arrow is to move to next page and click on arrows fourth arrow is to move to last page. First step, you should create a MVC app and make model Users.cs. Now write the following code:

Model: Users.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.ComponentModel.DataAnnotations;
namespace MvcMovieStore.Models
{
public class Users
{
DataSet ds;
[Required]
[Display(Name = "ID")]
public int ID { get; set; }
[Required]
[Display(Name = "UserName")]
public string UserName { get; set; }
[Required]
[Display(Name = "Gender")]
public string Gender { get; set; }
[Required]
[Display(Name = "Country")]
public string Country { get; set; }
public DataTable GetUsers()
{
try
{
ds = new DataSet();
SqlConnection con = new qlConnection(System.Configuration.ConfigurationManager.
ConnectionStrings["con"].ConnectionString);
SqlDataAdapter sqlAda = new SqlDataAdapter("Select User_Id,UserName,Country,Gender from User_Details", con);
sqlAda.Fill(ds);
return ds.Tables[0];
}
catch (Exception err)
{
throw err;
}
}
}
}
Controller: UsersController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using MvcMovieStore.Models;
namespace MvcMovieStore.Controllers
{
public class UsersController : Controller
{
//
// GET: /Users/
public ActionResult Index()
{
DataTable dtGrid = new DataTable();
Users objUser = new Users();
dtGrid = objUser.GetUsers();
List<Users> Gridd = new List<Users>();
foreach (DataRow dr in dtGrid.Rows)
{
Users users = new Users();
users.ID = Convert.ToInt32(dr["User_Id"]);
users.UserName = dr["UserName"].ToString();
users.Country = dr["Country"].ToString();
users.Gender = dr["Gender"].ToString();
Gridd.Add(users);
}
return View("Index", Gridd);
}
}
}
View: Index.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcMovieStore.Models.Users>>"%>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Binding and Sorting Grid in ASP.NET MVC 2.0 using JQuery
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js">
</script>
<script src="../../Scripts/jquery.tablesorter.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.tablesorter.pager.js" type="text/javascript"></script>
<style type="text/css">
table.tablesorter thead tr .header
{
background-color: #000000;
color: #fff;
cursor: pointer;
padding: 5px 15px;
}
img{width=20px;height:20px;}
</style>
<h2>
Index</h2>
<%-- only for sorting
<script type="text/javascript">
$(document).ready(function () {
$("#userTable").tablesorter();
});
</script>--%>
<%--Sorting and paging --%>
<script type="text/javascript">
$(function () {
$("#userTable")
.tablesorter({ widthFixed: true })
.tablesorterPager({ container: $("#pager") });
$("#userTable").bind("sortStart", function () {
}).bind("sortEnd", function () {
});
//Hide/delete row on click.
$("#userTable img").click(function () { $(this).parent().parent().hide(); });
});
</script>
<p>
<%: Html.ActionLink("Create New", "Create") %>
</p>
<table id="userTable" class="tablesorter" style="height: 100%">
<thead>
<tr>
<th>
ID
</th>
<th>
UserName
</th>
<th>
Gender
</th>
<th>
Country
</th>
<th>
Edit
</th>
<th>
Details
</th>
<th>
Delete
</th>
</tr>
</thead>
<% foreach (var item in Model)
{ %>
<tr>
<td>
<%: item.ID %>
</td>
<td>
<%: item.UserName %>
</td>
<td>
<%: item.Gender %>
</td>
<td>
<%: item.Country %>
</td>
<td>
<%: Html.ActionLink("Edit", "Edit", new {id=item.ID }) %>
</td>
<td>
<%: Html.ActionLink("Details", "Details", new { id = item.ID })%>
</td>
<td>
<%: Html.ActionLink("Delete", "Delete", new { id = item.ID })%>
</td>
</tr>
<% } %>
</table>
<div id="pager" class="pager">
<br />
<img src="../../Content/arrow-left.png" class="first" />
<img src="../../Content/arrow-left.png" class="prev" />
<input type="text" class="pagedisplay" />
<img src="../../Content/arrow-right.png" class="next" />
<img src="../../Content/arrow-right.png" class="last" />
<select class="pagesize">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
</asp:Content>
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.


June 29, 2015 08:48 by
Peter
Logging may be a method of tracking/monitoring what's happening when an application is in progress/running. Log records are going to be most required things when one thing goes wrong in your application, be it Windows Forms, mobile or web applications.

Here I will be able to be walking through the basic steps in implementing work functionality using Apache log4net framework in an ASP.NET MVC 5 application. I'm using Visual Studio express 2013 for web as my development environment targeting .NET framework 4.5. Open Visual Studio 2013 for web and build a new ASP.NET web application selecting MVC template.

Here in this demo application, we are going to use Apache Log4net framework for logging. We'd like to add reference of Log4net DLL using NuGet package manager. In VS 2013 solution explorer and then Right click on Reference and select Manage NuGet Packages. Search for ‘log4net’ and Install.


Once installation is successful, we are able to see the log4net DLL added beneath the solution explorer Reference section as shown below:

Next, we'd like to piece our application to use log4net logging framework. Add the below line in your startup.cs get into ASP.NET MVC5 solution folder. The below line of code provides data about log4net configuration file.
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Web.config", Watch = true)]

Now, write the following code to web.config file:
<configSections>
<!-- Add log4net config section-->
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net debug="true">
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logs\log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
Modify the Global.asax.cs and add the following code inside Application_Start() method.
log4net.Config.XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config")));
Now our log4net library is ready to use with MVC5 application.
Add logger declaration in classes for which we want to make logs as below:
readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
Use the following logger.Error() method to log messages when needed as you can see on the below picture:

Run an application and that we will see the log file generated underneath the logs folder under the application root directory as configured in the web config file.
HostForLIFE.eu ASP.NET MVC 5 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.
