Exemple #1
0
        private void btnModifySharings_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (var item in sharingDetailsList.Where(x => x.modified))
                {
                    var modifyAccess = new ModifyAccessRequest()
                    {
                        Target          = new EntityReference(item.entity.GetAttributeValue <string>("objecttypecode"), item.entity.GetAttributeValue <Guid>("objectid")),
                        PrincipalAccess = new PrincipalAccess()
                        {
                            AccessMask = getNewAccessRightMask(item),
                            Principal  = new EntityReference(item.entity.GetAttributeValue <string>("principaltypecode"), item.entity.GetAttributeValue <Guid>("principalid"))
                        }
                    };

                    this.pvm.controllerManager.serviceClient.Execute(modifyAccess);
                }
            }
            catch (Exception exception)
            {
                this.pvm.log.LogData(EventType.Exception, LogAction.SharingsUpdated, exception);
                throw;
            }

            MessageBox.Show("The sharings were updated successfully !", "Sharing Updates", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.pvm.log.LogData(EventType.Event, LogAction.SharingsUpdated);
        }
        public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx)
        {
            ModifyAccessRequest req = (ModifyAccessRequest)request;

            ctx.AccessRightsRepository.ModifyAccessOn(req.Target, req.PrincipalAccess);
            return(new ModifyAccessResponse());
        }
//Code to modify privileges for the target record and team
        private void ModifyAccess(string targetEntityName, Guid targetRecordID, Guid teamID, IOrganizationService orgService)
        {
            try
            {
//Get User or Team reference and Target Entity and record ID that needs to be shared.
                var          RecordReference = new EntityReference(targetEntityName, targetRecordID);
                var          teamRef         = new EntityReference("team", teamID);
                AccessRights accessRights    = new AccessRights();
                accessRights = AccessRights.DeleteAccess;
                var modifyAcess = new ModifyAccessRequest
                {
                    PrincipalAccess = new PrincipalAccess
                    {
                        AccessMask = accessRights,
                        Principal  = teamRef
                    },
                    Target = RecordReference
                };
// Execute the Request
                orgService.Execute(modifyAcess);
            }
            catch (Exception ex)
            {
                throw new Exception("An error occured in Modifying access." + ex.Message);
            }
        }
        public void Test_That_Existing_Permissions_Can_Be_Modified()
        {
            XrmFakedContext      context         = new XrmFakedContext();
            IOrganizationService service         = context.GetOrganizationService();
            List <Entity>        initialEntities = new List <Entity>();

            Entity contact = new Entity("contact");

            contact.Id = Guid.NewGuid();
            initialEntities.Add(contact);

            Entity user = new Entity("systemuser");

            user.Id = Guid.NewGuid();
            initialEntities.Add(user);

            context.Initialize(initialEntities);

            GrantAccessRequest grantRequest = new GrantAccessRequest()
            {
                Target          = contact.ToEntityReference(),
                PrincipalAccess = new PrincipalAccess()
                {
                    Principal = user.ToEntityReference(), AccessMask = AccessRights.ReadAccess
                }
            };

            service.Execute(grantRequest);

            RetrieveSharedPrincipalsAndAccessRequest getPermissions = new RetrieveSharedPrincipalsAndAccessRequest()
            {
                Target = contact.ToEntityReference(),
            };

            var permissionsResponse = (RetrieveSharedPrincipalsAndAccessResponse)service.Execute(getPermissions);

            // Make sure things are correct before I start changing things
            Assert.Equal(user.Id, permissionsResponse.PrincipalAccesses[0].Principal.Id);
            Assert.Equal(AccessRights.ReadAccess, permissionsResponse.PrincipalAccesses[0].AccessMask);

            ModifyAccessRequest modifyRequest = new ModifyAccessRequest()
            {
                Target          = contact.ToEntityReference(),
                PrincipalAccess = new PrincipalAccess()
                {
                    Principal = user.ToEntityReference(), AccessMask = AccessRights.ReadAccess | AccessRights.DeleteAccess
                }
            };

            service.Execute(modifyRequest);

            permissionsResponse = (RetrieveSharedPrincipalsAndAccessResponse)service.Execute(getPermissions);

            // Check permissions
            Assert.Equal(user.Id, permissionsResponse.PrincipalAccesses[0].Principal.Id);
            Assert.Equal(AccessRights.ReadAccess | AccessRights.DeleteAccess, permissionsResponse.PrincipalAccesses[0].AccessMask);
        }
