Search This Blog

Thursday, May 12, 2016

Get the GUID value of a SharePoint List and item ID using Javascript

I coded some Javascript that will retrieve the GUID value of a SharePoint list and the first item ID of that list.
Once all the values have been determined, Javascript will open the Infopath form of that list using the
SharePoint Client Side Dialog object.
<script type="text/javascript">


 function OpenDialogOki() {
       
       var options = SP.UI.$create_DialogOptions();
       options.resizable = 1;
       options.scroll = 1;
        
         clientContext = new SP.ClientContext.get_current();                    
        spWebobj = this.clientContext.get_web();
        spListobj = spWebobj.get_lists().getByTitle("MessagefromOki");
        var spCamlQuery = new SP.CamlQuery();
        var spViewXML = '<View><Query /></View>';
        spCamlQuery.set_viewXml(spViewXML);
        spListobjItems = spListobj.getItems(spCamlQuery);
     
             
        clientContext.load(spWebobj);
        clientContext.load(spListobjItems);  
        this.collList = spWebobj.get_lists();
        clientContext.load(collList, 'Include(Title, Id)');
         
        // get the GUID info
        var listInfo = '';
        var listEnumerator = collList.getEnumerator();
               while (listEnumerator.moveNext()) {
                    var oList = listEnumerator.get_current();
                      
                    if ( oList.get_title() == "MessageFromOki") {
                         listInfo += 'Title: ' + oList.get_title() + ' ID: ' 
                           + oList.get_id().toString() + '\n';
                         var oki_guid = oList.get_id().toString();
                          } 
                       }
                 
         //window.OkiItemID - global variable of the list item ID               
          options.url =  "/Lists/MessageFromOki/Item/displayifs.aspx?List=" 
         + oki_guid + "&ID=" + window.OkiItemID;
          SP.UI.ModalDialog.showModalDialog(options);
   } 
    

  
 function OpenDialogSal() {
       
       var options = SP.UI.$create_DialogOptions();
       options.resizable = 1;
       options.scroll = 1;
        
        clientContext = new SP.ClientContext.get_current();                 
        spWebobj = this.clientContext.get_web();
        spListobj = spWebobj.get_lists().getByTitle("MessagefromSal");
        var spCamlQuery = new SP.CamlQuery();
        var spViewXML = '<View><Query /></View>';
        spCamlQuery.set_viewXml(spViewXML);
        spListobjItems = spListobj.getItems(spCamlQuery);
     
             
        clientContext.load(spWebobj);
        clientContext.load(spListobjItems);  
        this.collList = spWebobj.get_lists();
        clientContext.load(collList, 'Include(Title, Id)');
         
        // get the GUID info
        var listInfo = '';
        var listEnumerator = collList.getEnumerator();
               while (listEnumerator.moveNext()) {
                    var oList = listEnumerator.get_current();
                      
                    if ( oList.get_title() == "MessageFromSal") {
                         listInfo += 'Title: ' + oList.get_title() + ' ID: ' + oList.get_id().toString() + '\n';
                         var sal_guid = oList.get_id().toString();
                          } 
                       }
          options.url =  "/_layouts/listform.aspx?PageType=4&ListId=" + sal_guid + "&ID=" + window.SalItemID;
      
         SP.UI.ModalDialog.showModalDialog(options);
   } 
  
                var tpj = jQuery;
                tpj.noConflict();
                  
                tpj(document).ready(function () {
             
              if (typeof(_spBodyOnLoadWrapper) != 'undefined') {
                   _spBodyOnLoadWrapper();
              }
               
               
               
              if (tpj.fn.cssOriginal != undefined)
                        tpj.fn.css = tpj.fn.cssOriginal;
                        tpj('#services-example-1').services(
                        {
                            width: 920,
                            height: 300,
                            slideAmount: 5,
                            slideSpacing: 30,
                            carousel: "off",
                            touchenabled: "on",
                            mouseWheel: "on",
                            hoverAlpha: "off",           
                           // Turns Alpha Fade on/off by Hovering
                            slideshow: 0,              
                            // 0 = No SlideShow, 1000 = 1 sec Slideshow 
                              (rotating automatically)
                            hovereffect: "on",          
                           // All Hovereffect on/off
                            callBack: function () { }   
                            //Callback any Function after loaded
                           
                        });
                     });
                 
                 
                             
                 
                               
              ExecuteOrDelayUntilScriptLoaded(getOkiTitle, "sp.js");
                     
                 function getOkiTitle() {
                    
                    clientContext = new SP.ClientContext.get_current();                 
                    spWebobj = this.clientContext.get_web();
                    spListobj = spWebobj.get_lists().getByTitle("MessagefromOki");
                    var spCamlQuery = new SP.CamlQuery();
                    var spViewXML = '<View><Query /></View>';
                    spCamlQuery.set_viewXml(spViewXML);
                    spListobjItems = spListobj.getItems(spCamlQuery);
                    clientContext.load(spWebobj);
                    clientContext.load(spListobjItems);                     
                                         
                    // need to retrieve GUID for List MessageFromSal, MessageFromOki
                     this.collList = spWebobj.get_lists();
                     clientContext.load(collList, 'Include(Title, Id)');
                     clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), 
                Function.createDelegate(this, this.onQueryFailed));
         
                     
                }
                 
                 
                                 
             function onQuerySucceeded() {
                clientContext.executeQueryAsync(onSuccess, onFail);
               }
             
             function onQueryFailed(sender, args) {
                alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
             }

     
            function GetSalTitle() {
                    clientContext = new SP.ClientContext.get_current();
                    spWebobj = this.clientContext.get_web();
                    spListobj = spWebobj.get_lists().getByTitle("MessagefromSal");              
                    var spCamlQuery = new SP.CamlQuery();
                    var spViewXML = '<View><Query /></View>';
                    spCamlQuery.set_viewXml(spViewXML);
                    spListobjItems = spListobj.getItems(spCamlQuery);
                    clientContext.load(spWebobj);
                    clientContext.load(spListobjItems);
                    clientContext.executeQueryAsync(onSuccess2, onFail);
                }
                     
                     
            function onSuccess2() {
                     
                        liCount = spListobjItems.get_count();
                        //alert (liCount);
                        for (x = 0; x < liCount; x++) {
                            var listItem = spListobjItems.itemAt(x);
                            var itemTitle  = listItem.get_item('Title');
                            var SalItemID  = listItem.get_id();
                            //window.SalItemID = SalItemID;  
                            //display dynamic title on the page
                            document.getElementById("SaloTitle").innerHTML = itemTitle;     
                           window.SalItemID = SalItemID; 
                             
                       }
     
                     
                 
                function onSuccess() {
                    // get the GUID value of MessageFromOki list
                        liCount = spListobjItems.get_count();
                        for (x = 0; x < liCount; x++) {
                            var listItem = spListobjItems.itemAt(x);
                            var itemTitle  = listItem.get_item('Title');
                            var OkiItemID  = listItem.get_id();
                            //display dynamic title on the page
                            document.getElementById("OkiTitle").innerHTML = itemTitle;
                                                       
                         }
                        // global variable of the list item to display
                         window.OkiItemID = OkiItemID;  
                         GetSalTitle()
                        }
     
                    function onFail() {
                        alert('request failed ' + args.get_message() + '\n'
                      + args.get_stackTrace());   
                    }
                     

                 
             
            </script>

How to send E-Mail using SPUtility.SendEmail


SharePoint SPUtility class has SendEmail method which is used to send email to any email address. By default, SPUtility.SendEmail() method picks the 'From address' from Outgoing E-Mail Settings in Central administration. Use SPUtility.IsEmailServerSet method to check if server is configured with SMTP mail settings.

Here is a C# Example for sending E-mail using SPUtility.SendEmail:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.IO;
using Microsoft.SharePoint.Utilities;
using System.Collections.Specialized;
 
namespace HideUserInfo
{
    class SendEMail
    {
        static void Main(string[] args)
        {
 
            using (SPSite oSPSite = new SPSite("https://sharepoint.com"))  //Site collection URL
            {
                using (SPWeb oSPWeb = oSPSite.OpenWeb("News"))  //Subsite URL
                {
                    StringDictionary headers = new StringDictionary();
 
                    headers.Add("from""sender@domain.com");
                    headers.Add("to""receiver@domain.com");
                    headers..add("bcc","SharePointAdmin@domain.com");
                    headers.Add("subject""Welcome to the SharePoint");
                    headers.Add("fAppendHtmlTag","True"); //To enable HTML format
 
                    System.Text.StringBuilder strMessage = new System.Text.StringBuilder();
                    strMessage.Append("Message from CEO:");
                    
                    strMessage.Append("<span style='color:red;'> Make sure you have completed the survey! </span>");
                    SPUtility.SendEmail(oSPWeb, headers, strMessage.ToString());
 
                }
            }
        }
    }
}



Open SharePoint 2010 modal dialog and refresh the parent page from custom form

Objective:

1) Open a SharePoint 2010 popup and refresh the parent page when one closes it.
2) Build a custom form that at “submit event” closes the popup and refreshes the parent page.
Solution:
-          Open a Popup using “Javascript” and “SP.UI.$create_DialogOptions();”
-          Add the method “CloseCallback” using the “dialogReturnValueCallback” property
-          Add some JavaScript code inside the CloseCallback to reload the parent page, like the following
 example:

