Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Retrieve Role Privileges and export into XL Sheet

(0) ShareShare
ReportReport
Posted on by 383

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
    383 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
    490 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
    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
    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

🌸 Community Spring Festival 2025 Challenge Winners! 🌸

Congratulations to all our community participants!

Adis Hodzic – Community Spotlight

We are honored to recognize Adis Hodzic as our May 2025 Community…

Kudos to the April Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard > Microsoft Dynamics CRM (Archived)

#1
Mohamed Amine Mahmoudi Profile Picture

Mohamed Amine Mahmoudi 83 Super User 2025 Season 1

#2
Community Member Profile Picture

Community Member 52

#3
Victor Onyebuchi Profile Picture

Victor Onyebuchi 6

Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans