Thursday, May 5, 2011

Creating A Custom Edit Control Block Part 2

     So in the last post, I went over the basic means for getting a custom ECB up and running. In this post, I will give more detailed examples and how to use .Net code to really give your ECB some nice features! So moving on to a more detailed example. The following image shows a custom ECB created using javascript and .Net object model code:


As you can see, there is a lot of functionality in there. It is security trimmed by the item and determines what the current user can do. The Repeat options allow the author of the item to basically copy the commitment to another department/division/ branch in this case. So how do we do this you ask? Let's take a look at some code that makes this kind of thing happen. First the javascript code:

function Custom_AddListMenuItems(m, ctx) {
    if (test.indexOf("Lists/Commitments") > 0) {
 var request;
 var url = ctx.HttpRoot + "/CustomPages/ECB.aspx?ListID=" + ctx.listName + "&ItemID=" + currentItemID + "&DateTime=" + Date();
 request = new ActiveXObject("Microsoft.XMLHTTP");
      if (request) {
  request.open("GET", url, false);
  request.send();
      }
      if (request) {
  var commands = request.responseXML.getElementsByTagName("Command");
  var dvs, brs;
  var menuitema, menuitemb, menuitemc, menuitemd, menuiteme;
  var menuitemsd = new Array();
  var menuitemse = new Array();
  var menuitemsf = new Array();
  var menuitems = new Array(100, 100);
  var chka = 0;
  var chkb = 0;
  var chkc = 0;
  var chkd = 0;
  var chke = 0;
  var tp0, tp1, tp2, tp3, tp4, tp5;
  var ddbr;
   CAMOpt(m, "Print Item...", "_nnsy_printListItem()", "/_layouts/images/fax.gif");
   // Add separator
   CAMSep(m);
   for (var i = 0; i < commands.length; i++) {
       var cmdName = commands[i].getElementsByTagName("Name")[0].firstChild.nodeValue;
       var imageUrl = commands[i].getElementsByTagName("ImageUrl")[0].firstChild.nodeValue;
       var type = commands[i].getElementsByTagName("Type")[0].firstChild.nodeValue;
       switch (type) {
           case "Seperator":
               CAMSep(m);
               break;

           case "MenuItem":
               var js = commands[i].getElementsByTagName("Script")[0].firstChild.nodeValue;
               CAMOpt(m, cmdName, js, imageUrl);
               break;

           case "Concurrence":
               var js = commands[i].getElementsByTagName("Script")[0].firstChild.nodeValue;
               if (chkb == 0) {
                   menuitemb = CASubM(m, "Concurrences", "", "/_layouts/images/forward.gif");
                   menuitemsd[chkb] = CASubM(menuitemb, cmdName, imageUrl)
                   CAMOpt(menuitemsd[chkb], "View", "viewconcurrence('" + js + "', 'Concurrence', 'View')", imageUrl);
                   CAMOpt(menuitemsd[chkb], "Edit", "editconcurrence('" + js + "', 'Concurrence', 'Edit')", imageUrl);
                   CAMOpt(menuitemsd[chkb], "Concur", "editconcurrence('" + js + "', 'Concurrence', 'Concur')", imageUrl);
                   chkb += 1;
               }
               else {
                   menuitemsd[chkb] = CASubM(menuitemb, cmdName, imageUrl)
                   CAMOpt(menuitemsd[chkb], "View", "viewconcurrence('" + js + "', 'Concurrence', 'View')", imageUrl);
                   CAMOpt(menuitemsd[chkb], "Edit", "editconcurrence('" + js + "', 'Concurrence', 'Edit')", imageUrl);
                   CAMOpt(menuitemsd[chkb], "Concur", "editconcurrence('" + js + "', 'Concurrence', 'Concur')", imageUrl);
                   chkb += 1;
               }
               break;

           case "Extension":
               var js = commands[i].getElementsByTagName("Script")[0].firstChild.nodeValue;
               if (chkc == 0) {
                   menuitemc = CASubM(m, "Extensions", "", "/_layouts/images/forward.gif");
                   menuitemse[chkc] = CASubM(menuitemc, cmdName, imageUrl)
                   CAMOpt(menuitemse[chkc], "View", "viewconcurrence('" + js + "', 'Extension', 'View')", imageUrl);
                   CAMOpt(menuitemse[chkc], "Edit", "editconcurrence('" + js + "', 'Extension', 'Edit')", imageUrl);
                   CAMOpt(menuitemse[chkc], "Concur", "editconcurrence('" + js + "', 'Extension', 'Concur')", imageUrl);
                   chkc += 1;
               }
               else {
                   menuitemse[chkc] = CASubM(menuitemc, cmdName, imageUrl)
                   CAMOpt(menuitemse[chkc], "View", "viewconcurrence('" + js + "', 'Extension', 'View')", imageUrl);
                   CAMOpt(menuitemse[chkc], "Edit", "editconcurrence('" + js + "', 'Extension', 'Edit')", imageUrl);
                   CAMOpt(menuitemse[chkc], "Concur", "editconcurrence('" + js + "', 'Extension', 'Concur')", imageUrl);
                   chkc += 1;
               }
               break;

           case "Closeout":
               var js = commands[i].getElementsByTagName("Script")[0].firstChild.nodeValue;
               if (chkd == 0) {
                   menuitemd = CASubM(m, "Closeout", "", "/_layouts/images/forward.gif");
                   CAMOpt(menuitemd, "View", "viewconcurrence('" + js + "', 'Closeout', 'View')", imageUrl);
                   CAMOpt(menuitemd, "Edit", "editconcurrence('" + js + "', 'Closeout', 'Edit')", imageUrl);
                   CAMOpt(menuitemd, "Concur", "editconcurrence('" + js + "', 'Closeout', 'Concur')", imageUrl);
                   chkd += 1;
               }
               else {
                   CAMOpt(menuitemd, "View", "viewconcurrence('" + js + "', 'Closeout', 'View')", imageUrl);
                   CAMOpt(menuitemd, "Edit", "editconcurrence('" + js + "', 'Closeout', 'Edit')", imageUrl);
                   CAMOpt(menuitemd, "Concur", "editconcurrence('" + js + "', 'Closeout', 'Concur')", imageUrl);
                   chkd += 1;
               }
               break;


           case "CopyToDept":
               var xmldata1 = new ActiveXObject("MSXML.DomDocument");
               xmldata1.loadXML(request.responseText);
               var depts = xmldata1.selectNodes("ECB/Departments/Department");
               menuitems[99, 99] = CASubM(m, "Repeat To Department");
               for (var j = 0; j < depts.length; j++) {
                   tp0 = depts[j].childNodes[0].firstChild.nodeValue;
                   CAMOpt(menuitems[99, 99], tp0, "copyitem('" + cmdName + "', '" + tp0 + "', '" + null + "', '" + null + "')", "/_layouts/images/forward.gif");
               }
               break;

           case "CopyToDiv":
               var xmldata1 = new ActiveXObject("MSXML.DomDocument");
               xmldata1.loadXML(request.responseText);
               var depts = xmldata1.selectNodes("ECB/Departments/Department");
               menuitems[99, 99] = CASubM(m, "Repeat To Division");
               for (var j = 0; j < depts.length; j++) {
                   tp0 = depts[j].childNodes[0].firstChild.nodeValue;
                   menuitems[j, 0] = CASubM(menuitems[99, 99], tp0);
                   dvs = depts[j].childNodes[1].childNodes;
                   for (var k = 0; k < dvs.length; k++) {
                       tp1 = dvs[k].childNodes[0].firstChild.nodeValue;
                       CAMOpt(menuitems[j, 0], tp1, "copyitem('" + cmdName + "', '" + tp0 + "', '" + tp1 + "', '" + null + "')", "/_layouts/images/forward.gif");
                   }
               }
               break;


           case "CopyToBranch":
               var xmldata1 = new ActiveXObject("MSXML.DomDocument");
               xmldata1.loadXML(request.responseText);
               var depts = xmldata1.selectNodes("ECB/Departments/Department");
               menuitems[99, 99] = CASubM(m, "Repeat To Branch");
               for (var j = 0; j < depts.length; j++) {
                   tp0 = depts[j].childNodes[0].firstChild.nodeValue;
                   menuitems[j, 0] = CASubM(menuitems[99, 99], tp0);
                   dvs = depts[j].childNodes[1].childNodes;
                   for (var k = 0; k < dvs.length; k++) {
                       tp1 = dvs[k].childNodes[0].firstChild.nodeValue;
                       menuitems[j, k + 1] = CASubM(menuitems[j, 0], tp1);
                       brs = dvs[k].childNodes[1].childNodes;
                       for (var n = 0; n < brs.length; n++) {
                           tp2 = brs[n].childNodes[0].firstChild.nodeValue;
                           CAMOpt(menuitems[j, k + 1], tp2, "copyitem('" + cmdName + "', '" + tp0 + "', '" + tp1 + "', '" + tp2 + "')", "/_layouts/images/forward.gif");
                       }
                   }
               }
               break;
       }

   }
   if (commands.length > 0) CAMSep(m);
   return true;
   //return false; // for testing
  }
 }
 else {
  return false;
 }  
}

So as you can see here there is a lot going on. The first step is to setup an ajax request to the .aspx page that has the object model code. This could be done using inline script or code behind which is the better choice. This page is actually in a document library that users would have read access to. So the request object sends requests to the page and sends the list and item id's in the querystring. This page has several responsibilities. It must return valid xml to be used by the javascript code. It will also determine the users ability based on what the requirements are. In the code below, there is a lot of stuff to go through but I will try to tie it all together in the end.

private void Page_Load(Object sender, EventArgs e)
{
    SPWeb web = SPContext.Current.Web;
    SPUser curuser;
    String author = String.Empty;
    String cuser = String.Empty;
    SPListItem item = null;
    String qry;
    int itemID = 1;
    curuser = SPContext.Current.Web.CurrentUser;
    SPList emps = web.Lists["User Information List"];
    SPList status = web.Lists["Status"];
    SPList ddbr = web.Lists["DDBR"];
    SPList prefs = web.Lists["Preferences"];
    SPListItem pref = prefs.Items.GetItemById(1);
    SPListItem user = emps.Items.GetItemById(Convert.ToInt32(curuser.ID));
    SPList list = web.Lists["Commitments"];
    SPList concs = web.Lists["Concurrences"];
    Boolean goon = true;
    try
    {
        itemID = int.Parse(this.Page.Request.QueryString["ItemID"]);
        item = list.Items.GetItemById(itemID);
        author = item["Author"].ToString();
        int loc = author.IndexOf("#");
        author = author.Remove(0, loc + 1);
        cuser = curuser.Name.ToString();
    }
    catch (Exception ex){ author = ex.Message.ToString() + ", " + ex.Source.ToString(); }
        
    String xhtml = "";

    String asgdiv = String.Empty;
    if (item["AssignedDivision"] != null) { asgdiv = item["AssignedDivision"].ToString(); }
    String asgdept;
    asgdept = item["AssignedDepartment"].ToString();
        
    this.Page.Response.ClearHeaders();
    this.Page.Response.ClearContent();
    this.Page.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    this.Page.Response.AddHeader("Content-type", "text/xml");

    string cmdPatterna = @"";
    
    xhtml += "";
    xhtml += "";    
    String udept = "";
    String udiv = "";
    String ubr = "";
    SPQuery dpqry;
    SPQuery dvqry;

    xhtml += "";
    foreach (SPListItem x in ddbr.Items)
    {
        if (x["Department"].ToString() != udept)
        {
            udept = x["Department"].ToString();
            xhtml += string.Format("{0}", udept);
            dpqry = new SPQuery();
            dpqry.Query = "" + udept + "";
            foreach (SPListItem y in ddbr.GetItems(dpqry))
            {
                if (y["Division"].ToString() != udiv)
                {
                    udiv = y["Division"].ToString();
                    xhtml += string.Format("{0}", udiv);
                    dvqry = new SPQuery();
                    dvqry.Query = "" + udiv + "";
                    foreach (SPListItem z in ddbr.GetItems(dvqry))
                    {
                        if (z["Branch"].ToString() != ubr)
                        {
                            ubr = z["Branch"].ToString();
                            xhtml += string.Format("{0}", ubr);
                        }
                    }
                    xhtml += "";
                    xhtml += "";
                }
            }
            xhtml += "";
            xhtml += "";
        }
    }
    xhtml += "";
    xhtml += "";

    if (list.DoesUserHavePermissions(SPBasePermissions.CreateAlerts)) { xhtml += string.Format(cmdPatterna, "MenuItem", "Alert Me", Page.ResolveUrl("~/_layouts/images/outl.gif"), "alertme('" + itemID + "', '{" + list.ID.ToString() + "}')"); }
    if (list.DoesUserHavePermissions(SPBasePermissions.ViewListItems)) { xhtml += string.Format(cmdPatterna, "MenuItem", "View Commitment", Page.ResolveUrl("~/_layouts/images/openfold.gif"), "viewitem('" + itemID + "', '" + item["Priority"].ToString() + "')"); }
    if (list.DoesUserHavePermissions(SPBasePermissions.ViewVersions)) { xhtml += string.Format(cmdPatterna, "MenuItem", "Version History", Page.ResolveUrl("~/_layouts/images/versions.gif"), "versions('" + itemID + "', '{" + list.ID.ToString() + "}')"); }
    xhtml += string.Format(cmdPatterna, "Seperator", null, null, null);
        
    try
    {
        if (web.IsCurrentUserMemberOfGroup(web.Groups["CTS Content Manager"].ID) == true || web.IsCurrentUserMemberOfGroup(web.Groups["WebAdmin"].ID) == true || web.IsCurrentUserMemberOfGroup(web.Groups["CTS Owners"].ID) == true || author == curuser.Name.ToString()) //  || author == curuser.Name.ToString()
        {
            xhtml += string.Format(cmdPatterna, "CopyToDept", itemID, null, null);
            xhtml += string.Format(cmdPatterna, "CopyToDiv", itemID, null, null);
            xhtml += string.Format(cmdPatterna, "CopyToBranch", itemID, null, null);
            xhtml += string.Format(cmdPatterna, "Seperator", null, null, null);
            xhtml += string.Format(cmdPatterna, "MenuItem", "Create Concurrence Request", Page.ResolveUrl("~/_layouts/images/icspgen.gif"), "concurrence('" + itemID + "')");
            xhtml += string.Format(cmdPatterna, "MenuItem", "Create Complete Request", Page.ResolveUrl("~/_layouts/images/icspgen.gif"), "createcloseout('" + itemID + "')");
            xhtml += string.Format(cmdPatterna, "MenuItem", "Revise ECD", Page.ResolveUrl("~/_layouts/images/icspgen.gif"), "revecd('" + itemID + "')");
            xhtml += string.Format(cmdPatterna, "Seperator", null, null, null);
            xhtml += string.Format(cmdPatterna, "MenuItem", "Edit Commitment", Page.ResolveUrl("~/_layouts/images/edit.gif"), "edititem('" + itemID + "', '" + item["Priority"].ToString() + "')");
            xhtml += string.Format(cmdPatterna, "MenuItem", "Complete Commitment", Page.ResolveUrl("~/_layouts/images/star.gif"), "closeitem('" + itemID + "')"); 
            if (list.DoesUserHavePermissions(SPBasePermissions.DeleteListItems)) { xhtml += string.Format(cmdPatterna, "MenuItem", "Delete Commitment", Page.ResolveUrl("~/_layouts/images/delete.gif"), "deleteitem('" + itemID + "')"); }
            if (list.DoesUserHavePermissions(SPBasePermissions.ManagePermissions)) { xhtml += string.Format(cmdPatterna, "MenuItem", "Manage Permissions", Page.ResolveUrl("~/_layouts/images/managePerm.gif"), "permissions('" + itemID + "', '{" + list.ID.ToString() + "}')"); }
        }
        else
        {
            if (web.IsCurrentUserMemberOfGroup(web.Groups["CTS Power Users"].ID) == true || web.IsCurrentUserMemberOfGroup(web.Groups["CTS Users"].ID) == true)
            {
                if (item["Priority"].ToString().Contains("Interdepartmental"))  // Interdepartmental commitment
                {
                    if (item["AssignedDepartment"].ToString().Equals(user["CTSDepartment"].ToString()))
                    {
                        xhtml += string.Format(cmdPatterna, "MenuItem", "Create Concurrence Request", Page.ResolveUrl("~/_layouts/images/icspgen.gif"), "concurrence('" + itemID + "')");
                        xhtml += string.Format(cmdPatterna, "MenuItem", "Revise ECD", Page.ResolveUrl("~/_layouts/images/icspgen.gif"), "revecd('" + itemID + "')"); 
                        xhtml += string.Format(cmdPatterna, "MenuItem", "Edit Commitment", Page.ResolveUrl("~/_layouts/images/edit.gif"), "edititem('" + itemID + "', '" + item["Priority"].ToString() + "')");
                        if (list.DoesUserHavePermissions(SPBasePermissions.DeleteListItems))
                        {
                            xhtml += string.Format(cmdPatterna, "MenuItem", "Complete Commitment", Page.ResolveUrl("~/_layouts/images/star.gif"), "closeitem('" + itemID + "')");
                            xhtml += string.Format(cmdPatterna, "MenuItem", "Delete Commitment", Page.ResolveUrl("~/_layouts/images/delete.gif"), "deleteitem('" + itemID + "')");
                        }
                        else
                        {
                            if (pref["AllowCloseout"].ToString().Equals("Yes"))
                            {
                                if (item["Status"].ToString().Equals("In Progress")) { xhtml += string.Format(cmdPatterna, "MenuItem", "Complete Commitment", Page.ResolveUrl("~/_layouts/images/star.gif"), "closeitem('" + itemID + "')"); }
                            }
                            else
                            {
                                if (item["Status"].ToString().Equals("In Progress")) { xhtml += string.Format(cmdPatterna, "MenuItem", "Create Complete Request", Page.ResolveUrl("~/_layouts/images/icspgen.gif"), "createcloseout('" + itemID + "')"); }
                            }
                        }
                    }
                }
                else  // item is critical or commitment
                {
                    xhtml += string.Format(cmdPatterna, "MenuItem", "Create Concurrence Request", Page.ResolveUrl("~/_layouts/images/icspgen.gif"), "concurrence('" + itemID + "')");
                    xhtml += string.Format(cmdPatterna, "MenuItem", "Revise ECD", Page.ResolveUrl("~/_layouts/images/icspgen.gif"), "revecd('" + itemID + "')");
                    xhtml += string.Format(cmdPatterna, "MenuItem", "Edit Commitment", Page.ResolveUrl("~/_layouts/images/edit.gif"), "edititem('" + itemID + "', '" + item["Priority"].ToString() + "')");
                    if (list.DoesUserHavePermissions(SPBasePermissions.DeleteListItems))
                    {
                        xhtml += string.Format(cmdPatterna, "MenuItem", "Complete Commitment", Page.ResolveUrl("~/_layouts/images/star.gif"), "closeitem('" + itemID + "')");
                        xhtml += string.Format(cmdPatterna, "MenuItem", "Delete Commitment", Page.ResolveUrl("~/_layouts/images/delete.gif"), "deleteitem('" + itemID + "')");
                    }
                    else
                    {
                        if (pref["AllowCloseout"].ToString().Equals("Yes"))
                        {
                            if (item["Status"].ToString().Equals("In Progress")) { xhtml += string.Format(cmdPatterna, "MenuItem", "Complete Commitment", Page.ResolveUrl("~/_layouts/images/star.gif"), "closeitem('" + itemID + "')"); }
                        }
                        else
                        {
                            if (item["Status"].ToString().Equals("In Progress")) { xhtml += string.Format(cmdPatterna, "MenuItem", "Create Complete Request", Page.ResolveUrl("~/_layouts/images/icspgen.gif"), "createcloseout('" + itemID + "')"); }
                        }
                    }
                }
            }
            else
            {
                if (web.IsCurrentUserMemberOfGroup(web.Groups["CTS Dept Power Users"].ID) == true || web.IsCurrentUserMemberOfGroup(web.Groups["CTS Dept Users"].ID) == true)
                {
                    if (item["Priority"].ToString().Contains("Interdepartmental"))  // Interdepartmental commitment
                    {
                        if (item["AssignedDepartment"].ToString().Equals(user["CTSDepartment"].ToString()))
                        {
                            xhtml += string.Format(cmdPatterna, "MenuItem", "Create Concurrence Request", Page.ResolveUrl("~/_layouts/images/icspgen.gif"), "concurrence('" + itemID + "')");
                            xhtml += string.Format(cmdPatterna, "MenuItem", "Revise ECD", Page.ResolveUrl("~/_layouts/images/icspgen.gif"), "revecd('" + itemID + "')");
                            xhtml += string.Format(cmdPatterna, "MenuItem", "Edit Commitment", Page.ResolveUrl("~/_layouts/images/edit.gif"), "edititem('" + itemID + "', '" + item["Priority"].ToString() + "')");
                            if (pref["AllowCloseout"].ToString().Equals("Yes"))
                            {
                                if (item["Status"].ToString().Equals("In Progress")) { xhtml += string.Format(cmdPatterna, "MenuItem", "Complete Commitment", Page.ResolveUrl("~/_layouts/images/star.gif"), "closeitem('" + itemID + "')"); }
                            }
                            else
                            {
                                if (item["Status"].ToString().Equals("In Progress")) { xhtml += string.Format(cmdPatterna, "MenuItem", "Create Complete Request", Page.ResolveUrl("~/_layouts/images/icspgen.gif"), "createcloseout('" + itemID + "')"); }
                            }
                            if (list.DoesUserHavePermissions(SPBasePermissions.DeleteListItems) && item["Status"].ToString().Equals("In Progress")) { xhtml += string.Format(cmdPatterna, "MenuItem", "Delete Commitment", Page.ResolveUrl("~/_layouts/images/delete.gif"), "deleteitem('" + itemID + "')"); }
                        }
                        else
                        {
                            // not in assigned dept!
                        }
                    }
                    else  //critical or commitment
                    {
                        // Already have the print and view options at the top
                    }
                }
            }
        }            
    }
        
    catch { }
        
    xhtml += "";
    this.Page.Response.Write(xhtml);
    this.Page.Response.End();          
}

There is one thing I want to point out here in that due to the code formatting, the commandpattern line is not formatted correctly due to the </Script> tag. If you pasted this code into Visual Studio for example, it will show an error unless you escape the slash with a \

Now, as you can see, there is a lot of stuff here. I wanted to get it out there for you and I will go over it more in the next post. Sorry, but there is a lot here and I really want to get into it! Until then!

No comments:

Post a Comment