Tuesday, March 15, 2016

Change SharePoint authentication from classic mode to claims based


Recently I was in a situation to enable form authentication for a SharePoint web application that was configured using classic mode authentication. So the solution for me is to change the authentication mode to claims based.
Caution: Be noted that once you migrated the authentication provider to claims based, you can not revert it back.
(In 2007 version, the option was to extend the web application on the same content database, and enable form authentication, but there were some troubles always as I need to deploy the dll to bin folder in both web applications, original and extended. Also there were other troubles for deploying smart parts. )
From the central administration, I checked the authentication provider and it is showing my current authentication provider as windows.
clip_image001
Now I am going to change my authentication provider, to do this, you need to use windows powershell.
From the start menu, go to
All Programs -> SharePoint 2010 products -> Sharepoint 2010 Management Shell
clip_image002
The power shell window is opened as follows.
clip_image004
Execute the following commands
$WebAppName = “http://win-hgdsnnuakhv
$account = "WIN-HGDSNNUAKHV\Administrator"
$wa = get-SPWebApplication $WebAppName
Set-SPwebApplication $wa –AuthenticationProvider (New-SPAuthenticationProvider) –Zone Default
When you execute this command, a confirmation message will appear on the screen as follows.
clip_image006
Type Y for confirmation
After the command executed successfully, check the authentication provider from the central administration, it will show “claims based authentication”
clip_image007
Now execute the following commands.
  • set the user as an administrator for the site
$wa = get-SPWebApplication $WebAppName
$account = (New-SPClaimsPrincipal -identity $account -identitytype 1).ToEncodedString()
  • configure the policy to enable the user to have full access
$zp = $wa.ZonePolicies("Default")
$p = $zp.Add($account,"PSPolicy")
$fc=$wa.PolicyRoles.GetSpecialRole("FullControl")
$p.PolicyRoleBindings.Add($fc)
$wa.Update()
  • perform user migration
$wa = get-SPWebApplication $WebAppName
$wa.MigrateUsers($true)

Enabling or Disabling Claims Based Authentication


Claims Based Authentication is becoming so popular these days and enabling a SharePoint site to authenticate users no matter what authentication system is involved just got easier. I will not digress on Claims Based Authentication, not the point of this article, but I will focus on how to enable or disable CBA using PowerShell since there is no GUI available for this trick.
First, make sure your site (web application) does not have the CBA enabled. Go to Central Administration >> Manage web applications and click on the site you’re planning to enable CBA. Under Web Applications tab click on the Authentication Providers icon and a small window will pop-up. Under Default you should see Windows.
Claims Based Authentication
Claims Based Authentication
Next, create a PowerShell (.ps1) file using Notepad and paste the following code into it:
$setcba = Get-SPWebApplication "http://YourSiteURL"
$setcba.UseClaimsAuthentication = 1;
$setcba.Update()
Give it a name, like SetCB.ps1 and save in under C: on your SharePoint 2010 server.
Claims Based Authentication
Open SharePoint 2010 Management Shell, make sure you’re under C: (use CD.. to move under C:)and type or Copy and right-click Paste this command ./SetCB.ps1
Claims Based Authentication
Hit Enter and after few seconds your SharePoint site should have Claims Based Authentication enabled.
Repeat the previous steps to check if your site has CBA enabled, Central Administration >> Manage web applications and click on the site, click on the Authentication Providers icon and under Default you should see now Claims Based Authentication.
Claims Based Authentication
To revert back to Classic mode authentication (disabled Claims Based Authentication) just change the 1 to a 0:
$setcba = Get-SPWebApplication "http://YourSiteURL"
$setcba.UseClaimsAuthentication = 0;
$setcba.Update()

Wednesday, March 2, 2016

WebGrid with CRUD Operations using MVC

Enhancing WebGrid with Insert Update and Delete Operations


Many developers want to do Insert, Update and Delete with in WebGrid like as GridView, but don't know how to do it. This article will help you to do the CRUD operations with in WebGrid.

Populating WebGrid

The Model

First of all design the customer model using Entity Framework database first approach as show below
  1. CREATE TABLE [dbo].[Customer]
  2. (
  3. [CustID] [int] IDENTITY(1,1) PRIMARY KEY,
  4. [Name] [varchar](100) NULL,
  5. [Address] [varchar](200) NULL,
  6. [ContactNo] [varchar](20) NULL,
  7. )