Exemple #5
0
        public void ModifyAccess(EntityReference target, PrincipalAccess access)
        {
            var req = new ModifyAccessRequest()
            {
                Target          = target,
                PrincipalAccess = access
            };

            this.Execute(req);
        }
        public void ModifyAccess(EntityReference principalEntityReference, EntityReference targetEntityReference, AccessRights accessMask)
        {
            ModifyAccessRequest modifyRequest = new ModifyAccessRequest()
            {
                PrincipalAccess = new PrincipalAccess()
                {
                    Principal  = principalEntityReference,
                    AccessMask = accessMask
                },
                Target = targetEntityReference
            };

            ServiceProxy.Execute(modifyRequest);
        }
Exemple #7
0
        public static void UnShareRecord(this OrganizationServiceContext context, EntityReference targetRef, EntityReference unShareToRef)
        {
            var modifyAccessRequest = new ModifyAccessRequest
            {
                PrincipalAccess = new PrincipalAccess
                {
                    AccessMask = AccessRights.None,
                    Principal  = unShareToRef
                },
                Target = targetRef
            };

            context.Execute(modifyAccessRequest);
        }
        public void ModifyAccess(EntityReference userOrTeam, EntityReference target, AccessRights acessRight)
        {
            ModifyAccessRequest modifyAccessRequest = new ModifyAccessRequest
            {
                PrincipalAccess = new PrincipalAccess
                {
                    AccessMask = acessRight,
                    Principal  = userOrTeam
                },
                Target = target
            };

            service.Execute(modifyAccessRequest);
        }
        /// <summary>
        /// Replace the access rights on the target record for the specified security principal (user or team).
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.modifyaccessrequest(v=crm.8).aspx
        /// </para>
        /// </summary>
        /// <param name="shareToPrincipal"><see cref="PrincipalType"/></param>
        /// <param name="shareToId"></param>
        /// <param name="targetEntityLogicalName"></param>
        /// <param name="targetId"></param>
        /// <param name="targetAccessRights"></param>
        /// <returns>
        /// <see cref="ModifyAccessResponse"/>
        /// </returns>
        public ModifyAccessResponse ModifyShare(PrincipalType shareToPrincipal, Guid shareToId, string targetEntityLogicalName, Guid targetId, AccessRights targetAccessRights)
        {
            ExceptionThrow.IfGuidEmpty(shareToId, "shareToId");
            ExceptionThrow.IfGuidEmpty(targetId, "targetId");
            ExceptionThrow.IfNullOrEmpty(targetEntityLogicalName, "targetEntityLogicalName");

            ModifyAccessRequest request = new ModifyAccessRequest()
            {
                PrincipalAccess = new PrincipalAccess()
                {
                    Principal  = new EntityReference(shareToPrincipal.Description(), shareToId),
                    AccessMask = targetAccessRights
                },
                Target = new EntityReference(targetEntityLogicalName, targetId)
            };

            return((ModifyAccessResponse)this.OrganizationService.Execute(request));
        }
Exemple #10
0
        public void Run(ServerConnection.Configuration serverConfig,
            bool promptforDelete)
        {
            using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
            {
                // This statement is required to enable early bound type support.
                _serviceProxy.EnableProxyTypes();
                CreateRequiredRecords();

                // Retrieve and display the access that the calling user has to the
                // created lead.
                var leadReference = new EntityReference(Lead.EntityLogicalName, _leadId);
                var currentUserReference = new EntityReference(
                    SystemUser.EntityLogicalName, _currentUserId);
                RetrieveAndDisplayPrincipalAccess(leadReference, currentUserReference,
                    "Current User");

                // Retrieve and display the access that the first user has to the
                // created lead.
                var systemUser1Ref = new EntityReference(SystemUser.EntityLogicalName,
                    _systemUserIds[0]);
                RetrieveAndDisplayPrincipalAccess(leadReference, systemUser1Ref,
                    "System User 1");

                // Grant the first user read access to the created lead.
                var grantAccessRequest1 = new GrantAccessRequest
                {
                    PrincipalAccess = new PrincipalAccess
                    {
                        AccessMask = AccessRights.ReadAccess,
                        Principal = systemUser1Ref
                    },
                    Target = leadReference
                };

                Console.WriteLine("Granting {0} to {1} ({2}) on the lead...\r\n",
                    AccessRights.ReadAccess, GetEntityReferenceString(systemUser1Ref), "System User 1");
                _serviceProxy.Execute(grantAccessRequest1);


                // Retrieve and display access information for the lead.
                RetrieveAndDisplayPrincipalAccess(leadReference, systemUser1Ref,
                    "System User 1");
                RetrieveAndDisplayLeadAccess(leadReference);

                //<snippetUserAccess1>
                // Grant the team read/write access to the lead.
                var teamReference = new EntityReference(Team.EntityLogicalName, _teamId);
                var grantAccessRequest = new GrantAccessRequest
                {
                    PrincipalAccess = new PrincipalAccess
                    {
                        AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess,
                        Principal = teamReference
                    },
                    Target = leadReference
                };

                Console.WriteLine("Granting {0} to {1} ({2}) on the lead...\r\n",
                    AccessRights.ReadAccess | AccessRights.WriteAccess, GetEntityReferenceString(teamReference), "Team");
                _serviceProxy.Execute(grantAccessRequest);

                var systemUser2Ref = new EntityReference(SystemUser.EntityLogicalName,
                    _systemUserIds[1]);

                //</snippetUserAccess1>
               
                // Retrieve and display access information for the lead and system user 2.
                RetrieveAndDisplayPrincipalAccess(leadReference, systemUser2Ref,
                    "System User 2");
                RetrieveAndDisplayLeadAccess(leadReference);

                //<snippetUserAccess2>

                // Grant the first user delete access to the lead.
                var modifyUser1AccessReq = new ModifyAccessRequest
                {
                    PrincipalAccess = new PrincipalAccess
                    {
                        AccessMask = AccessRights.DeleteAccess,
                        Principal = systemUser1Ref
                    },
                    Target = leadReference
                };

                Console.WriteLine("Granting delete access to {0} on the lead...\r\n",
                    GetEntityReferenceString(systemUser1Ref));
                _serviceProxy.Execute(modifyUser1AccessReq);
                //</snippetUserAccess2>

                // Retrieve and display access information for the lead.
                RetrieveAndDisplayLeadAccess(leadReference);

                //<snippetUserAccess3>

                // Revoke access to the lead for the second user.
                var revokeUser2AccessReq = new RevokeAccessRequest
                {
                    Revokee = systemUser2Ref,
                    Target = leadReference
                };

                Console.WriteLine("Revoking access to the lead for {0}...\r\n",
                    GetEntityReferenceString(systemUser2Ref));
                _serviceProxy.Execute(revokeUser2AccessReq);
                //</snippetUserAccess3>

                // Retrieve and display access information for the lead.
                RetrieveAndDisplayPrincipalAccess(leadReference, systemUser2Ref,
                    "System User 2");

                RetrieveAndDisplayLeadAccess(leadReference);

                DeleteRequiredRecords(promptforDelete);
            }
        }
        /// <summary>
        /// Demonstrates sharing records by exercising various access messages including:
        /// Grant, Modify, Revoke, RetrievePrincipalAccess, and
        /// RetrievePrincipalsAndAccess.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    _service = (IOrganizationService)_serviceProxy;

                    CreateRequiredRecords();

                    #region GrantAccess Message

                    // Create the request object and set the target and principal access
                    // object.
                    GrantAccessRequest grantRequest = new GrantAccessRequest()
                    {
                        Target          = new EntityReference(Account.EntityLogicalName, _accountId),
                        PrincipalAccess = new PrincipalAccess()
                        {
                            Principal  = new EntityReference(SystemUser.EntityLogicalName, _userId),
                            AccessMask = AccessRights.WriteAccess | AccessRights.ReadAccess | AccessRights.ShareAccess
                        }
                    };

                    // Execute the request.
                    GrantAccessResponse grantResponse =
                        (GrantAccessResponse)_service.Execute(grantRequest);

                    Console.Write("Access Granted ");

                    #endregion

                    #region ModifyAccess Message

                    // Create the request object and set the target and principal access
                    // object.
                    ModifyAccessRequest modifyRequest = new ModifyAccessRequest()
                    {
                        Target          = new EntityReference(Account.EntityLogicalName, _accountId),
                        PrincipalAccess = new PrincipalAccess()
                        {
                            Principal  = new EntityReference(SystemUser.EntityLogicalName, _userId),
                            AccessMask = AccessRights.ReadAccess | AccessRights.ShareAccess
                        }
                    };

                    // Execute the request.
                    ModifyAccessResponse modifyResponse =
                        (ModifyAccessResponse)_service.Execute(modifyRequest);

                    Console.Write("and Modified. ");

                    #endregion

                    #region RetrievePrincipalAccess Message

                    // Create the request object and set the target and principal.
                    RetrievePrincipalAccessRequest retrieveRequest = new RetrievePrincipalAccessRequest()
                    {
                        Target    = new EntityReference(Account.EntityLogicalName, _accountId),
                        Principal = new EntityReference(SystemUser.EntityLogicalName, _userId)
                    };

                    // Execute the request.
                    RetrievePrincipalAccessResponse retrieveResponse =
                        (RetrievePrincipalAccessResponse)_service.Execute(retrieveRequest);

                    Console.Write("Retrieved principal access. ");

                    #endregion

                    #region RetrieveSharedPrincipalsAndAccess Message

                    // Create the request object and set the target.
                    RetrieveSharedPrincipalsAndAccessRequest retrieveSharedRequest =
                        new RetrieveSharedPrincipalsAndAccessRequest()
                    {
                        Target = new EntityReference(Account.EntityLogicalName, _accountId)
                    };

                    // Execute the request.
                    RetrieveSharedPrincipalsAndAccessResponse retrieveSharedResponse =
                        (RetrieveSharedPrincipalsAndAccessResponse)_service.Execute(retrieveSharedRequest);

                    Console.Write("Retrieved principals and access. ");

                    #endregion

                    #region RevokeAccess Message

                    // Create the request object and set the target and revokee.
                    RevokeAccessRequest revokeRequest = new RevokeAccessRequest()
                    {
                        Target  = new EntityReference(Account.EntityLogicalName, _accountId),
                        Revokee = new EntityReference(SystemUser.EntityLogicalName, _userId)
                    };

                    // Execute the request.
                    RevokeAccessResponse revokeResponse =
                        (RevokeAccessResponse)_service.Execute(revokeRequest);

                    Console.Write("Revoked Access.");

                    #endregion

                    DeleteRequiredRecords(promptforDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Exemple #12
0
        public void Run(ServerConnection.Configuration serverConfig,
                        bool promptforDelete)
        {
            using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
            {
                // This statement is required to enable early bound type support.
                _serviceProxy.EnableProxyTypes();
                CreateRequiredRecords();

                // Retrieve and display the access that the calling user has to the
                // created lead.
                var leadReference        = new EntityReference(Lead.EntityLogicalName, _leadId);
                var currentUserReference = new EntityReference(
                    SystemUser.EntityLogicalName, _currentUserId);
                RetrieveAndDisplayPrincipalAccess(leadReference, currentUserReference,
                                                  "Current User");

                // Retrieve and display the access that the first user has to the
                // created lead.
                var systemUser1Ref = new EntityReference(SystemUser.EntityLogicalName,
                                                         _systemUserIds[0]);
                RetrieveAndDisplayPrincipalAccess(leadReference, systemUser1Ref,
                                                  "System User 1");

                // Grant the first user read access to the created lead.
                var grantAccessRequest1 = new GrantAccessRequest
                {
                    PrincipalAccess = new PrincipalAccess
                    {
                        AccessMask = AccessRights.ReadAccess,
                        Principal  = systemUser1Ref
                    },
                    Target = leadReference
                };

                Console.WriteLine("Granting {0} to {1} ({2}) on the lead...\r\n",
                                  AccessRights.ReadAccess, GetEntityReferenceString(systemUser1Ref), "System User 1");
                _serviceProxy.Execute(grantAccessRequest1);


                // Retrieve and display access information for the lead.
                RetrieveAndDisplayPrincipalAccess(leadReference, systemUser1Ref,
                                                  "System User 1");
                RetrieveAndDisplayLeadAccess(leadReference);

                //<snippetUserAccess1>
                // Grant the team read/write access to the lead.
                var teamReference      = new EntityReference(Team.EntityLogicalName, _teamId);
                var grantAccessRequest = new GrantAccessRequest
                {
                    PrincipalAccess = new PrincipalAccess
                    {
                        AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess,
                        Principal  = teamReference
                    },
                    Target = leadReference
                };

                Console.WriteLine("Granting {0} to {1} ({2}) on the lead...\r\n",
                                  AccessRights.ReadAccess | AccessRights.WriteAccess, GetEntityReferenceString(teamReference), "Team");
                _serviceProxy.Execute(grantAccessRequest);

                var systemUser2Ref = new EntityReference(SystemUser.EntityLogicalName,
                                                         _systemUserIds[1]);

                //</snippetUserAccess1>

                // Retrieve and display access information for the lead and system user 2.
                RetrieveAndDisplayPrincipalAccess(leadReference, systemUser2Ref,
                                                  "System User 2");
                RetrieveAndDisplayLeadAccess(leadReference);

                //<snippetUserAccess2>

                // Grant the first user delete access to the lead.
                var modifyUser1AccessReq = new ModifyAccessRequest
                {
                    PrincipalAccess = new PrincipalAccess
                    {
                        AccessMask = AccessRights.DeleteAccess,
                        Principal  = systemUser1Ref
                    },
                    Target = leadReference
                };

                Console.WriteLine("Granting delete access to {0} on the lead...\r\n",
                                  GetEntityReferenceString(systemUser1Ref));
                _serviceProxy.Execute(modifyUser1AccessReq);
                //</snippetUserAccess2>

                // Retrieve and display access information for the lead.
                RetrieveAndDisplayLeadAccess(leadReference);

                //<snippetUserAccess3>

                // Revoke access to the lead for the second user.
                var revokeUser2AccessReq = new RevokeAccessRequest
                {
                    Revokee = systemUser2Ref,
                    Target  = leadReference
                };

                Console.WriteLine("Revoking access to the lead for {0}...\r\n",
                                  GetEntityReferenceString(systemUser2Ref));
                _serviceProxy.Execute(revokeUser2AccessReq);
                //</snippetUserAccess3>

                // Retrieve and display access information for the lead.
                RetrieveAndDisplayPrincipalAccess(leadReference, systemUser2Ref,
                                                  "System User 2");

                RetrieveAndDisplayLeadAccess(leadReference);

                DeleteRequiredRecords(promptforDelete);
            }
        }
Exemple #13
0
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    //////////////////////////////////////////////
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate

                    // Retrieve and display the access that the calling user has to the
                    // created lead.
                    var accountReference     = new EntityReference(Account.EntityLogicalName, _accountId);
                    var currentUserReference = new EntityReference(
                        SystemUser.EntityLogicalName, _currentUserId);
                    RetrieveAndDisplayPrincipalAccess(service, accountReference, currentUserReference,
                                                      "Current User");

                    // Retrieve and display the access that the first user has to the
                    // created lead.
                    var systemUser1Ref = new EntityReference(SystemUser.EntityLogicalName,
                                                             _systemUserIds[0]);
                    RetrieveAndDisplayPrincipalAccess(service, accountReference, systemUser1Ref,
                                                      "System User 1");

                    // Grant the first user read access to the created lead.
                    var grantAccessRequest1 = new GrantAccessRequest
                    {
                        PrincipalAccess = new PrincipalAccess
                        {
                            AccessMask = AccessRights.ReadAccess,
                            Principal  = systemUser1Ref
                        },
                        Target = accountReference
                    };

                    Console.WriteLine("Granting {0} to {1} ({2}) on the lead...\r\n",
                                      AccessRights.ReadAccess, GetEntityReferenceString(service, systemUser1Ref), "System User 1");
                    service.Execute(grantAccessRequest1);


                    // Retrieve and display access information for the lead.
                    RetrieveAndDisplayPrincipalAccess(service, accountReference, systemUser1Ref,
                                                      "System User 1");
                    RetrieveAndDisplayAccountAccess(service, accountReference);

                    // Grant the team read/write access to the lead.
                    var teamReference      = new EntityReference(Team.EntityLogicalName, _teamId);
                    var grantAccessRequest = new GrantAccessRequest
                    {
                        PrincipalAccess = new PrincipalAccess
                        {
                            AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess,
                            Principal  = teamReference
                        },
                        Target = accountReference
                    };

                    Console.WriteLine("Granting {0} to {1} ({2}) on the lead...\r\n",
                                      AccessRights.ReadAccess | AccessRights.WriteAccess, GetEntityReferenceString(service, teamReference), "Team");
                    service.Execute(grantAccessRequest);

                    var systemUser2Ref = new EntityReference(SystemUser.EntityLogicalName,
                                                             _systemUserIds[1]);


                    // Retrieve and display access information for the lead and system user 2.
                    RetrieveAndDisplayPrincipalAccess(service, accountReference, systemUser2Ref,
                                                      "System User 2");
                    RetrieveAndDisplayAccountAccess(service, accountReference);


                    // Grant the first user delete access to the lead.
                    var modifyUser1AccessReq = new ModifyAccessRequest
                    {
                        PrincipalAccess = new PrincipalAccess
                        {
                            AccessMask = AccessRights.DeleteAccess,
                            Principal  = systemUser1Ref
                        },
                        Target = accountReference
                    };

                    Console.WriteLine("Granting delete access to {0} on the account...\r\n",
                                      GetEntityReferenceString(service, systemUser1Ref));
                    service.Execute(modifyUser1AccessReq);

                    // Retrieve and display access information for the lead.
                    RetrieveAndDisplayAccountAccess(service, accountReference);


                    // Revoke access to the lead for the second user.
                    var revokeUser2AccessReq = new RevokeAccessRequest
                    {
                        Revokee = systemUser2Ref,
                        Target  = accountReference
                    };

                    Console.WriteLine("Revoking access to the lead for {0}...\r\n",
                                      GetEntityReferenceString(service, systemUser2Ref));
                    service.Execute(revokeUser2AccessReq);

                    // Retrieve and display access information for the lead.
                    RetrieveAndDisplayPrincipalAccess(service, accountReference, systemUser2Ref,
                                                      "System User 2");

                    RetrieveAndDisplayAccountAccess(service, accountReference);

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                #endregion Demonstrate
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            #endregion Sample Code
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Exemple #14
0
        /// <summary>
        /// Demonstrates sharing records by exercising various access messages including:
        /// Grant, Modify, Revoke, RetrievePrincipalAccess, and 
        /// RetrievePrincipalsAndAccess.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetSharingRecords1>
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    _service = (IOrganizationService)_serviceProxy;

                    CreateRequiredRecords();

                    #region GrantAccess Message

                    // Create the request object and set the target and principal access
                    // object.
                    GrantAccessRequest grantRequest = new GrantAccessRequest()
                    {
                        Target = new EntityReference(Account.EntityLogicalName, _accountId),
                        PrincipalAccess = new PrincipalAccess()
                        {
                            Principal = new EntityReference(SystemUser.EntityLogicalName, _userId),
                            AccessMask = AccessRights.WriteAccess | AccessRights.ReadAccess | AccessRights.ShareAccess
                        }
                    };

                    // Execute the request.
                    GrantAccessResponse grantResponse =
                        (GrantAccessResponse)_service.Execute(grantRequest);

                    Console.Write("Access Granted ");

                    #endregion

                    #region ModifyAccess Message

                    // Create the request object and set the target and principal access
                    // object.
                    ModifyAccessRequest modifyRequest = new ModifyAccessRequest()
                    {
                        Target = new EntityReference(Account.EntityLogicalName, _accountId),
                        PrincipalAccess = new PrincipalAccess()
                        {
                            Principal = new EntityReference(SystemUser.EntityLogicalName, _userId),
                            AccessMask = AccessRights.ReadAccess | AccessRights.ShareAccess
                        }
                    };

                    // Execute the request.
                    ModifyAccessResponse modifyResponse =
                        (ModifyAccessResponse)_service.Execute(modifyRequest);

                    Console.Write("and Modified. ");

                    #endregion

                    #region RetrievePrincipalAccess Message

                    // Create the request object and set the target and principal.
                    RetrievePrincipalAccessRequest retrieveRequest = new RetrievePrincipalAccessRequest()
                    {
                        Target = new EntityReference(Account.EntityLogicalName, _accountId),
                        Principal = new EntityReference(SystemUser.EntityLogicalName, _userId)
                    };

                    // Execute the request.
                    RetrievePrincipalAccessResponse retrieveResponse = 
                        (RetrievePrincipalAccessResponse)_service.Execute(retrieveRequest);

                    Console.Write("Retrieved principal access. ");

                    #endregion

                    #region RetrieveSharedPrincipalsAndAccess Message

                    // Create the request object and set the target.
                    RetrieveSharedPrincipalsAndAccessRequest retrieveSharedRequest = 
                        new RetrieveSharedPrincipalsAndAccessRequest()
                    {
                        Target = new EntityReference(Account.EntityLogicalName, _accountId)
                    };

                    // Execute the request.
                    RetrieveSharedPrincipalsAndAccessResponse retrieveSharedResponse = 
                        (RetrieveSharedPrincipalsAndAccessResponse)_service.Execute(retrieveSharedRequest);

                    Console.Write("Retrieved principals and access. ");

                    #endregion

                    #region RevokeAccess Message

                    // Create the request object and set the target and revokee.
                    RevokeAccessRequest revokeRequest = new RevokeAccessRequest()
                    {
                        Target = new EntityReference(Account.EntityLogicalName, _accountId),
                        Revokee = new EntityReference(SystemUser.EntityLogicalName, _userId)
                    };

                    // Execute the request.
                    RevokeAccessResponse revokeResponse =
                        (RevokeAccessResponse)_service.Execute(revokeRequest);

                    Console.Write("Revoked Access.");

                    #endregion

                    DeleteRequiredRecords(promptforDelete);
                }
                //</snippetSharingRecords1>
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }