Tuesday, May 31, 2016

List/library roles/permissions & folder/item level - unique permissions report to csv file

List level roles.. folder/item level - unique permissions report to csv file




        public static void GetAllFolderNfilesPermissionNAdd2MYSPGroup(SPWeb webElevated, string selectedLibrary)
        {
            try
            {
                SPList list = webElevated.Lists.TryGetList(selectedLibrary);
                if (list != null)
                {
                    string selectedLibraryRolesCSV = selectedLibrary.ToString() + "_UserRoles_Report.csv";

                    StreamWriter SW;
                    SPListItem itemNull = null;

                    SW = File.AppendText("C:\\" + selectedLibraryRolesCSV);

                    SW.WriteLine("File Name, User Name, Group Name, Permission Type, FileID, File Location, Folder Name, Unique Permission");
                    // List level permissions
                    if (list.RoleAssignments.Count > 0)
                    {
                        foreach (SPRoleAssignment asignment in list.RoleAssignments)
                        {
                            rolesAssigmentNWrite2Report(asignment, selectedLibrary, SW, itemNull, false, false);
                        }
                    }
                    else
                    {
                        bool listUniqueRightes = list.HasUniqueRoleAssignments;
                        SW.WriteLine("" + "," + "" + "," + "" + "," + "LIST OR LIB IS NOT SHARED WITH ANYONE" + "," + " " + "," + " " + "," + " " + "," + listUniqueRightes);
                    }


                    // Folder level permissions
                    foreach (SPListItem folderItem in list.Folders)
                    {
                        bool uniqueRoleAssignmentObj = folderItem.HasUniqueRoleAssignments;

                        if (uniqueRoleAssignmentObj)
                        {
                            if (folderItem.RoleAssignments.Count > 0)
                            {
                                foreach (SPRoleAssignment asignment in folderItem.RoleAssignments)
                                {
                                    rolesAssigmentNWrite2Report(asignment, selectedLibrary, SW, folderItem, true, false);
                                }
                            }
                            else
                            { // Not Share with anyone
                                SPRoleAssignment asignment = null;
                                rolesAssigmentNWrite2Report(asignment, selectedLibrary, SW, folderItem, true, true);
                            }
                            // Get files in side folder
                            //SPFolder folder = folderItem.Folder;
                            //foreach (SPFile file in folder.Files)
                            //{ // file operations }
                        }
                    }
                   
                    //Item/file level permissions
                    SPView Myview = list.Views["All Documents"];
                    SPQuery oQuery = new SPQuery(Myview);
                    oQuery.ViewAttributes = "Scope=\"Recursive\"";
                    SPListItemCollection itemColl = list.GetItems(oQuery);

                    foreach (SPListItem item in itemColl)
                    {
                        bool uniqueRoleAssignmentObj = item.HasUniqueRoleAssignments;

                        if (uniqueRoleAssignmentObj)
                        {
                           //
                            if (item.RoleAssignments.Count > 0)
                            {
                                foreach (SPRoleAssignment asignment in item.RoleAssignments)
                                {
                                    rolesAssigmentNWrite2Report(asignment, selectedLibrary, SW, item, true, false);
                                }
                            }
                            else
                            { // Not Share with anyone
                                SPRoleAssignment asignment = null;
                                rolesAssigmentNWrite2Report(asignment, selectedLibrary, SW, item, true, true);
                            }
                        }

                    }
                    SW.Close();
                }
            }
            catch (Exception ex)
            {

            }

        }
        public static void rolesAssigmentNWrite2Report(SPRoleAssignment asignment, string selectedLibrary, StreamWriter SW, SPListItem item, bool isSPListItem, bool notSharedwithAnyone)
        {
            try
            {
                if (notSharedwithAnyone)
                {   //Item/folder if not shared with anyone                
                    SW.WriteLine(item.Name + "," + "NOT SHARED WITH ANYONE" + "," + "NOT SHARED WITH ANYONE" + "," + "NOT SHARED WITH ANYONE" + "," + item.ID + "," + item.Url + "," + item.Name + "," + "Yes");
                }
                else
                {
                    if (asignment != null)
                    {
                        foreach (SPRoleDefinition roleDefinition in asignment.RoleDefinitionBindings)
                        {
                            string groupName = ""; string UserName = ""; string PermissionType = "";
                            if (asignment.Member is SPUser)
                            {
                                //UserName = ((SPUser)asignment.Member).ToString();
                                SPUser user = ((SPUser)asignment.Member);
                                UserName = user.Name;
                                addUserToMyGroup(webElevated, user, selectedLibrary);
                                PermissionType = roleDefinition.Name.ToString();
                            }
                            else if (asignment.Member is SPGroup)
                            {
                                SPGroup grp = (SPGroup)asignment.Member;
                                groupName = grp.Name;
                                foreach (SPUser user in grp.Users)
                                {
                                    PermissionType = roleDefinition.Name.ToString();
                                    addUserToMyGroup (webElevated, user, selectedLibrary);
                                }

                            }
                            if (isSPListItem)
                            {
                                string folderName = "";

                                if (item.Folder != null)
                                {
                                    folderName = item.Folder.ToString();
                                }
                                // SW.WriteLine("1.UserName, 2.GroupName,      3.PermissionType,        4.FileName, 5.FileID, 6.FileUrl, 7.FolderName, 8.HASUnicPermission");
                                SW.WriteLine(item.Name + "," + UserName + "," + groupName + "," + PermissionType + "," + item.ID + "," + item.Url + "," + folderName + "," + "Yes");
                            }
                            else
                            { // list level permissions
                                SW.WriteLine("DTR: " + selectedLibrary + "," + UserName + "," + groupName + "," + PermissionType + "," + "NA" + "," + "NA" + "," + "NA" + "," + "NA");
                            }

                            //  1.UserName, 2.GroupName, 3.PermissionType, 4.FileName, 5.FileID, 6.FileUrl, 7.FolderName, 8.HASUnicPermission
                        }
                    }
                }


            }
            catch (Exception ex12) { }

        }

        public static void addUserToMyGroup(SPWeb elevweb, SPUser user, string selectedLibraryName)
        {
            string dtRoomGrpName = selectedLibraryName + "_ViewOnly";

            try
            {
                elevweb.AllowUnsafeUpdates = true;
                SPGroup grp = elevweb.Groups.GetByName(dtRoomGrpName);
                grp.AddUser(user);
                elevweb.Update();
                elevweb.AllowUnsafeUpdates = false;
            }
            catch (Exception ex)
            {
                // msgError("Error while adding user into site Access: " + x.Message);
            }

        }

