Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Wednesday, 18 December 2019

CSOM : How to remove permission of all the SharePoint users?


public static void RemoveSitePermissions(string strURL)
        {
            AuthenticationManager authManagerSource = new AuthenticationManager();
            using (ClientContext clientContextSource = authManagerSource.GetWebLoginClientContext(strURL))
            {
                clientContextSource.RequestTimeout = 9999999;
                Web sourceWeb = clientContextSource.Web;
                clientContextSource.Load(sourceWeb, w => w.HasUniqueRoleAssignments, w => w.RoleDefinitions, w => w.ServerRelativeUrl, w => w.Title);
                clientContextSource.ExecuteQuery();


                if (sourceWeb.HasUniqueRoleAssignments)
                {
                    RoleAssignmentCollection webRoleAssignments = sourceWeb.RoleAssignments;
                    clientContextSource.Load(webRoleAssignments);
                    clientContextSource.ExecuteQuery();
                    Console.WriteLine("Removing permissions from web..\r\n\r\n");
                    foreach (RoleAssignment webRoleAssignment in webRoleAssignments)
                    {
                        clientContextSource.Load(webRoleAssignment, r => r.Member, r => r.RoleDefinitionBindings);
                        clientContextSource.ExecuteQuery();
                        Principal oPrincipal = webRoleAssignment.Member;
                        if (oPrincipal.PrincipalType == PrincipalType.User)
                        {

                            foreach (RoleDefinition rd in webRoleAssignment.RoleDefinitionBindings)
                            {
                                try
                                {
                                    if (rd.Name != "Limited Access")
                                    {
                                        clientContextSource.Load(rd);
                                        webRoleAssignment.RoleDefinitionBindings.Remove(rd);
                                        webRoleAssignment.Update();
                                        clientContextSource.Load(webRoleAssignment, r => r.Member, r => r.RoleDefinitionBindings);
                                        sourceWeb.Update();
                                        clientContextSource.ExecuteQuery();
                                        Console.Write(".");
                                    }
                                }
                                catch (Exception ex)
                                { }
                            }
                        }
                    }
                }
                ListCollection listColl = sourceWeb.Lists;
                clientContextSource.Load(listColl, lc => lc.Include(l => l.HasUniqueRoleAssignments, l => l.Hidden, l => l.Title));
                clientContextSource.ExecuteQuery();

                foreach (List list in listColl)
                {
                    if (list.HasUniqueRoleAssignments && (!list.Hidden))
                    {

                        RoleAssignmentCollection oRoleAssignments = list.RoleAssignments;
                        clientContextSource.Load(oRoleAssignments);
                        clientContextSource.ExecuteQuery();

                        Console.WriteLine("Removing permissions from lists..\r\n\r\n");
                        foreach (RoleAssignment listRoleAssignment in oRoleAssignments)
                        {
                            clientContextSource.Load(listRoleAssignment, r => r.Member, r => r.RoleDefinitionBindings);
                            clientContextSource.ExecuteQuery();
                            Principal oPrincipal = listRoleAssignment.Member;
                            if (oPrincipal.PrincipalType == PrincipalType.User)
                            {
                                foreach (RoleDefinition rd in listRoleAssignment.RoleDefinitionBindings)
                                {
                                    try
                                    {
                                        if (rd.Name != "Limited Access")
                                        {
                                            clientContextSource.Load(rd);
                                            listRoleAssignment.RoleDefinitionBindings.Remove(rd);
                                            listRoleAssignment.Update();
                                            clientContextSource.Load(listRoleAssignment, r => r.Member, r => r.RoleDefinitionBindings);
                                            list.Update();
                                            clientContextSource.ExecuteQuery();
                                            Console.Write(".");
                                        }
                                    }
                                    catch { }
                                }
                            }
                        }


                    }
                }
            }
        }

Reference: https://sharepoint.stackexchange.com/a/228169

Thursday, 21 November 2019

SSOM: How to copy SharePoint permissions from one user account to another?


