HI WELCOME TO SIRIS
Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Securing Asp.Net MVC Application by using Authorize Attribute

Authorization is the process of determining the rights of an authenticated user for accessing the application's resources. The Asp.Net MVC Framework has a AuthorizeAttribute filter for filtering the authorized user to access a resource. Refer this article for Custom Authentication and Authorization in ASP.NET MVC
Authorize Attribute Properties
Properties
Description
Roles
Gets or sets the roles required to access the controller or action method.
Users
Gets or sets the user names required to access the controller or action method.

Filtering Users by Users Property

Suppose you want to allow the access of AdminProfile to only shailendra and mohan users then you can specify the authorize users list to Users property as shown below.
  1. [Authorize(Users = "shailendra,mohan")]
  2. public ActionResult AdminProfile()
  3. {
  4. return View();
  5. }

Filtering Users by Roles Property

Suppose you want to allow the access of AdminProfile action to only Admin and SubAdmin roles then you can specify the authorize roles list to Users property as shown below.
  1. [Authorize(Roles = "Admin,SubAdmin")]
  2. public ActionResult AdminProfile()
  3. {
  4. return View();
  5. }
What do you think?
I hope you will enjoy the tips while programming with Asp.Net MVC. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Understanding Caching in Asp.Net MVC with example

Caching is a most important aspect of high-performance web application. Caching provides a way of storing frequently accessed data and reusing that data. Practically, this is an effective way for improving web application’s performance.

Advantage of Caching

  1. Reduce hosting server round-trips

    When content is cached at the client or in proxies, it cause minimum request to server.
  2. Reduce database server round-trips

    When content is cached at the web server, it can eliminate the database request.
  3. Reduce network traffic

    When content is cached at the client side, it it also reduce the network traffic.
  4. Avoid time-consumption for regenerating reusable content

    When reusable content is cached, it avoid the time consumption for regenerating reusable content.
  5. Improve performance

    Since cached content reduce round-trips, network traffic and avoid time consumption for regenerating reusable content which cause a boost in the performance.

Key points about Caching

  1. Use caching for contents that are accessed frequently.
  2. Avoid caching for contents that are unique per user.
  3. Avoid caching for contents that are accessed infrequently/rarely.
  4. Use the VaryByCustom function to cache multiple versions of a page based on customization aspects of the request such as cookies, role, theme, browser, and so on.
  5. For efficient caching use 64-bit version of Windows Server and SQL Server.
  6. For database caching make sure your database server has sufficient RAM otherwise, it may degrade the performance.
  7. For caching of dynamic contents that change frequently, define a short cache–expiration time rather than disabling caching.

Output Cache Filter

The OutputCache filter allow you to cache the data that is output of an action method. By default, this attribute filter cache the data till 60 seconds. After 60 sec, if a call was made to this action then ASP.NET MVC will cache the output again.

Enabling Output Caching

You can enable the output caching for an action method or controller by adding an [OutputCache] attribute as shown below:
[OutputCache(Duration=20, VaryByParam="none")]
public ActionResult Index()
{
 ViewBag.Message = DateTime.Now.ToString();
 return View();
}
The output of the Index() action method will be cached for 20 seconds. If you will not defined the duration, it will cached it for by default cache duration 60 sec. You can see the cache effect by applying the break point on index method as shown below.
  

OutputCache Filter Parameter

Parameter
Type
Description
CacheProfile
string
Specify the name of the output cache policy which is defined with in <outputCacheSettings> tag of Web.config.
Duration
int
Specify the time in sec to cache the content
Location
OutputCacheLocation
Specify the location of the output to be cached. By default location is Any.
NoStore
bool
Enable/Disable where to use HTTP Cache-Control. This is used only to protect very sensitive data.
SqlDependency
string
Specify the database and table name pairs on which the cache content depends on. The cached data will expire automatically when the data changes in the database.
VaryByContentEncoding
string
Specify the semicolon separated list of character set (Content encoding like gzip and deflate) that the output cache uses to vary the cache content
VaryByCustom
string
Specify the list of custom strings that the output cache uses to vary the cache content.
VaryByHeader
string
Specify the semicolon separated list of HTTP header names that are used to vary the cache content.
VaryByParam
string
Specify the semicolon separated list of form POST or query string parameters that are used to vary the cache content. If not specified, the default value is none.

Output Caching Location

By default, content is cached in three locations: the web server, any proxy servers, and the user's browser. You can control the content's cached location by changing the location parameter of the OutputCache attribute to any of the following values: Any, Client, Downstream, Server, None, or ServerAndClient.
By default, the location parameter has the value Any which is appropriate for most the scenarios. But there are scenarios when you required more control over the cached data.
Suppose you want to cache the logged in use information then you should cache the data on client browser since this data is specific to a user. If you will cache this data on the server, all the user will see the same information that is wrong.
You should cache the data on the server which is common to all the users and is sensitive.

Configure Cache Location

For configuring the cache location, you need to add the System.Web.UI namespace on your controller. You can cached the user's personal information in his browser like as below.
[OutputCache(Duration = 7200, Location = OutputCacheLocation.Client, VaryByParam = "none", NoStore = true)]
public ActionResult Index()
{
 ViewBag.Message = "Welcome : " + User.Identity.Name;
 return View();
}
What do you think?
I hope you have got what is caching and how it works. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

CRUD Operations using jQuery dialog, Entity Framework and ASP.NET MVC

This article will demonstrate, how to create an Asp.Net MVC application with CRUD (Create, Read, Update, Delete) Operations using jQuery and Entity Framework code first. suppose you have following data model and DataContext classes in EF.
  1. public class User
  2. {
  3. public int UserID { get; set; }
  4. [Required(ErrorMessage = "Please Enter Your Name")]
  5. public string Name { get; set; }
  6. [Required(ErrorMessage = "Please Enter Your Address")]
  7. public string Address { get; set; }
  8. [Required(ErrorMessage = "Please Enter Your Contact No")]
  9. public string ContactNo { get; set; }
  10. }
  11.  
  12. public class DataContext : DbContext
  13. {
  14. public DataContext()
  15. : base("DefaultConnection")
  16. {
  17.  
  18. }
  19.  
  20. public DbSet<User> Users { get; set; }
  21. }
Now migrate your data model class into SQL Server database by using EF code first database migration. For more help refer this link Understanding Entity Framework Code First Migrations

Create Operation






Read Operation


Update Operation






Delete Operation


Making jQuery dialogs for CRUD Operations

  1. @model IEnumerable<jQuery_CRUD.DAL.User>
  2. @{
  3. ViewBag.Title = "Index";
  4. }
  5. <script src="~/Scripts/jquery-1.8.2.min.js"></script>
  6. <script src="~/Scripts/jquery-ui-1.8.24.min.js"></script>
  7. <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
  8. <script>
  9. $(document).ready(function () {
  10. var url = "";
  11. $("#dialog-alert").dialog({
  12. autoOpen: false,
  13. resizable: false,
  14. height: 170,
  15. width: 350,
  16. show: { effect: 'drop', direction: "up" },
  17. modal: true,
  18. draggable: true,
  19. open: function (event, ui) {
  20. $(".ui-dialog-titlebar-close").hide();
  21. },
  22. buttons: {
  23. "OK": function () {
  24. $(this).dialog("close");
  25.  
  26. },
  27. "Cancel": function () {
  28. $(this).dialog("close");
  29. }
  30. }
  31. });
  32.  
  33. if ('@TempData["msg"]' != "") {
  34. $("#dialog-alert").dialog('open');
  35. }
  36.  
  37. $("#dialog-edit").dialog({
  38. title: 'Create User',
  39. autoOpen: false,
  40. resizable: false,
  41. width: 400,
  42. show: { effect: 'drop', direction: "up" },
  43. modal: true,
  44. draggable: true,
  45. open: function (event, ui) {
  46. $(".ui-dialog-titlebar-close").hide();
  47. $(this).load(url);
  48. }
  49. });
  50.  
  51. $("#dialog-confirm").dialog({
  52. autoOpen: false,
  53. resizable: false,
  54. height: 170,
  55. width: 350,
  56. show: { effect: 'drop', direction: "up" },
  57. modal: true,
  58. draggable: true,
  59. open: function (event, ui) {
  60. $(".ui-dialog-titlebar-close").hide();
  61.  
  62. },
  63. buttons: {
  64. "OK": function () {
  65. $(this).dialog("close");
  66. window.location.href = url;
  67. },
  68. "Cancel": function () {
  69. $(this).dialog("close");
  70. }
  71. }
  72. });
  73.  
  74. $("#dialog-detail").dialog({
  75. title: 'View User',
  76. autoOpen: false,
  77. resizable: false,
  78. width: 400,
  79. show: { effect: 'drop', direction: "up" },
  80. modal: true,
  81. draggable: true,
  82. open: function (event, ui) {
  83. $(".ui-dialog-titlebar-close").hide();
  84. $(this).load(url);
  85. },
  86. buttons: {
  87. "Close": function () {
  88. $(this).dialog("close");
  89. }
  90. }
  91. });
  92.  
  93. $("#lnkCreate").live("click", function (e) {
  94. //e.preventDefault(); //use this or return false
  95. url = $(this).attr('href');
  96. $("#dialog-edit").dialog('open');
  97.  
  98. return false;
  99. });
  100.  
  101. $(".lnkEdit").live("click", function (e) {
  102. // e.preventDefault(); use this or return false
  103. url = $(this).attr('href');
  104. $(".ui-dialog-title").html("Update User");
  105. $("#dialog-edit").dialog('open');
  106.  
  107. return false;
  108. });
  109.  
  110. $(".lnkDelete").live("click", function (e) {
  111. // e.preventDefault(); use this or return false
  112. url = $(this).attr('href');
  113. $("#dialog-confirm").dialog('open');
  114.  
  115. return false;
  116. });
  117.  
  118. $(".lnkDetail").live("click", function (e) {
  119. // e.preventDefault(); use this or return false
  120. url = $(this).attr('href');
  121. $("#dialog-detail").dialog('open');
  122.  
  123. return false;
  124. });
  125.  
  126. $("#btncancel").live("click", function (e) {
  127. $("#dialog-edit").dialog("close");
  128. return false;
  129. });
  130. });
  131. </script>
  132. <div id="dialog-alert" style="display: none">
  133. <p>
  134. @TempData["msg"]!
  135. </p>
  136. </div>
  137.  
  138. <div id="dialog-confirm" style="display: none">
  139. <p>
  140. <span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>
  141. Are you sure to delete?
  142. </p>
  143. </div>
  144.  
  145. <div id="dialog-edit" style="display: none">
  146. </div>
  147. <div id="dialog-detail" style="display: none">
  148. </div>
  149.  
  150. <h2>Users List</h2>
  151.  
  152. <p>
  153. @Html.ActionLink("Create New", "Create", null, new { id = "lnkCreate" })
  154. </p>
  155. <table>
  156. <tr>
  157. <th>
  158. @Html.DisplayNameFor(model => model.Name)
  159. </th>
  160. <th>
  161. @Html.DisplayNameFor(model => model.Address)
  162. </th>
  163. <th>
  164. @Html.DisplayNameFor(model => model.ContactNo)
  165. </th>
  166. <th></th>
  167. </tr>
  168.  
  169. @foreach (var item in Model)
  170. {
  171. <tr>
  172. <td>
  173. @Html.DisplayFor(modelItem => item.Name)
  174. </td>
  175. <td>
  176. @Html.DisplayFor(modelItem => item.Address)
  177. </td>
  178. <td>
  179. @Html.DisplayFor(modelItem => item.ContactNo)
  180. </td>
  181. <td>
  182. @Html.ActionLink("Edit", "Edit", new { id = item.UserID }, new { @class = "lnkEdit" }) |
  183. @Html.ActionLink("Details", "Details", new { id = item.UserID }, new { @class = "lnkDetail" }) |
  184. @Html.ActionLink("Delete", "Delete", new { id = item.UserID }, new { @class = "lnkDelete" })
  185. </td>
  186. </tr>
  187. }
  188.  
  189. </table>

Controller for handling CRUD Operations

  1. public class UserController : Controller
  2. {
  3. private DataContext db = new DataContext();
  4.  
  5. // GET: /User/
  6. public ActionResult Index()
  7. {
  8. return View(db.Users.ToList());
  9. }
  10.  
  11. // GET: /User/Details/5
  12. public ActionResult Details(int id = 0)
  13. {
  14. User user = db.Users.Find(id);
  15. if (user == null)
  16. {
  17. return HttpNotFound();
  18. }
  19. return View(user);
  20. }
  21.  
  22. // GET: /User/Create
  23. public ActionResult Create()
  24. {
  25. return PartialView();
  26. }
  27.  
  28. // POST: /User/Create
  29. [HttpPost]
  30. [ValidateAntiForgeryToken]
  31. public ActionResult Create(User user, string Command)
  32. {
  33. if (ModelState.IsValid)
  34. {
  35. db.Users.Add(user);
  36. db.SaveChanges();
  37. TempData["Msg"] = "Data has been saved succeessfully";
  38. return RedirectToAction("Index");
  39. }
  40.  
  41. return View(user);
  42. }
  43.  
  44. // GET: /User/Edit/5
  45. public ActionResult Edit(int id = 0)
  46. {
  47. User user = db.Users.Find(id);
  48. if (user == null)
  49. {
  50. return HttpNotFound();
  51. }
  52. return View(user);
  53. }
  54.  
  55. // POST: /User/Edit/5
  56. [HttpPost]
  57. [ValidateAntiForgeryToken]
  58. public ActionResult Edit(User user)
  59. {
  60. if (ModelState.IsValid)
  61. {
  62. db.Entry(user).State = EntityState.Modified;
  63. db.SaveChanges();
  64. TempData["Msg"] = "Data has been updated succeessfully";
  65. return RedirectToAction("Index");
  66. }
  67. return View(user);
  68. }
  69.  
  70. // GET: /User/Delete/5
  71. public ActionResult Delete(int id)
  72. {
  73. User user = db.Users.Find(id);
  74. db.Users.Remove(user);
  75. db.SaveChanges();
  76. TempData["Msg"] = "Data has been deleted succeessfully";
  77. return RedirectToAction("Index");
  78. }
  79.  
  80. protected override void Dispose(bool disposing)
  81. {
  82. db.Dispose();
  83. base.Dispose(disposing);
  84. }
  85. }
What do you think?
I hope you will enjoy these tricks while programming with ASP.NET MVC. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.