Now design the model for querying the data from customer table and populating it to the GridView
  1. public static class SortExtension
  2. {
  3. public static IOrderedEnumerable OrderByWithDirection
  4. (this IEnumerable source,Func keySelector,bool descending)
  5. {
  6. return descending ? source.OrderByDescending(keySelector)
  7. : source.OrderBy(keySelector);
  8. }
  9. public static IOrderedQueryable OrderByWithDirection
  10. (this IQueryable source,Expression> keySelector,
  11. bool descending)
  12. {
  13. return descending ? source.OrderByDescending(keySelector)
  14. : source.OrderBy(keySelector);
  15. }
  16. }
  17. public class ModelServices : IDisposable
  18. {
  19. private readonly TestDBEntities entities = new TestDBEntities();
  20. public IEnumerable<Customer> GetCustomerPage(int pageNumber, int pageSize, string sort, bool Dir)
  21. {
  22. if (pageNumber < 1)
  23. pageNumber = 1;
  24. if (sort == "name")
  25. return entities.Customers.OrderByWithDirection(x => x.Name, Dir)
  26. .Skip((pageNumber - 1) * pageSize)
  27. .Take(pageSize)
  28. .ToList();
  29. else if (sort == "address")
  30. return entities.Customers.OrderByWithDirection(x => x.Address, Dir)
  31. .Skip((pageNumber - 1) * pageSize)
  32. .Take(pageSize)
  33. .ToList();
  34. else if (sort == "contactno")
  35. return entities.Customers.OrderByWithDirection(x => x.ContactNo, Dir)
  36. .Skip((pageNumber - 1) * pageSize)
  37. .Take(pageSize)
  38. .ToList();
  39. else
  40. return entities.Customers.OrderByWithDirection(x => x.CustID, Dir)
  41. .Skip((pageNumber - 1) * pageSize)
  42. .Take(pageSize)
  43. .ToList();
  44. }
  45. public int CountCustomer()
  46. {
  47. return entities.Customers.Count();
  48. }
  49. public void Dispose()
  50. {
  51. entities.Dispose();
  52. }
  53. }
  54. public class PagedCustomerModel
  55. {
  56. public int TotalRows { get; set; }
  57. public IEnumerable<Customer> Customer { get; set; }
  58. public int PageSize { get; set; }
  59. }

The View

Now design the view based on the above developed model as show below
  1. @model Mvc4_WebGrid_CRUD.Models.PagedCustomerModel
  2. @{
  3. ViewBag.Title = "WebGrid CRUD Operations";
  4. WebGrid grid = new WebGrid(rowsPerPage: Model.PageSize);
  5. grid.Bind(Model.Customer,autoSortAndPage: false,rowCount: Model.TotalRows
  6. );
  7. }
  8.  
  9. <div id="divmsg" style="color: green; font-weight: bold"></div>
  10. <a href="#" class="add">Add New</a>
  11. <br />
  12. <br />
  13. @grid.GetHtml(
  14. htmlAttributes: new { id = "grid" },
  15. fillEmptyRows: false,
  16. mode: WebGridPagerModes.All,
  17. firstText: "<< First",
  18. previousText: "< Prev",
  19. nextText: "Next >",
  20. lastText: "Last >>",
  21. columns: new[] {
  22. grid.Column("CustID",header: "ID", canSort: false),
  23. grid.Column(header: "Name",format: @<span> <span id="spanName_@item.CustID">@item.Name</span> @Html.TextBox("Name_"+(int)item.CustID,(string)item.Name,new{@style="display:none"})</span>),
  24. grid.Column(header: "Address",format: @<span> <span id="spanAddress_@item.CustID">@item.Address</span> @Html.TextBox("Address_"+(int)item.CustID,(string)item.Address,new{@style="display:none"})</span>),
  25. grid.Column(header: "Contact No",format: @<span> <span id="spanContactNo_@item.CustID">@item.ContactNo</span> @Html.TextBox("ContactNo_"+(int)item.CustID,(string)item.ContactNo,new{@style="display:none"})</span>),
  26. grid.Column(header: "Action",format:@<text> <a href="#" id="Edit_@item.CustID" class="edit">Edit</a><a href="#" id="Update_@item.CustID" style="display:none" class="update">Update</a><a href="#" id="Cancel_@item.CustID" style="display:none" class="cancel">Cancel</a><a href="#" id="Delete_@item.CustID" class="delete">Delete</a></text>)
  27. })

The Controller