<a href="javascript:openModalDialog('form.aspx');">Open My Custom Form</a>

<SharePoint:ScriptLink ID="ScriptLink1" Name="sp.js" runat="server" OnDemand="true" Localizable="false"
 />

<script type="text/ecmascript">

    var options;
    function openModalDialog() {
        options = SP.UI.$create_DialogOptions();
        options.width = 300;
        options.height = 100;
        options.url = SP.Utilities.Utility.getLayoutsPageUrl('customdialog.htm' );
        options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);
        SP.UI.ModalDialog.showModalDialog(options);

    }

    function CloseCallback(result, target) {
        location.reload(true);
    }

</script>

Now when you close the popup, the parent page is refreshed.
If one is working with a Custom Form and wants to close the popup and refresh the parent after
 the Submit,
he could have two (or more) choices:
1) If you have 1 post back only, after the submit, the you can add in the page load the following:
protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
            {
                string script = "<script language='javascript'>parent.CloseCallback();</script>";
                if (!this.Page.ClientScript.IsClientScriptBlockRegistered("rKey"))
                    this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "rKey", script);
            }
        }

          2) If your custom form handles more than 1 post back, you can add the following code at one 
specific submit click event:
Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup()
;</script>");
Context.Response.Flush();
Context.Response.End();
The last script is suggested at the following link: http://social.msdn.microsoft.com/Forums/en-

Show a document library hierarchy in a tree view

Objective:

To programmatically build a tree view that shows a specific document library.
Solution:
To achieve this goal, SharePoint offers the classes:
SPHierarchyDataSourceControl
SPTreeView
With SPHierarchyDataSourceControl you can build the entire hierarchy of you web. In this case we need 
to limit it to a single document library.
Build a new Web Part and override the CreateChildControls method with the following code, modifying 
the data source with your needed:

protected override void CreateChildControls()
{
           
        SPDocumentLibrary docLib = GetDocLib(SPContext.Current.Web.ServerRelativeUrl, "Shared Documents");
        //change GetDocLib with your code to get a SPDocumentLibrary object

SPHierarchyDataSourceControl myDataSource = new SPHierarchyDataSourceControl();
myDataSource.ID = "myTreeViewDataSource";
myDataSource.RootContextObject = "Web";
        myDataSource.IncludeDiscussionFolders = false;
        myDataSource.ShowDocLibChildren = true;
        myDataSource.ShowFolderChildren = true;
        myDataSource.ShowListChildren = false;
        myDataSource.ShowWebChildren = false;
        myDataSource.Web = SPContext.Current.Web;
        myDataSource.RootWebId = SPContext.Current.Web.ID.ToString();
        myDataSource.RootContextObject = null;
        myDataSource.RootListId = docLib.ID.ToString();
           

        SPTreeView myTreeView = new SPTreeView();
        myTreeView.ID = "myTreeView";
        myTreeView.DataSourceID = "myTreeViewDataSource";
        myTreeView.EnableClientScript = true;
        myTreeView.EnableViewState = true;
        myTreeView.NodeIndent = 12;
        myTreeView.NodeStyle.CssClass = "ms-navitem";
        myTreeView.NodeStyle.HorizontalPadding = 2;
        myTreeView.SelectedNodeStyle.CssClass = "ms-tvselected";
        myTreeView.ExpandDepth = 0;
        myTreeView.ExpandImageUrl = 
        SPUrlUtility.CombineUrl(SPContext.Current.Web.ServerRelativeUrl, "/_layouts/images/tvplus.gif");

        myTreeView.CollapseImageUrl =
        SPUrlUtility.CombineUrl(SPContext.Current.Web.ServerRelativeUrl, "/_layouts/images/ tvminus.gif");

        myTreeView.NoExpandImageUrl = 
       SPUrlUtility.CombineUrl(SPContext.Current.Web.ServerRelativeUrl, "/_layouts/images/ tvblank.gif");

        myTreeView.SkipLinkText = "";
        myTreeView.ShowLines = true;
        Controls.Add(myTreeView);
}

Enable Ribbon button when one item only is selected and it is not folder

Objective:

To programmatically enable a ribbon button by JavaScript, when one item only is selected.

Solution:
Edit the element.xml file of the Ribbon button Custom Action.
In the CommandUIHandles section

<CommandUIHandlers>
        <CommandUIHandler
                Command="CommandName"
                CommandAction=" … "
                EnabledScript=" …  "/>
      </CommandUIHandlers>
</CommandUIHandlers>
Add the following JavaScript code in EnabledScript:

EnabledScript="javascript:
        function enable() {
        var items = SP.ListOperation.Selection.getSelectedItems();
        var itemCount = CountDictionary(items);
        return (itemCount==1 &amp;&amp; items[0].fsObjType == 0);
        }enable();

itemCount==1  is used to identify if one item only is selected

If this condition is TRUE it means that the “items” array contains the element 0.
So it is possible to test if is it a folder with the following:

 items[0].fsObjType == 0

If you write you JavaScript code in the Element.xml file, you need to encode the operator AND:
 &amp;&amp;

Sandbox Solution Limitations: Workarounds.

1) Cannot use Visual Web Part     

      You can!
      Install the Visual Studio 2010 SharePoint Power Tools:        
     http://visualstudiogallery.msdn.microsoft.com/8e602a8c-6714-4549-9e95-f3700344b0d9/ 
     ant you will find a new "Visual Web Part (Sandboxed)" template.



2) Cannot deploy files on layouts folder
     You can use a Module to deploy files on your application, without using Document Library.


     You can read the files appending the Module URL to your site collection URL:
     http://[MyHostName]/[MySiteCollection]/MyFiles/js/jquery-1.4.4.min.js

 3) Cannot use Application Pages with code behind
      You can deploy an application page using a Module and add a Sandboxed Web Part to use code behind.
       SharePoint offers a specific class name <WebPartPages:SPUserCodeWebPart > to archives this goal. 
       At the following link you can find a good example:
       http://www.wictorwilen.se/Post/Custom-application-pages-in-the-SharePoint-2010-Sandbox.aspx

Add an existing site collection Group to sub site with modified Roles

OBJECTIVE


The site collection contains a group named “All Members” with “Contributor” privilege.
I want to add this group programmatically to a sub site and modify its roles from “Contributor” to 
Read” without modifying the original group.

The following are the variables used in the code:
       -          site: the SPSite object of the site collection being used
-          web: the SPWeb object of the sub site you want to add the group to.

SOLUTION:
SPGroup group = site.RootWeb.SiteGroups["All Members"];
SPRoleAssignment roleAssignment = new SPRoleAssignment(group);
SPRoleDefinition roleDefinition = site.RootWeb.RoleDefinitions["Read"];
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
if (!web.HasUniqueRoleAssignments)
     web.BreakRoleInheritance(true);
web.RoleAssignments.Add(roleAssignment);

---------------------------------------------------------------------------

Working with Group: quick review:
      1)       BREAK INHERITANCE  
         2)       ADD NEW GROUP TO SITE COLLECTION 
         3)       ASSOCIATE THE NEW GROUP TO A WEB 
         4)       ASSIGNMENT OF THE ROLES
         5)       ADD USERS TO THE GROUP 
         6)       REMOVE ALL ROLES
     

1) BREAK INHERITANCE
if (!web.HasUniqueRoleAssignments)
            web.BreakRoleInheritance(true);

2) ADD NEW GROUP TO SITE COLLECTION:
web.SiteGroups.Add("MyNewGroup", web.AssociatedOwnerGroup, null"MyNewGroup description");

3) ASSOCIATE THE NEW GROUP TO A WEB:
web.AssociatedGroups.Add(group);
web.Update();

4) ASSIGNMENT OF THE ROLES:
SPGroup group = web.SiteGroups["MyNewGroup"];
SPRoleAssignment roleAssignment = new SPRoleAssignment(group);
SPRoleDefinition roleDefinition = site.RootWeb.RoleDefinitions["Read"];
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
web.RoleAssignments.Add(roleAssignment);

5) ADD USERS TO THE GROUP:
SPUser user = web.EnsureUser("domain\MyUser"); 
SPGroup group = web.Groups["MyNewGroup"];                        
if(user!=null && group!=null)
     group.AddUser(user);

6) REMOVE ALL ROLES:
SPRoleAssignmentCollection SPRoleAssColn = web.RoleAssignments;
for (int i = SPRoleAssColn.Count - 1; i >= 0; i--)
{
      SPRoleAssColn.Remove(i);
}