protected static void CopySitePermissions_Source_Groups(string strUrl)
        {
            try
            {
                Console.WriteLine("\n\rStarting new site at: " + DateTime.Now + "\n\r");
                LogStartingNewSite(strUrl);
            }
            catch (Exception ex)
            {
                string strmsg = ex.Message;
            }
            using (SPSite site = new SPSite(strUrl))
            {
                using (SPWeb Web = site.OpenWeb())
                {
                    foreach (SPGroup siteGroup in Web.Groups)
                    {
                        foreach (SPUser objUser in siteGroup.Users)
                        {
                            try
                            {
                                string TargetUserID = SourceUserID + "@company.com";

                                if (Web.HasUniqueRoleAssignments)
                                {
                                    CopyUserPermissions(SourceUserID, TargetUserID, Web, Web);
                                }

                                foreach (SPList List in Web.Lists)
                                {
                                    if (List.HasUniqueRoleAssignments && (!List.Hidden))
                                    {
                                        CopyUserPermissions(SourceUserID, TargetUserID, Web, List);
                                    }

                                    if (List.Folders != null)
                                    {
                                        foreach (SPListItem folder in List.Folders)
                                        {
                                            if (folder.HasUniqueRoleAssignments)
                                            {
                                                CopyUserPermissions(SourceUserID, TargetUserID, Web, folder);
                                            }
                                        }
                                    }

                                    foreach (SPListItem item in List.Items)
                                    {
                                        if (item.HasUniqueRoleAssignments)
                                        {
                                            CopyUserPermissions(SourceUserID, TargetUserID, Web, item);
                                        }
                                    }
                                }

                            }
                            catch (Exception ex)
                            {
                                string strEx = ex.Message;
                            }
                        }
                    }

                    foreach (SPUser objUser in Web.Users)
                    {
                        try
                        {
                         
                            string TargetUserID = SourceUserID + "@company.com";

                            if (Web.HasUniqueRoleAssignments)
                            {
                                CopyUserPermissions(SourceUserID, TargetUserID, Web, Web);
                            }

                            foreach (SPList List in Web.Lists)
                            {
                                if (List.HasUniqueRoleAssignments && (!List.Hidden))
                                {
                                    CopyUserPermissions(SourceUserID, TargetUserID, Web, List);
                                }

                                if (List.Folders != null)
                                    {
                                        foreach (SPListItem folder in List.Folders)
                                        {
                                            if (folder.HasUniqueRoleAssignments)
                                            {
                                                CopyUserPermissions(SourceUserID, TargetUserID, Web, folder);
                                            }
                                        }
                                    }

                                    foreach (SPListItem item in List.Items)
                                    {
                                        if (item.HasUniqueRoleAssignments)
                                        {
                                            CopyUserPermissions(SourceUserID, TargetUserID, Web, item);
                                        }
                                    }
                            }
                        }
                        catch (Exception ex)
                        {
                            //log error
                        }
                    }

                }
            }
        }


public static void CopyUserPermissions(string SourceUserID, string TargetUserID, SPWeb web, SPSecurableObject Object)
        {
            try
            {
                var SourceUser = web.EnsureUser(SourceUserID);
                var TargetUser = web.EnsureUser(TargetUserID);

                var SourcePermissions = Object.GetUserEffectivePermissionInfo(SourceUser.LoginName);

                foreach (var SourceRoleAssignment in SourcePermissions.RoleAssignments)
                {
                    List<string> SourceUserPermissions = new List<string>();
                    foreach (SPRoleDefinition SourceRoleDefinition in SourceRoleAssignment.RoleDefinitionBindings)
                    {
                        if (SourceRoleDefinition.Name != "Limited Access")
                        {
                            SourceUserPermissions.Add(SourceRoleDefinition.Name);
                        }
                    }

                    if (SourceUserPermissions.Count > 0)
                    {
                        if (SourceRoleAssignment.Member is SPGroup)
                        {
                            var Group = (SPGroup)SourceRoleAssignment.Member;
                            var flag = false;
                            foreach (SPUser user in Group.Users)
                            {
                                if (user.LoginName == TargetUserID)
                                {
                                    flag = true;
                                }
                            }
                            if (!flag)
                            {
                                Group.AddUser(TargetUser);
                                try
                                {
                                    LogOperation(web.ServerRelativeUrl, SourceUserID.Split('|')[2], "Group", Group.Name);
                                    Console.WriteLine("Added " + SourceUserID.Split('|')[2] + " in Group: " + Group.Name + " at " + web.ServerRelativeUrl);
                                }
                                catch (Exception ex)
                                {
                                     //log error
                                }
                            }
                        }
                        else
                        {
                            foreach (string NewRoleDefinition in SourceUserPermissions)
                            {
                                var NewRoleAssignment = new SPRoleAssignment(TargetUser);
                                NewRoleAssignment.RoleDefinitionBindings.Add(web.RoleDefinitions[NewRoleDefinition]);

                                if (Object.GetType().Equals(typeof(SPWeb)))
                                {
                                    SPWeb spWeb = Object as SPWeb;
                                    spWeb.RoleAssignments.Add(NewRoleAssignment);
                                    spWeb.Update();
                                    try
                                    {
                                        LogOperation(web.ServerRelativeUrl, SourceUserID.Split('|')[2], "Site", spWeb.Title);
                                        Console.WriteLine("Added " + SourceUserID.Split('|')[2]+ " in Site: " + spWeb.Title + " at " + web.ServerRelativeUrl);
                                    }
                                    catch (Exception ex)
                                    {
                                         //log error
                                    }
                                }
                                if (Object.GetType().Equals(typeof(SPList)))
                                {
                                    SPList list = Object as SPList;
                                    list.RoleAssignments.Add(NewRoleAssignment);
                                    list.Update();
                                    try
                                    {
                                        LogOperation(web.ServerRelativeUrl, SourceUserID.Split('|')[2], "List", list.Title);
                                        Console.WriteLine("Added " + SourceUserID.Split('|')[2] + " in List: " + list.Title + " at " + web.ServerRelativeUrl);
                                    }
                                    catch (Exception ex)
                                    {
                                        string strmsg = ex.Message;
                                    }
                                }
                                if (Object.GetType().Equals(typeof(SPListItem)))
                                {
                                    SPListItem item = Object as SPListItem;
                                    item.RoleAssignments.Add(NewRoleAssignment);
                                    item.Update();
                                    try
                                    {
                                        LogOperation(web.ServerRelativeUrl, SourceUserID.Split('|')[2], "Item", item.ID.ToString());
                                        Console.WriteLine("Added " + SourceUserID.Split('|')[2]+ " in Item: " + item.ID.ToString() + " at " + web.ServerRelativeUrl);
                                    }
                                    catch (Exception ex)
                                    {
                                        //log error
                                    }
                                }

                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                try
                {
                    LogError(ex.Message, SourceUserID.Split('|')[1], web.ServerRelativeUrl);
                    Console.WriteLine("\n\rERROR at " + web.ServerRelativeUrl + " while adding " + SourceUserID.Split('|')[1] +
                        " Message: " + ex.Message + "\n\r");
                }
                catch { }
            }
        }

Reference: https://www.sharepointdiary.com/2015/01/clone-sharepoint-user-permissions-using-powershell.html

Wednesday, 20 November 2019

CSOM: How to copy all files from one SharePoint library to another?

private void btnCopyFiles_Click(object sender, EventArgs e)
        {
            int itemProcessed = 0;
            try
            {
                F.MessageBox.Show("Please make sure the workflows are disabled on the target list.");
                progressBar1.Value = 0;


                PnP.AuthenticationManager authManagerTarget = new PnP.AuthenticationManager();
                using (ClientContext clientContextTarget = authManagerTarget.GetWebLoginClientContext(txtTargetSite.Text))
                {
                    clientContextTarget.RequestTimeout = 9999999;
                    List targetList = clientContextTarget.Web.Lists.GetByTitle(drpTargetList.SelectedItem.ToString());
                    clientContextTarget.Load(targetList);
                    clientContextTarget.ExecuteQueryRetry();

                    PnP.AuthenticationManager authManagerSource = new PnP.AuthenticationManager();
                    using (ClientContext clientContextSource = authManagerSource.GetWebLoginClientContext(txtSourceSite.Text))
                    {
                        List sourceList = clientContextSource.Web.Lists.GetByTitle(drpSourceList.SelectedItem.ToString());
                        CamlQuery camlQuery = new CamlQuery();
                        camlQuery.ViewXml = "<View Scope ='RecursiveAll'></View>";
                        ListItemCollection sourceItems = sourceList.GetItems(camlQuery);
                        clientContextSource.Load(sourceItems);
                        clientContextSource.ExecuteQueryRetry();

                        progressBar1.Maximum = sourceItems.Count;


                        int itemToSkip = 0;
                        try
                        {
                            itemToSkip = txtItemsToSkip.Text.ToInt32();
                        }
                        catch { }

                        string sourceLibrary = string.Empty;
                        string targetLibrary = drpTargetList.SelectedItem.ToString();
                        string fileName = string.Empty;
                        string fileUrl = string.Empty;
                        string folderPath = string.Empty;
                        Web targetWeb = clientContextTarget.Web;
                        clientContextTarget.Load(targetWeb, u => u.ServerRelativeUrl);
                        clientContextTarget.ExecuteQueryRetry();
                        string _path = targetWeb.ServerRelativeUrl;

                        try
                        {
                            sourceLibrary = sourceItems[0].FieldValues["FileDirRef"].ToString();
                            string[] urlArr = sourceLibrary.Split('/');
                            sourceLibrary = urlArr[urlArr.Count() - 1];
                        }
                        catch { }

                        foreach (ListItem sourceItem in sourceItems)
                        {
                            itemProcessed++;

                            if (itemProcessed <= txtItemsToSkip.Text.ToInt32())
                            {
                                progressBar1.Value += 1;
                                continue;
                            }

                            if (sourceItem.FileSystemObjectType == FileSystemObjectType.File)
                            {
                                try
                                {
                                    fileUrl = sourceItem["FileRef"].ToString();
                                    if (!FileExists(targetList, fileUrl.Replace("/Shared Documents/","/Documents/")))
                                    {
                                        string[] fileNames = fileUrl.Split(new string[] { sourceLibrary }, StringSplitOptions.None);
                                        fileName = fileNames[fileNames.Count() - 1];

                                        MSC.File file = sourceItem.File;
                                        clientContextSource.Load(file);
                                        clientContextSource.ExecuteQueryRetry();

                                        FileInformation fileInfo = MSC.File.OpenBinaryDirect(clientContextSource, file.ServerRelativeUrl);
                                        MSC.File.SaveBinaryDirect(clientContextTarget, _path + "/" + targetLibrary + fileName, fileInfo.Stream, false);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    this.LogCopyError(ex, "File", targetLibrary, fileUrl);
                                }
                            }

                            else if (sourceItem.FileSystemObjectType == FileSystemObjectType.Folder)
                            {
                                try
                                {
                                    folderPath = sourceItem["FileRef"].ToString();
                                    string[] fileNames = folderPath.Split(new string[] { sourceLibrary }, StringSplitOptions.None);
                                    folderPath = fileNames[fileNames.Count() - 1];
                                    folderPath = folderPath.TrimStart(new Char[] { '/' });
                                    MSC.Folder folder = CreateFolder(clientContextTarget.Web, drpTargetList.SelectedItem.ToString(), folderPath);
                                }
                                catch (Exception ex)
                                {
                                    this.LogError(ex);
                                }
                            }

                            progressBar1.Value += 1;
                        }
                    }
                }
                F.MessageBox.Show("Done. Please match the items count");
            }
            catch (Exception ex)
            {
                this.LogError(ex);
                F.MessageBox.Show("Something went wrong. Please check the logs.");
                try
                {
                    F.MessageBox.Show("Items processed: " + (--itemProcessed));
                }
                catch { }
            }
        }

        private MSC.Folder CreateFolder(Web web, string listTitle, string fullFolderPath)
        {

            if (string.IsNullOrEmpty(fullFolderPath))
                throw new ArgumentNullException("fullFolderPath");
            var list = web.Lists.GetByTitle(listTitle);
            return CreateFolderInternal(web, list.RootFolder, fullFolderPath);

        }

        private MSC.Folder CreateFolderInternal(Web web, MSC.Folder parentFolder, string fullFolderPath)
        {

            var folderUrls = fullFolderPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            string folderUrl = folderUrls[0];
            var curFolder = parentFolder.Folders.Add(folderUrl);
            web.Context.Load(curFolder);
            web.Context.ExecuteQueryRetry();

            if (folderUrls.Length > 1)
            {
                var folderPath = string.Join("/", folderUrls, 1, folderUrls.Length - 1);
                return CreateFolderInternal(web, curFolder, folderPath);
            }

            return curFolder;
        }

        public bool FileExists(List list, string fileUrl)
        {
            var ctx = list.Context;
            var qry = new CamlQuery();
            qry.ViewXml = string.Format("<View Scope=\"RecursiveAll\"><Query><Where><Eq><FieldRef Name=\"FileRef\"/><Value Type=\"Url\">{0}</Value></Eq></Where></Query></View>", fileUrl);
            var items = list.GetItems(qry);
            ctx.Load(items);
            ctx.ExecuteQuery();
            return items.Count > 0;
        }

Reference: https://sharepoint.stackexchange.com/a/203283

Saturday, 27 July 2019

CSOM: How to authenticate a user on SharePoint 2013 using claim based authentication?


Visual Studio > Project > References > Manage NuGet Packages > Online > Search 'Microsoft.SharePointOnline.CSOM' > Accept and Install

Visual Studio > Project > References > Manage NuGet Packages > Online > Search 'OfficeDevPnP.Core'> Accept and Install


using Microsoft.SharePoint.Client;
using PnP = OfficeDevPnP.Core;

PnP.AuthenticationManager authManager = new PnP.AuthenticationManager();
ClientContext context = authManager.GetWebLoginClientContext("siteUrl");



Thursday, 16 February 2017

How to use HyperLink in ASP.NET GridView and dynamically bind its URL?


ASPX Design:

<asp:GridView ID="gridWithLinks" runat="server"
                                 AutoGenerateColumns="false"
                                 DataKeyNames="ID"

                                <Columns>

                                    <asp:TemplateField HeaderText="Link">
                                        <ItemTemplate>
                                            <asp:HyperLink

                                                ID="linkDetails"
                                                Target="_blank"
                                                Text="View details"
                                                runat="server">

                                            </asp:HyperLink>
                                        </ItemTemplate>
                                    </asp:TemplateField>

                               </Columns>
                            </asp:GridView>

Code Behind:

                gridWithLinks.DataSource = dataTableName;
                gridWithLinks.DataBind();

                foreach (GridViewRow row in gridWithLinks.Rows)
                {
                    ((HyperLink)row.FindControl("linkDetails")).NavigateUrl =
                        "https://URL?ID=" + gridWithLinks.DataKeys[row.RowIndex].Value.ToString() + "";

                }

Thursday, 5 January 2017

How to query Data Table in C# ?


To get distinct rows:

using System.Linq;

var distinctRows = dt.DefaultView.ToTable(true, "Resource_x0020_ID").Rows.OfType<DataRow>().Select(k => k[0] + "").ToArray();


To filter using where:

var product = from row in tempTable.AsEnumerable()
where row.Field<int>("ProdID") == 100 &&
(row.Field<string>("Category") != "Closed" ||
row.Field<string>("Type") == "Electroncs")
select row;

DataRow[] results = table.Select("A = 'foo' AND B = 'bar' AND C = 'baz'");


To get count:

int count = dt.Select("Product_x0020_Type = 'Mobile'").Length;

int blrCount = dt.Select("Work_x0020_Location like '%Bangalore%'").Length;

Thursday, 5 February 2015

How to clear SharePoint People Picker control using C# ?

Here is a way to clear the SharePoint People Picker control using c#

peoplePickerObjectID.CommaSeparatedAccounts = null;

How to get single item from SharePoint document library using SPQuery (without using for loop) ?

Here is the C# code to achieve the above requirement:

public SPListItemCollection GetSpecificLibraryItem(fileName)
{
SPList list = web.Lists["MyDocName"];
SPQuery dQuery = new SPQuery();
dQuery.ViewAttributes = "Scope=\"Recursive\"";
string QueryString = "<Where>" +
                      "<Eq>" +
                        "<FieldRef Name=\"FileLeafRef\"/>" +
                        "<Value Type=\"Text\">" + fileName + "</Value>" +
                      "</Eq>" +
                     "</Where>";
         dQuery.Query = QueryString;
        SPListItemCollection collListItems = list.GetItems(dQuery);
  return collListItems;
}

How to get all SharePoint Web Applications from SP Farm programmatically using C# ?

Here is a way to get all SharePoint Web Applications in a SP Farm:

public ListItemCollection GetAllWebApplicationsInSPFarm()
{
ddlDataSource = new ListItemCollection();
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPServiceCollection services = SPFarm.Local.Services;
foreach (SPService curService in services)
{
if (curService is SPWebService)
{
webService = (SPWebService)curService;
if (curService.TypeName.Equals("Microsoft SharePoint Foundation Web Application"))
{
webService = (SPWebService)curService;
SPWebApplicationCollection webApplications = webService.WebApplications;
foreach (SPWebApplication webApplication in webApplications)
{
if (webApplication != null)
{
//Now you have the required object i.e. webApplication. You can use it like this:
//string webApp = webApplication.AlternateUrls[0].Collection.Name.ToString();
//Write your code here…    
}
}
}
}
}
});
}

How to open SharePoint application page in modal dialog (popup) using c#?

C# Code:
void OpenApplicationPageAsPopup(){
string strWebUrl = SPContext.Current.Web.Url;
string strPageURL = strWebUrl + "/_layouts/MyLayoutFolder/MyPage.aspx";
System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), ClientID, "ExecuteOrDelayUntilScriptLoaded(openModelDialogPopup('" + strPageURL + "'), \"SP.js\");", true);

}
JavaScript Code:
function openModelDialogPopup(strPageURL ) {

    var dialogOptions = {
        title: "This is Modal Dialog", //Popup title.
        url: strPageURL, 
        width: 600, // Width of the dialog.
        height: 400
    };
    SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', dialogOptions);
    return false;
}