Skip to main content

Notifications

Microsoft Dynamics CRM (Archived)

Retrieve Role Privileges and export into XL Sheet

Posted on by 377

Hi,

I have an requirement where user can select security role and need to exports all the related privileges to Xl sheet . Any suggestions.

Thanks in advance

*This post is locked for comments

  • ZeroHar Profile Picture
    ZeroHar 377 on at
    RE: Retrieve Role Privileges and export into XL Sheet

    Thansk for the help, any JS . i am able to retrieve privileges based on role id. but i am unable to sort by entity. Any suggestion?

  • Inogic Profile Picture
    Inogic 24,094 on at
    RE: Retrieve Role Privileges and export into XL Sheet

    You can refer below code to export the security privileges for the provided security role. 

    using System;
    using System.Linq;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;
    using Microsoft.Xrm.Sdk.Client;
    using Microsoft.Crm.Sdk.Messages;
    using System.Configuration;
    using CrmEarlyBound;
    using Microsoft.Xrm.Tooling.Connector;
    using System.IO;
    using System.Data;
    
    namespace RetreieveRoles
    {
        public class Roles
        {
            #region How To Sample Code
            /// <summary>
            /// gets the organisation roles and stores it into DataTable
            /// </summary>
            public void GetOrgRoles() //ServerConnection.Configuration serverConfig, bool promptforDelete
            {
                try
                {
                    #region CRMConnection
                    //connecting to CRm environment
                    CrmServiceClient service = new CrmServiceClient(ConfigurationManager.ConnectionStrings["XrmName"].ConnectionString);
                    OrganizationServiceContext context = new OrganizationServiceContext(service);
                    #endregion
    
                    DataTable dtrecords = new DataTable();
                    //getting roles entity
                    QueryExpression query = new QueryExpression
                    {
                        EntityName = "role"
                    };
    
                    Guid roleId = new Guid();
                    //secuirty id to get privileges for
                    string securityId = "E0796DC8-C897-E511-80D9-D89D676440FC";
                    roleId = new Guid(securityId);
    
                    //Get all Security Roles
                    EntityCollection Securityroles = service.RetrieveMultiple(query);
    
                    //Get all Privileges
                    RetrievePrivilegeSetRequest requestp = new RetrievePrivilegeSetRequest();
                    RetrievePrivilegeSetResponse responsep = (RetrievePrivilegeSetResponse)service.Execute(requestp);
    
                    //Get record from RolePrivilege Mapping
                    RetrieveRolePrivilegesRoleRequest req = new RetrieveRolePrivilegesRoleRequest();
                    req.RoleId = roleId;
                    RetrieveRolePrivilegesRoleResponse response = (RetrieveRolePrivilegesRoleResponse)service.Execute(req);
    
                    //writing into Datatable
                    //Column Name to be added into dataTable
                    string colName = "privilege Name";
                    if (!dtrecords.Columns.Contains(colName))
                    {
                        dtrecords.Columns.Add(colName);
                    }
                    foreach (RolePrivilege priv in response.RolePrivileges)
                    {
                        //Add columns to datatable                    
                        var privile = responsep.EntityCollection.Entities.Where(a => a.Id == priv.PrivilegeId).ToArray();
                        try
                        {
                            foreach (Entity ent in privile)
                            {
                                //getting the privileges name only
                                Privilege privilege = ent.ToEntity<Privilege>();
                                dtrecords.Rows.Add(privilege.Name.ToString());
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                    string strFilePath = ConfigurationManager.AppSettings["PathToStoreCSV"];
                    //converting to csv
                    CreateCSVFile(dtrecords, strFilePath);
                }
                // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
                catch (Exception ex)
                {
                    // You can handle an exception here or pass it back to the calling method.
                    throw ex;
                }
            }
    
            #endregion How To Sample Code
    
    
            #region Datatable To CSV File
            /// <summary>
            /// function to convert datatable to CSV
            /// </summary>
            /// <param name="dt"> Datatable to convert into csv</param>
            /// <param name="strFilePath"> file path where csv would be saved mentioned in apconfig file</param>
            public void CreateCSVFile(DataTable dt, string strFilePath)
            {
                #region Export Grid to CSV
                // Create the CSV file to which grid data will be exported.
                StreamWriter sw = new StreamWriter(strFilePath, false);
                // First we will write the headers.
                //DataTable dt = m_dsProducts.Tables[0];
                int iColCount = dt.Columns.Count;
    
                for (int i = 0; i < iColCount; i++)
                {
                    sw.Write(dt.Columns[i]);
                    if (i < iColCount - 1)
                    {
                        sw.Write(",");
                    }
                }
                sw.Write(sw.NewLine);
                // Now write all the rows.
                foreach (DataRow dr in dt.Rows)
                {
                    for (int i = 0; i < iColCount; i++)
                    {
                        if (!Convert.IsDBNull(dr[i]))
                        {
                            sw.Write(dr[i].ToString());
                        }
                        if (i < iColCount - 1)
                        {
                            sw.Write(",");
                        }
                    }
                    sw.Write(sw.NewLine);
                }
                sw.Close();
                #endregion
    
            }
            #endregion
        }
    }
    


    Thanks!

  • Suggested answer
    Mahendar Pal Profile Picture
    Mahendar Pal 45,095 on at
    RE: Retrieve Role Privileges and export into XL Sheet

    Hello,

    You can also consider www.xrmcoaches.com/snapshot

  • Mohan Prasad MAni Profile Picture
    Mohan Prasad MAni 235 on at
    RE: Retrieve Role Privileges and export into XL Sheet

    archive.codeplex.com/

    Plesae mark the answer as "Suggested" if this resolves your query!!

    Thanks

    Mohan

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Community AMA December 12th

Join us as we continue to demystify the Dynamics 365 Contact Center

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,253 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,188 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans