Wednesday, 7 June 2017

How to get permissions of all SharePoint users using CSOM?

Below code fetches only site level permissions. Same can me modified to fetch all lists and/or list items and check permissions at that level as well.

SecureString securePassword = new SecureString();
            ClientContext context = new ClientContext(txtURL.Text);
            string decryptedPwdt = txtPassword.Text;
            foreach (char c in decryptedPwdt)
            {
                securePassword.AppendChar(c);
            }
            context.Credentials = new NetworkCredential(txtUser.Text, decryptedPwdt, "Domain");
            Web web = context.Web;
            context.Load(web);

            UserCollection userColl = web.SiteUsers;
            context.Load(userColl);

            var assignments = web.RoleAssignments;
            context.Load(assignments, ac => ac.Include(
                a => a.RoleDefinitionBindings, a => a.Member.LoginName));

            context.ExecuteQuery();
            context.RequestTimeout = 9999999;
            DataTable dt = new DataTable();
            dt.Columns.Add("User");
            dt.Columns.Add("Permission");

            foreach (User user in userColl)
            {
                try
                {
                    var permissions = web.GetUserEffectivePermissions(user.LoginName);
                    context.ExecuteQuery();

                    if (permissions != null)
                    {
                        if (permissions.Value.Has(PermissionKind.ManageWeb))
                        {
                            dt.Rows.Add(user.Email, "Full Controll");
                        }
                        else if (permissions.Value.Has(PermissionKind.ManageLists))
                        {
                            dt.Rows.Add(user.Email, "Edit");
                        }
                        else if (permissions.Value.Has(PermissionKind.DeleteListItems))
                        {
                            dt.Rows.Add(user.Email, "Contribute");
                        }
                        else if (permissions.Value.Has(PermissionKind.ViewListItems))
                        {
                            dt.Rows.Add(user.Email, "Read");
                        }
                    }
                }
                catch { }
            }
            dataGridPermissions.DataSource = dt;
            MessageBox.Show("Done!");

How to get permissions of all SharePoint users using Server Side code?

Below code fetches only site level permissions. Same can me modified to fetch all lists and/or list items and check permissions at that level as well.

string startedAt = System.DateTime.Now.ToShortTimeString();
            SPSite site = new SPSite(txtURL.Text);
            SPWeb web = site.OpenWeb();

            SPUserCollection users = web.SiteUsers;

            DataTable dt = new DataTable();
            dt.Columns.Add("User");
            dt.Columns.Add("Permission");

            foreach (SPUser user in users)
            {
                try
                {
                    SPBasePermissions permissions = web.GetUserEffectivePermissions(user.LoginName);
                    if (permissions != null)
                    {
                        if (permissions.HasFlag(SPBasePermissions.ManagePermissions))
                        {
                            dt.Rows.Add(user.Email, "Full Controll");
                        }
                        else if (permissions.HasFlag(SPBasePermissions.ManageLists))
                        {
                            dt.Rows.Add(user.Email, "Edit");
                        }
                        else if (permissions.HasFlag(SPBasePermissions.DeleteListItems))
                        {
                            dt.Rows.Add(user.Email, "Contribute");
                        }
                        else if (permissions.HasFlag(SPBasePermissions.ViewListItems))
                        {
                            dt.Rows.Add(user.Email, "Read");
                        }
                    }
                }
                catch { }
            }
            gridPermissions.DataSource = dt;
            MessageBox.Show("Done!\r\n\r\nStart Time: "
                + startedAt
                + "\r\n\r\nEnd Time: "
                + System.DateTime.Now.ToShortTimeString()); 

Monday, 29 May 2017

SharePoint Carousel: How to create SharePoint Image plus text carousel on an Application page?


References:

<script src="scripts/jquery-1.8.3.min.js"></script>
<script src="scripts/SPService0.7.1a.js"></script>
<script src="scripts/unslider.min.js"></script>
<link href="styles/Welcome.css" rel="stylesheet" />

<script src="scripts/Welcome.js"></script>

HTML:

<div class="Banner">
                    <ul id='Slider'></ul>

                    <a href="#" class="unslider-arrow prev">
                        <span style="color: white; font-weight: bold;">&lt;</span>
                    </a>
                    <a href="#" class="unslider-arrow next">
                        <span style="color: white; font-weight: bold;">&gt;</span>
                    </a>

 </div>

Script:

jQuery(document).ready(function($) {
 
    var sliderList = "Slider"; // Name of the list that contains slides
    var slideContentField = "HTML"; //Name of the Rich text field that has slide content
    var slideBackgroundImageField = "Picture"; //Name of the picture field to use as background image

    Slider(sliderList, slideContentField, slideBackgroundImageField);


    });