Tuesday, May 17, 2016

Custom site page, add to pages library & set as default SharePoint2013 Home/Welcome page


Step1: Add module to the Project, Rename sample.txt as myPage.aspx.

aspx code goes here... change CodeBehind and Inherits once you add Code behind file in step2...

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>

<%@ Page Language="C#" CodeBehind="PageName.aspx.cs" Inherits="ProjectName.ModuleName.PageName, $SharePoint.Project.AssemblyFullName$" MasterPageFile="~masterurl/default.master"      MainContentID="PlaceHolderMain" meta:webpartpageexpansion="full" meta:progid="SharePoint.WebPartPage.Document" %>

<%@ Import Namespace="Microsoft.SharePoint.WebPartPages" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>






<asp:Content ContentPlaceHolderId="PlaceHolderPageTitle" runat="server">
       <SharePoint:ProjectProperty Property="Title" runat="server"/> - <SharePoint:ListItemProperty runat="server"/>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderPageImage" runat="server"><SharePoint:AlphaImage ID=onetidtpweb1 Src="/_layouts/15/images/wiki.png?rev=23" Width=145 Height=54 Alt="" Runat="server"/></asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderAdditionalPageHead" runat="server">
       <meta name="CollaborationServer" content="SharePoint Team Web Site" />
       <SharePoint:ScriptBlock runat="server">
       var navBarHelpOverrideKey = "WSSEndUser";
       </SharePoint:ScriptBlock>
       <SharePoint:RssLink runat="server"/>
       </asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderMiniConsole" runat="server">
       <SharePoint:FormComponent TemplateName="WikiMiniConsole" ControlMode="Display" runat="server" id="WikiMiniConsole"/>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderLeftActions" runat="server">
       <SharePoint:RecentChangesMenu runat="server" id="RecentChanges"/>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">

    <asp:Label ID="lblmsg" runat="server" ForeColor="Blue"></asp:Label>



       <span id="wikiPageNameDisplay" style="display: none;" runat="server">
              <SharePoint:ListItemProperty runat="server"/>
       </span>
       <span style="display:none;" id="wikiPageNameEdit" runat="server">
              <asp:TextBox id="wikiPageNameEditTextBox" runat="server"/>
       </span>

       <SharePoint:VersionedPlaceHolder UIVersion="4" runat="server">
              <SharePoint:SPRibbonButton
                     id="btnWikiEdit"
                     RibbonCommand="Ribbon.WikiPageTab.EditAndCheckout.SaveEdit.Menu.SaveEdit.Edit"
                     runat="server"
                     Text="edit"/>
              <SharePoint:SPRibbonButton
                     id="btnWikiSave"
                     RibbonCommand="Ribbon.WikiPageTab.EditAndCheckout.SaveEdit.Menu.SaveEdit.SaveAndStop"
                     runat="server"
                     Text="edit"/>
              <SharePoint:SPRibbonButton
                     id="btnWikiRevert"
                     RibbonCommand="Ribbon.WikiPageTab.EditAndCheckout.SaveEdit.Menu.SaveEdit.Revert"
                     runat="server"
                     Text="Revert"/>
       </SharePoint:VersionedPlaceHolder>
      
       <WebPartPages:WebPartZone runat="server" ID="Bottom" CssClass="ms-hide" Title="loc:Bottom"><ZoneTemplate></ZoneTemplate></WebPartPages:WebPartZone>
</asp:Content>

Step2: select the module and add new Item and add a code file.


ð  Add System.web dll
Make a class as a public and inherit from Webpartpage
Ex:  public class MyPage : WebPartPage
Add page load method if you want and to create any control then create a global object.
Ex:           protected Label lblmsg;
        private void Page_Load()
        {
     }

Open the elemnts.aspx


<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="TestModule"  Url="Pages">
    <File Path="ModuleName\MyPage.aspx" Url="MyPage.aspx" Type="GhostableInLibrary" IgnoreIfAlreadyExists="FALSE" ReplaceContent="TRUE"/>
  </Module>
</Elements>

Add Feature Receiver to set myPage as HomePage.


public static void setMyPageAsWelcomePage(SPWeb webElevated)
        {
            SPFolder pagesFolder = null;

            webElevated.AllowUnsafeUpdates = true;
            if (PublishingWeb.IsPublishingWeb(webElevated))
            {
                PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(webElevated);
                if (publishingWeb != null)
                {
                    SPFolder rootFolder = webElevated.RootFolder;
                    try
                    {
                        pagesFolder = publishingWeb.PagesList.RootFolder;
                    }
                    catch (Exception ex1) { }

                    try
                    {
                        if (rootFolder != null)
                        {
                            if (pagesFolder != null)
                            {
                                string newWelcomePageUrl = publishingWeb.PagesList.Title + "/" + "MyPage.aspx";
                                rootFolder.WelcomePage = newWelcomePageUrl;

                                if (newWelcomePageUrl.StartsWith(pagesFolder.Url, StringComparison.OrdinalIgnoreCase))
                                {
                                    pagesFolder.WelcomePage = newWelcomePageUrl.Substring(publishingWeb.PagesList.RootFolder.Url.Length + 1);
                                    pagesFolder.Update();
                                }
                                rootFolder.Update();
                                webElevated.Update();
                                publishingWeb.Update();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        if (publishingWeb != null)
                        {
                            publishingWeb.Close();
                        }
                    }

                }

            }

            webElevated.AllowUnsafeUpdates = false;
        }


Feature De Activating:

SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    using (SPWeb spWeb = (properties.Feature.Parent as SPWeb))
                    {
                        SPFolder rootFolder = spWeb.RootFolder;
                        rootFolder.WelcomePage = "sitepages/Home.aspx";
                        rootFolder.Update();
                    }
                }
                catch (Exception ex) { }
            });