Now, let's see how to write the code for populating the webgrid using model class and methods.
  1. public class HomeController : Controller
  2. {
  3. ModelServices mobjModel = new ModelServices();
  4. public ActionResult WebGridCRUD(int page = 1, string sort = "custid", string sortDir = "ASC")
  5. {
  6. const int pageSize = 10;
  7. var totalRows = mobjModel.CountCustomer();
  8. bool Dir = sortDir.Equals("desc", StringComparison.CurrentCultureIgnoreCase) ? true : false;
  9. var customer = mobjModel.GetCustomerPage(page, pageSize, sort, Dir);
  10. var data = new PagedCustomerModel()
  11. {
  12. TotalRows = totalRows,
  13. PageSize = pageSize,
  14. Customer = customer
  15. };
  16. return View(data);
  17. }
  18. }

Insert Operation

The Model

  1. public bool SaveCustomer(string name, string address, string contactno)
  2. {
  3. try
  4. {
  5. Customer cust = new Customer();
  6. cust.Name = name;
  7. cust.Address = address;
  8. cust.ContactNo = contactno;
  9. entities.Customers.Add(cust);
  10. entities.SaveChanges();
  11. return true;
  12. }
  13. catch
  14. {
  15. return false;
  16. }
  17. }

The View

  1. <script type="text/javascript">
  2. $(".add").live("click", function () {
  3. var existrow = $('.save').length;
  4. if (existrow == 0) {
  5. var index = $("#grid tbody tr").length + 1;
  6. var Name = "Name_" + index;
  7. var Address = "Address_" + index;
  8. var ContactNo = "ContactNo_" + index;
  9. var Save = "Save_" + index;
  10. var Cancel = "Cancel_" + index;
  11. var tr = '<tr class="alternate-row"><td></td><td><span> <input id="' + Name + '" type="text" /></span></td>' +
  12. '<td><span> <input id="' + Address + '" type="text" /></span></td>' +
  13. '<td><span> <input id="' + ContactNo + '" type="text" /></span></td>' +
  14. '<td> <a href="#" id="' + Save + '" class="save">Save</a><a href="#" id="' + Cancel + '" class="icancel">Cancel</a></td>' +
  15. '</tr>';
  16. $("#grid tbody").append(tr);
  17. }
  18. else {
  19. alert('First Save your previous record !!');
  20. }
  21. });
  22. $(".icancel").live("click", function () {
  23. var flag = confirm('Are you sure to cancel');
  24. if (flag) {
  25. $(this).parents("tr").remove();
  26. }
  27. });
  28. $(".save").live("click", function () {
  29. var id = $("#grid tbody tr").length;
  30. var Name = $("#Name_" + id).val();
  31. var Address = $("#Address_" + id).val();
  32. var ContactNo = $("#ContactNo_" + id).val();
  33. if (id != "") {
  34. $.ajax({
  35. type: "GET",
  36. contentType: "application/json; charset=utf-8",
  37. url: '@Url.Action("SaveRecord", "Home")',
  38. data: { "name": Name, "address": Address, "contactno": ContactNo },
  39. dataType: "json",
  40. beforeSend: function () { },
  41. success: function (data) {
  42. if (data.result == true) {
  43. $("#divmsg").html("Record has been saved successfully !!");
  44. setTimeout(function () { window.location.replace("WebGridCRUD"); }, 2000);
  45. }
  46. else {
  47. alert('There is some error');
  48. }
  49. }
  50. });
  51. }
  52. });
  53. <script>

The Controller

  1. [HttpGet]
  2. public JsonResult SaveRecord(string name, string address, string contactno)
  3. {
  4. bool result = false;
  5. try
  6. {
  7. result = mobjModel.SaveCustomer(name, address, contactno);
  8. }
  9. catch (Exception ex)
  10. {
  11. }
  12. return Json(new { result }, JsonRequestBehavior.AllowGet);
  13. }

How it works..

  

Update Operation

The Model

  1. public bool UpdateCustomer(int id, string name, string address, string contactno)
  2. {
  3. try
  4. {
  5. var cust = (from tbl in entities.Customers
  6. where tbl.CustID == id
  7. select tbl).FirstOrDefault();
  8. cust.Name = name;
  9. cust.Address = address;
  10. cust.ContactNo = contactno;
  11. entities.SaveChanges();
  12. return true;
  13. }
  14. catch
  15. {
  16. return false;
  17. }
  18. }

The View

  1. <script type="text/javascript">
  2. $(".edit").live("click", function () {
  3. var str = $(this).attr("id").split("_");
  4. id = str[1];
  5. var Name = "#Name_" + id;
  6. var spanName = "#spanName_" + id;
  7. var Address = "#Address_" + id;
  8. var spanAddress = "#spanAddress_" + id;
  9. var ContactNo = "#ContactNo_" + id;
  10. var spanContactNo = "#spanContactNo_" + id;
  11. $(Name).show();
  12. $(spanName).hide();
  13. $(Address).show();
  14. $(spanAddress).hide();
  15. $(ContactNo).show();
  16. $(spanContactNo).hide();
  17. $(this).hide();
  18. $("#Update_" + id).show();
  19. $("#Cancel_" + id).show();
  20. });
  21.  
  22. $(".update").live("click", function () {
  23. var str = $(this).attr("id").split("_");
  24. id = str[1];
  25. var Name = $("#Name_" + id).val();
  26. var spanName = $("#spanName_" + id).val();
  27. var Address = $("#Address_" + id).val();
  28. var spanAddress = $("#spanAddress_" + id).val();
  29. var ContactNo = $("#ContactNo_" + id).val();
  30. var spanContactNo = $("#spanContactNo_" + id).val();
  31. if (id != "") {
  32. $.ajax({
  33. type: "GET",
  34. contentType: "application/json; charset=utf-8",
  35. url: '@Url.Action("UpdateRecord", "Home")',
  36. data: { "id": id, "name": Name, "address": Address, "contactno": ContactNo },
  37. dataType: "json",
  38. beforeSend: function () {//alert(id);
  39. },
  40. success: function (data) {
  41. if (data.result == true) {
  42. $("#Update_" + id).hide();
  43. $("#Cancel_" + id).hide();
  44. $("#Edit_" + id).show();
  45. var Name = "#Name_" + id;
  46. var spanName = "#spanName_" + id;
  47. var Address = "#Address_" + id;
  48. var spanAddress = "#spanAddress_" + id;
  49. var ContactNo = "#ContactNo_" + id;
  50. var spanContactNo = "#spanContactNo_" + id;
  51. $(Name).hide();
  52. $(spanName).show();
  53. $(Address).hide();
  54. $(spanAddress).show();
  55. $(ContactNo).hide();
  56. $(spanContactNo).show();
  57. $(spanName).text($(Name).val());
  58. $(spanAddress).text($(Address).val());
  59. $(spanContactNo).text($(ContactNo).val());
  60. }
  61. else {
  62. alert('There is some error');
  63. }
  64. }
  65. });
  66. }
  67. });
  68.  
  69. <script>

The Controller

  1. [HttpGet]
  2. public JsonResult UpdateRecord(int id, string name, string address, string contactno)
  3. {
  4. bool result = false;
  5. try
  6. {
  7. result = mobjModel.UpdateCustomer(id, name, address, contactno);
  8. }
  9. catch (Exception ex)
  10. {
  11. }
  12. return Json(new { result }, JsonRequestBehavior.AllowGet);
  13. }

How it works..

 

Delete Operation

The Model

  1. public bool DeleteCustomer(int id)
  2. {
  3. try
  4. {
  5. var cust = (from tbl in entities.Customers
  6. where tbl.CustID == id
  7. select tbl).FirstOrDefault();
  8. entities.Customers.Remove(cust);
  9. entities.SaveChanges();
  10. return true;
  11. }
  12. catch
  13. {
  14. return false;
  15. }
  16. }

The View

  1. <script type="text/javascript">
  2. $(".delete").live("click", function () {
  3. var str = $(this).attr("id").split("_");
  4. id = str[1];
  5. var flag = confirm('Are you sure to delete ??');
  6. if (id != "" && flag) {
  7. $.ajax({
  8. type: "GET",
  9. contentType: "application/json; charset=utf-8",
  10. url: '@Url.Action("DeleteRecord", "Home")',
  11. data: { "id": id },
  12. dataType: "json",
  13. beforeSend: function () { },
  14. success: function (data) {
  15. if (data.result == true) {
  16. $("#Update_" + id).parents("tr").remove();
  17. }
  18. else {
  19. alert('There is some error');
  20. }
  21. }
  22. });
  23. }
  24. });
  25. <script>

The Controller

  1. public bool DeleteCustomer(int id)
  2. {
  3. try
  4. {
  5. var cust = (from tbl in entities.Customers
  6. where tbl.CustID == id
  7. select tbl).FirstOrDefault();
  8. entities.Customers.Remove(cust);
  9. entities.SaveChanges();
  10. return true;
  11. }
  12. catch
  13. {
  14. return false;
  15. }
  16. }

How it works..

 
What do you think?
I hope you will enjoy the tricks while programming with MVC Razor. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.