function Slider(sliderList,slideContentField,slideBackgroundImageField) {
 
    //query to retrieve all items
    var query = "<Query><Where><Neq><FieldRef Name='ID' /><Value Type='Number'></Value></Neq></Where></Query>";
 
    //return fields for slide content and background picture
    var camlViewFields = "<ViewFields><FieldRef Name='"+slideContentField+"' /><FieldRef Name='"+slideBackgroundImageField+"' /></ViewFields>";
 
    $().SPServices({
        operation: "GetListItems",
        async: true,
        listName: sliderList,
        CAMLViewFields: camlViewFields,
        CAMLQuery: query,
        completefunc: function(xData, Status) {
            $(xData.responseXML).SPFilterNode("z:row").each(function() {
                var slideContent = ($(this).attr("ows_"+slideContentField));
                var picture = $(this).attr("ows_"+slideBackgroundImageField)==undefined?"":$(this).attr("ows_"+slideBackgroundImageField).split(",")[0];
                //create slide (li) and append it to other slides
                $("#Slider").append("<li style=\"background-image: url('" + picture + "');background-repeat: no-repeat;background-position: right;\">" + slideContent + "</li>");
                }); // end completefunc
            //start the slider
            $('.Banner').unslider({
                speed: 500,               //  The speed to animate each slide (in milliseconds)
                delay: 3000,              //  The delay between slide animations (in milliseconds)
                complete: function () { },  //  A function that gets called after every slide animation
                keys: false,               //  Enable keyboard (left, right) arrow shortcuts
                dots: true,               //  Display dot navigation
                fluid: false              //  Support responsive design. May break non-responsive designs

            });

            var unslider = $('.Banner').unslider();

            $('.prev').click(function (event) {
                 event.preventDefault();
                unslider.data('unslider').prev();
            });

            $('.next').click(function (event) {
                event.preventDefault();
                unslider.data('unslider').next();
            });
            }
    }); // end SPServices call
}

CSS:

.Banner { position: relative; overflow: auto;  }
/*Adjust height from HTML div in the slider list*/
.Banner li { list-style: none; margin-top:-15px;}
.Banner ul li { float: left; }

.Banner ul {margin-left: -40px;}

.unslider-arrow {
  font-family: Expressway;
  font-size: 20px;
  text-decoration: none;
  color: #fff;
  background: rgba(255,255,255,0.7);
  padding: 0 20px 5px 20px;
}

.next {
  position: absolute;
  top: 91%;
  right: 48%;
}

.prev {
  position: absolute;
  top: 91%;
  right: 52%; /* change to left:0; if u wanna have arrow on left side */
}


Source: 

1. http://unslider.com/
2. http://summit7systems.com/a-simple-jquery-content-slider-for-sharepoint-200720102013-and-o365/

Friday, 28 April 2017

InfoPath Form: How to populate field on form load based on current user?


List One: Contains Account ID of the users and other fields.
List Two: Has the info-path form.

Customize List Two in InfoPath form:

Step 1. Create a connection to List One. Uncheck below option:

  • Store a copy of the data..
  • Automatically retrieve the data..
Step 2. Add a new rule under Form Load without any condition. Add 3 actions:
  1. Set a field's value:  Set the query field value for the above connection to filter the list item from List One. You can use userName() function to assign the value.
  2. Query using a data connection: Query for data from the above connection
  3. Set a field's value: Get the value from the data field  from the connection string and assign it to the form's field.

Wednesday, 26 April 2017

How to use SharePoint People Editor?


Designer:

<SharePoint:PeopleEditor ID="peopelID" runat="server" Width="350px" SelectionSet="User"
  MaximumEntities="1" MultiSelect="false" AllowEmpty="false" DoPostBackOnResolve="true"
   ErrorMessage="Type and press the enter key." ValidatorEnabled="true" ForeColor="Blue" >

</SharePoint:PeopleEditor>

Code:

To check if the control contains value:

if (peopelID.ResolvedEntities.Count > 0)

                {Do something...}

To clear the control:

peopelID.CommaSeparatedAccounts = null;

To read value:

PickerEntity picker = (PickerEntity)peopelID.ResolvedEntities[0];

Hashtable hstEntityData = picker.EntityData;

strWorkEmail = Convert.ToString(hstEntityData["Email"]);


CSS:

The control may look different based on the master page being used. So, you may need to use browser's developer tools to look for the style(s) to be changed.

Thursday, 16 March 2017

SharePoint Designer: What does a workflow lookup returns when the item is not found?


Item not found returns: ?????

Unassigned workflow variable returns: ****

Note: If you will look for ID of an item that does not exists then the variable will be assigned to 0.


Tuesday, 7 March 2017

Fixed: SharePoint 2013 workflow not starting on programmatically creating new list item.


For SharePoint 2013:

Just add "Log <this message> to the workflow history list" as the first statement in the workflow.


For SharePoint 2010:

Add below code just after item creation:

using(SPSitesite=newSPSite(web.Url))
{
  foreach(SPWorkflowAssociation spwfa in list.WorkflowAssociations)
  {
   if(spwfa.Name=="WorkFlow Name")
   {
    spwfa.AutoStartCreate=true;
  site.WorkflowManager.StartWorkflow(newItem,spwfa,spwfa.AssociationData);
   }
  }

}