コード例 #1
0
        public async Task GrantAccess(GrantAccessRequest grantAccessRequest)
        {
            var project = await ProjectRepository.GetProjectAsync(grantAccessRequest.ProjectId);

            if (!project.HasMasterAccess(CurrentUserId, a => a.CanGrantRights))
            {
                var user = await UserRepository.GetById(CurrentUserId);

                if (!user.Auth.IsAdmin)
                {
                    project.RequestMasterAccess(CurrentUserId, a => a.CanGrantRights);
                }
            }

            project.EnsureProjectActive();

            var acl = project.ProjectAcls.SingleOrDefault(a => a.UserId == grantAccessRequest.UserId);

            if (acl == null)
            {
                acl = new ProjectAcl
                {
                    ProjectId = project.ProjectId,
                    UserId    = grantAccessRequest.UserId,
                };
                project.ProjectAcls.Add(acl);
            }

            SetRightsFromRequest(grantAccessRequest, acl);

            await UnitOfWork.SaveChangesAsync();
        }
コード例 #2
0
        public void GrantUserObjectAccess(ISiteSetting siteSetting, Guid objectId, string objectLogicalName, Guid userId, int accessrightmask)
        {
            IOrganizationService organizationService = GetClientContext(siteSetting);
            //no delete access
            GrantAccessRequest grant = new GrantAccessRequest();

            grant.Target = new EntityReference(objectLogicalName, objectId);

            PrincipalAccess principal = new PrincipalAccess();

            principal.Principal   = new EntityReference("systemuser", userId);
            principal.AccessMask  = AccessRights.ReadAccess | AccessRights.AppendAccess | AccessRights.WriteAccess | AccessRights.AppendToAccess | AccessRights.ShareAccess | AccessRights.AssignAccess;
            grant.PrincipalAccess = principal;

            try
            {
                GrantAccessResponse grant_response = (GrantAccessResponse)organizationService.Execute(grant);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            /*
             * Entity account = new Entity("principalobjectaccess");
             * account["objectid"] = objectId;
             * account["principalid"] = userId;
             * account["accessrightsmask"] = accessrightmask;
             * Guid _accountId = organizationService.Create(account);
             */
        }
コード例 #3
0
ファイル: TestSharing.cs プロジェクト: poer-dev/XrmMockup
        public void TestSharingAccess()
        {
            using (var context = new Xrm(orgAdminUIService)) {
                var businessunit = new BusinessUnit();
                businessunit.Id = orgAdminUIService.Create(businessunit);
                var otherUser   = crm.CreateUser(orgAdminUIService, businessunit.ToEntityReference(), SecurityRoles._000TestingRole);
                var sharingUser = crm.CreateUser(orgAdminUIService, businessunit.ToEntityReference(), SecurityRoles.SystemAdministrator);

                var otherService   = crm.CreateOrganizationService(otherUser.Id);
                var sharingService = crm.CreateOrganizationService(sharingUser.Id);
                var contact        = new Contact();
                contact.Id = sharingService.Create(contact);


                FaultException faultException = null;
                try {
                    otherService.Retrieve(Contact.EntityLogicalName, contact.Id, new ColumnSet(true));
                    Assert.Fail();
                } catch (FaultException e) {
                    faultException = e;
                }
                var req = new GrantAccessRequest();
                req.PrincipalAccess = new PrincipalAccess()
                {
                    AccessMask = AccessRights.ReadAccess,
                    Principal  = otherUser.ToEntityReference()
                };
                req.Target = contact.ToEntityReference();
                sharingService.Execute(req);

                otherService.Retrieve(Contact.EntityLogicalName, contact.Id, new ColumnSet(true));
            }
        }
コード例 #4
0
        public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx)
        {
            GrantAccessRequest req = (GrantAccessRequest)request;

            ctx.AccessRightsRepository.GrantAccessTo(req.Target, req.PrincipalAccess);
            return(new GrantAccessResponse());
        }
コード例 #5
0
        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);
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: salmanaashish/Dynamics-SDK
//Share a record Read,Write and Append privileges with Team
        private void SharePrivileges(string targetEntityName, Guid targetRecordID, Guid teamID, bool read_Access, bool write_Access, bool append_Access, IOrganizationService orgService)
        {
            try
            {
//Get User or Team reference and Target Entity and record ID that needs to be shared.
                var          recordRef     = new EntityReference(targetEntityName, targetRecordID);
                var          teamRef       = new EntityReference("team", teamID);
                AccessRights Access_Rights = new AccessRights();
                Access_Rights = AccessRights.None;
//Read Access
                if (read_Access == true)
                {
                    Access_Rights = AccessRights.ReadAccess;
                }
//Write Access (or) Read, Write Access
                if (write_Access == true)
                {
                    if (Access_Rights == AccessRights.None)
                    {
                        Access_Rights = AccessRights.WriteAccess;
                    }
                    else
                    {
                        Access_Rights = Access_Rights | AccessRights.WriteAccess;
                    }
                }
//Append Access or all or any two accesses
                if (append_Access == true)
                {
                    if (Access_Rights == AccessRights.None)
                    {
                        Access_Rights = AccessRights.AppendToAccess | AccessRights.AppendAccess;
                    }
                    else
                    {
                        Access_Rights = Access_Rights | AccessRights.AppendToAccess | AccessRights.AppendAccess;
                    }
                }
                var grantAccess = new GrantAccessRequest
                {
                    PrincipalAccess = new PrincipalAccess
                    {
                        AccessMask = Access_Rights,
                        Principal  = teamRef
                    },
                    Target = recordRef
                };
// Execute the Request
                orgService.Execute(grantAccess);
            }
            catch (Exception ex)
            {
                throw new Exception("An error occured while applying Sharing rules for the record." + ex.Message);
            }
        }
コード例 #7
0
        private void DoTransfer()
        {
            var idfield = (record.LogicalName == "systemform") ? "formid" : record.LogicalName + "id";
            // Check if the view already exists on target organization
            var targetView = targetService.RetrieveMultiple(new QueryExpression(record.LogicalName)
            {
                ColumnSet = new ColumnSet(true),
                Criteria  = new FilterExpression
                {
                    Conditions =
                    {
                        new ConditionExpression(idfield, ConditionOperator.Equal, record.Id)
                    }
                }
            }).Entities.FirstOrDefault();

            if (targetView != null)
            {
                // We need to update the existing view
                CleanEntity(false);
                targetService.Update(record);
            }
            else
            {
                CleanEntity(true);

                var owner = record.GetAttributeValue <EntityReference>("ownerid");
                if (owner != null && owner.LogicalName == "team" || owner.Id != targetCurrentUserId)
                {
                    // Need to create the view for the current user
                    record.Attributes.Remove("ownerid");
                    record.Id       = targetService.Create(record);
                    record[idfield] = record.Id;

                    // Share it with ourselves
                    GrantAccessRequest grantRequest = new GrantAccessRequest()
                    {
                        Target          = record.ToEntityReference(),
                        PrincipalAccess = new PrincipalAccess()
                        {
                            Principal  = new EntityReference("systemuser", targetCurrentUserId),
                            AccessMask = AccessRights.WriteAccess | AccessRights.ReadAccess
                        }
                    };

                    // and then assign it to the team or user
                    record["ownerid"] = owner;
                    targetService.Update(record);
                }
                else
                {
                    targetService.Create(record);
                }
            }
        }
コード例 #8
0
 public void SharePrivileges(EntityReference targetEntity, EntityReference assigneeRef, bool readAccess, bool writeAccess, bool appendAccess)
 {
     try
     {
         AccessRights accessRights = new AccessRights();
         accessRights = AccessRights.None;
         //Read Access
         if (readAccess == true)
         {
             accessRights = AccessRights.ReadAccess;
         }
         //Write Access (or) Read, Write Access
         if (writeAccess == true)
         {
             if (accessRights == AccessRights.None)
             {
                 accessRights = AccessRights.WriteAccess;
             }
             else
             {
                 accessRights = accessRights | AccessRights.WriteAccess;
             }
         }
         //Append Access or all or any two accesses
         if (appendAccess == true)
         {
             if (accessRights == AccessRights.None)
             {
                 accessRights = AccessRights.AppendToAccess | AccessRights.AppendAccess;
             }
             else
             {
                 accessRights = accessRights | AccessRights.AppendToAccess | AccessRights.AppendAccess;
             }
         }
         var grantAccess = new GrantAccessRequest
         {
             PrincipalAccess = new PrincipalAccess
             {
                 AccessMask = accessRights,
                 Principal  = assigneeRef
             },
             Target = targetEntity
         };
         // Execute the Request
         this.Service.Execute(grantAccess);
     }
     catch (Exception ex)
     {
         throw new Exception("An error occured while applying Sharing rules for the record." + ex.Message +
                             assigneeRef.Id + "|| " + targetEntity.Id);
     }
 }
コード例 #9
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            #region "Load CRM Service from context"

            Common objCommon = new Common(executionContext);
            objCommon.tracingService.Trace("Load CRM Service from context --- OK");
            #endregion

            #region "Read Parameters"
            String _SharingRecordURL = this.SharingRecordURL.Get(executionContext);
            if (_SharingRecordURL == null || _SharingRecordURL == "")
            {
                return;
            }
            string[] urlParts       = _SharingRecordURL.Split("?".ToArray());
            string[] urlParams      = urlParts[1].Split("&".ToCharArray());
            string   objectTypeCode = urlParams[0].Replace("etc=", "");
            string   objectId       = urlParams[1].Replace("id=", "");
            objCommon.tracingService.Trace("ObjectTypeCode=" + objectTypeCode + "--ParentId=" + objectId);

            EntityReference teamReference = this.Team.Get(executionContext);
            principals.Clear();

            if (teamReference != null)
            {
                principals.Add(teamReference);
            }

            #endregion

            #region "ApplyRoutingRuteamReferenceleRequest Execution"
            string EntityName = objCommon.sGetEntityNameFromCode(objectTypeCode, objCommon.service);

            EntityReference refObject = new EntityReference(EntityName, new Guid(objectId));

            objCommon.tracingService.Trace("Grant Request--- Start");

            GrantAccessRequest grantRequest = new GrantAccessRequest();
            grantRequest.Target                     = refObject;
            grantRequest.PrincipalAccess            = new PrincipalAccess();
            grantRequest.PrincipalAccess.AccessMask = (AccessRights)getMask(executionContext);
            foreach (EntityReference principalObject2 in principals)
            {
                grantRequest.PrincipalAccess.Principal = principalObject2;
                GrantAccessResponse grantResponse = (GrantAccessResponse)objCommon.service.Execute(grantRequest);
            }

            objCommon.tracingService.Trace("Grant Request--- end");

            #endregion
        }
コード例 #10
0
        public static void ShareRecord(this OrganizationServiceContext context, EntityReference targetRef, EntityReference shareToRef)
        {
            var grantAccessRequest = new GrantAccessRequest
            {
                PrincipalAccess = new PrincipalAccess
                {
                    AccessMask = AccessRights.ReadAccess,
                    Principal  = shareToRef
                },
                Target = targetRef
            };

            context.Execute(grantAccessRequest);
        }
コード例 #11
0
ファイル: Helper.cs プロジェクト: wangfeng19890/oldcode
    public static void ShareToUser(Guid callerUser, Guid caseId, IOrganizationService crmService)
    {
        GrantAccessRequest grantAccessRequest = new GrantAccessRequest
        {
            PrincipalAccess = new PrincipalAccess
            {
                Principal  = new EntityReference("systemuser", callerUser),
                AccessMask = AccessRights.WriteAccess
            },
            Target = new EntityReference("incident", caseId)
        };

        crmService.Execute(grantAccessRequest);
    }
コード例 #12
0
        public void GrantAccess(EntityReference principalEntityReference, EntityReference targetEntityReference, AccessRights accessMask)
        {
            GrantAccessRequest grantRequest = new GrantAccessRequest()
            {
                PrincipalAccess = new PrincipalAccess()
                {
                    Principal  = principalEntityReference,
                    AccessMask = accessMask
                },
                Target = targetEntityReference
            };

            ServiceProxy.Execute(grantRequest);
        }
コード例 #13
0
        public void GrantAccess(EntityReference userOrTeam, EntityReference target, AccessRights acessRight)
        {
            GrantAccessRequest grantAccessRequest = new GrantAccessRequest
            {
                PrincipalAccess = new PrincipalAccess
                {
                    AccessMask = acessRight,
                    Principal  = userOrTeam
                },
                Target = target
            };

            service.Execute(grantAccessRequest);
        }
コード例 #14
0
        public void GrantAccess(EntityReference Record, EntityReference Principal, AccessRights AccessRights)
        {
            PrincipalAccess principalAccess = new PrincipalAccess();

            principalAccess.Principal  = Principal;
            principalAccess.AccessMask = AccessRights;

            GrantAccessRequest grantAccessRequest = new GrantAccessRequest();

            grantAccessRequest.Target          = Record;
            grantAccessRequest.PrincipalAccess = principalAccess;

            GrantAccessResponse grantAccessResponse = (GrantAccessResponse)OrganizationService.Execute(grantAccessRequest);
        }
コード例 #15
0
        /// <summary>
        /// Grants a specific user Read Access to a specific Entity record.
        /// </summary>
        /// <param name="OrganizationService"></param>
        /// <param name="Record">EntityReference of the record.</param>
        /// <param name="UserId">GUID of user that is getting access.</param>
        public void GrantUserReadAccess(EntityReference Record, Guid UserId)
        {
            PrincipalAccess principalAccess = new PrincipalAccess();

            principalAccess.Principal  = new EntityReference("systemuser", UserId);
            principalAccess.AccessMask = AccessRights.ReadAccess;

            GrantAccessRequest grantAccessRequest = new GrantAccessRequest();

            grantAccessRequest.Target          = Record;
            grantAccessRequest.PrincipalAccess = principalAccess;

            GrantAccessResponse grantAccessResponse = (GrantAccessResponse)OrganizationService.Execute(grantAccessRequest);
        }
コード例 #16
0
        public void Principal_Granted_Access_Multiple_Times_Only_Appears_Once()
        {
            var context  = new XrmFakedContext();
            var contact1 = new Contact {
                Id = Guid.NewGuid()
            };
            var user1 = new SystemUser {
                Id = Guid.NewGuid()
            };

            context.Initialize(new List <Entity>
            {
                contact1, user1
            });

            var service = context.GetFakedOrganizationService();

            GrantAccessRequest gar1 = new GrantAccessRequest
            {
                PrincipalAccess = new PrincipalAccess
                {
                    AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess,
                    Principal  = user1.ToEntityReference()
                },
                Target = contact1.ToEntityReference()
            };

            service.Execute(gar1);

            GrantAccessRequest gar2 = new GrantAccessRequest
            {
                PrincipalAccess = new PrincipalAccess
                {
                    AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess,
                    Principal  = user1.ToEntityReference()
                },
                Target = contact1.ToEntityReference()
            };

            service.Execute(gar2);

            RetrieveSharedPrincipalsAndAccessRequest req = new RetrieveSharedPrincipalsAndAccessRequest
            {
                Target = contact1.ToEntityReference()
            };
            RetrieveSharedPrincipalsAndAccessResponse resp = (RetrieveSharedPrincipalsAndAccessResponse)service.Execute(req);

            Assert.Equal(1, resp.PrincipalAccesses.Length);
        }
コード例 #17
0
        public static void Share(this DataAccessContext pluginContext, EntityReference targetEntity, EntityReference shareWith, AccessRights accessRights)
        {
            // Grant the first user read access to the created lead.
            var grantAccessRequest = new GrantAccessRequest
            {
                PrincipalAccess = new PrincipalAccess
                {
                    AccessMask = accessRights,
                    Principal  = shareWith
                },
                Target = targetEntity
            };

            pluginContext.OrganizationService.Execute(grantAccessRequest);
        }
コード例 #18
0
        //Share function
        private void ShareRecord(Guid teamId, Entity workOrder, IOrganizationService service, CodeActivityContext activityContext)
        {
            GrantAccessRequest grantRequest = new GrantAccessRequest()
            {
                Target          = new EntityReference(workOrder.LogicalName, workOrder.Id),
                PrincipalAccess = new PrincipalAccess()
                {
                    Principal  = new EntityReference("team", teamId),
                    AccessMask = (AccessRights)getMask(activityContext)
                }
            };

            // Execute the request.
            GrantAccessResponse grantResponse =
                (GrantAccessResponse)service.Execute(grantRequest);
        }
コード例 #19
0
        //Share function
        private void ShareRecordasReadOnly(Guid Userid, Entity task, IOrganizationService service)
        {
            GrantAccessRequest grantRequest = new GrantAccessRequest()
            {
                Target          = new EntityReference(task.LogicalName, task.Id),
                PrincipalAccess = new PrincipalAccess()
                {
                    Principal  = new EntityReference("systemuser", Userid),
                    AccessMask = AccessRights.ReadAccess
                }
            };

            // Execute the request.
            GrantAccessResponse grantResponse =
                (GrantAccessResponse)service.Execute(grantRequest);
        }
コード例 #20
0
        //Share function
        private void ShareRecord(Guid userId, Entity task, IOrganizationService service, CodeActivityContext activityContext)
        {
            GrantAccessRequest grantRequest = new GrantAccessRequest()
            {
                Target          = new EntityReference(task.LogicalName, task.Id),
                PrincipalAccess = new PrincipalAccess()
                {
                    Principal  = new EntityReference("systemuser", userId),
                    AccessMask = (AccessRights)getMask(activityContext)
                }
            };

            // Execute the request.
            GrantAccessResponse grantResponse =
                (GrantAccessResponse)service.Execute(grantRequest);
        }
コード例 #21
0
        public void Entity_Granted_Multiple_Access_Has_Access()
        {
            var context = new XrmFakedContext();
            var contact = new Contact {
                Id = Guid.NewGuid()
            };
            var user = new SystemUser {
                Id = Guid.NewGuid()
            };

            context.Initialize(new List <Entity>
            {
                contact, user
            });

            var service = context.GetFakedOrganizationService();

            GrantAccessRequest gar = new GrantAccessRequest
            {
                PrincipalAccess = new PrincipalAccess
                {
                    AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess | AccessRights.DeleteAccess | AccessRights.CreateAccess,
                    Principal  = user.ToEntityReference()
                },
                Target = contact.ToEntityReference()
            };

            service.Execute(gar);

            RetrievePrincipalAccessRequest rpar = new RetrievePrincipalAccessRequest
            {
                Target    = contact.ToEntityReference(),
                Principal = user.ToEntityReference()
            };

            RetrievePrincipalAccessResponse rpaResp = (RetrievePrincipalAccessResponse)service.Execute(rpar);

            Assert.NotEqual(AccessRights.None, rpaResp.AccessRights);
            Assert.True(rpaResp.AccessRights.HasFlag(AccessRights.ReadAccess));
            Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.AppendAccess));
            Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.AppendToAccess));
            Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.AssignAccess));
            Assert.True(rpaResp.AccessRights.HasFlag(AccessRights.CreateAccess));
            Assert.True(rpaResp.AccessRights.HasFlag(AccessRights.DeleteAccess));
            Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.ShareAccess));
            Assert.True(rpaResp.AccessRights.HasFlag(AccessRights.WriteAccess));
        }
コード例 #22
0
        public void SimpleShareTest()
        {
            var contact = new Contact()
            {
                FirstName = "test 1"
            };

            contact.Id = testUser1Service.Create(contact);

            var contact2 = new Contact()
            {
                FirstName = "test 2"
            };

            contact2.Id = testUser2Service.Create(contact2);

            //check that user 1 cannot share contact 2 with user 3
            var grant = new GrantAccessRequest();

            grant.PrincipalAccess = new PrincipalAccess()
            {
                Principal = testUser3.ToEntityReference(), AccessMask = AccessRights.ReadAccess
            };
            grant.Target = contact2.ToEntityReference();
            try
            {
                testUser1Service.Execute(grant);
                throw new XunitException();
            }
            catch (Exception ex)
            {
                if (!ex.Message.Contains("does not have share access"))
                {
                    throw;
                }
            }

            //user 1 needs read access to be able to share contact 2 with read access to add him to the read access team first
            AddUserToAccessTeam("TestReadContact", contact2.ToEntityReference(), testUser1.Id);

            AddUserToAccessTeam("TestShareContact", contact2.ToEntityReference(), testUser1.Id);
            testUser1Service.Execute(grant);

            testUser3Service.Retrieve("contact", contact2.Id, new ColumnSet(true));
        }
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Share a queue to the team.
        /// Optionally delete any entity records that were created for this sample.
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        /// </summary>

        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 = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();


                    // Grant the team Read and AppendTo access to the queue.
                    // Having Read and AppendTo privileges gives a team a full access
                    // to the queue items, but only read access to the queue. For
                    // example, team members can’t change the queue name, but they
                    // can make any modifications to the queue items.
                    GrantAccessRequest grantAccessRequest = new GrantAccessRequest
                    {
                        PrincipalAccess = new PrincipalAccess
                        {
                            Principal  = new EntityReference(Team.EntityLogicalName, _teamId),
                            AccessMask = AccessRights.ReadAccess
                                         | AccessRights.AppendToAccess
                        },
                        Target = new EntityReference(Queue.EntityLogicalName, _queueId)
                    };

                    _serviceProxy.Execute(grantAccessRequest);


                    Console.WriteLine("Queue has been shared to the team.");

                    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;
            }
        }
コード例 #24
0
        /// <summary>
        /// Grant a security principal (user or team) access to the specified record.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.grantaccessrequest(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="GrantAccessResponse"/>
        /// </returns>
        public GrantAccessResponse Share(PrincipalType shareToPrincipal, Guid shareToId, string targetEntityLogicalName, Guid targetId, AccessRights targetAccessRights)
        {
            ExceptionThrow.IfGuidEmpty(shareToId, "shareToId");
            ExceptionThrow.IfGuidEmpty(targetId, "targetId");
            ExceptionThrow.IfNullOrEmpty(targetEntityLogicalName, "targetEntityLogicalName");

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

            return((GrantAccessResponse)this.OrganizationService.Execute(request));
        }
コード例 #25
0
        /// <summary>
        /// Grants shared access to a team for any entity
        /// </summary>
        /// <param name="service"></param>
        /// <param name="entityReference">Reference to the entity that will have access granted</param>
        /// <param name="principals">Entity Refs for Teams or Users that will be granted permissions </param>
        /// <param name="shareAppend">Share append</param>
        /// <param name="shareAppendTo">Share append to</param>
        /// <param name="shareAssign">Share assign</param>
        /// <param name="shareDelete">Share delete</param>
        /// <param name="shareRead">Share read</param>
        /// <param name="shareShare">Share share</param>
        /// <param name="shareWrite">Share write</param>
        public static void GrantAccess(this IOrganizationService service, EntityReference entityReference, List <EntityReference> principals, bool shareAppend,
                                       bool shareAppendTo, bool shareAssign, bool shareDelete, bool shareRead, bool shareShare, bool shareWrite)
        {
            var grantRequest = new GrantAccessRequest
            {
                Target          = entityReference,
                PrincipalAccess = new PrincipalAccess
                {
                    AccessMask = (AccessRights)GetMask(shareAppend, shareAppendTo, shareAssign, shareDelete, shareRead,
                                                       shareShare, shareWrite)
                }
            };

            foreach (EntityReference principal in principals)
            {
                grantRequest.PrincipalAccess.Principal = principal;
                service.Execute(grantRequest);
            }
        }
コード例 #26
0
        public static GrantAccessResponse GrantAccess(
            this IOrganizationService service,
            EntityReference principal,
            EntityReference target,
            AccessRights accessMask)
        {
            var request = new GrantAccessRequest
            {
                PrincipalAccess = new PrincipalAccess
                {
                    AccessMask = accessMask,
                    Principal  = principal
                },
                Target = target
            };

            var response = service.Execute <GrantAccessResponse>(request);

            return(response);
        }
コード例 #27
0
        /// <summary>
        /// ShareRecord
        /// </summary>
        /// <param name="teamId"></param>
        /// <param name="targetEntity"></param>

        private void ShareRecord(Guid teamId, EntityReference targetEntity)
        {
            _tracingService.Trace("Sharing started with:" + teamId);
            _tracingService.Trace("Sharing started with:" + targetEntity.LogicalName + ":" + targetEntity.Id);
            //sharing
            var grantAccessRequest = new GrantAccessRequest
            {
                PrincipalAccess = new PrincipalAccess
                {
                    AccessMask = AccessRights.ReadAccess | AccessRights.AppendAccess | AccessRights.AppendToAccess | AccessRights.WriteAccess,
                    Principal  = new EntityReference
                    {
                        LogicalName = "team",
                        Id          = teamId//new Guid("C7BC381B-EC5E-E811-A86F-000D3AB17C7B")
                    }
                },
                Target = new EntityReference(targetEntity.LogicalName, targetEntity.Id)
            };

            service.Execute(grantAccessRequest);
            _tracingService.Trace("Shared the record:" + targetEntity.Id);
        }
コード例 #28
0
    public void Execute(IServiceProvider serviceprovider)
    {
        //obtain the tracingservice
        ITracingService tracingservice =
            (ITracingService)serviceprovider.GetService(typeof(ITracingService));
        //obtain the context
        IPluginExecutionContext context =
            (IPluginExecutionContext)serviceprovider.GetService(typeof(IPluginExecutionContext));

        //validation point for target
        if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity && context.depth < 2)
        {
            Entity entity = (Entity)context.InputParameters["Target"];

            IOrganizationService ServiceFactory = (IOrganizationService)serviceprovider.GetService(typeof(IOrganizationService));
            IOrganizationService service        = ServiceFactory.CreateOrganizationService(context.UserId);

            try
            {
                //for sharing a case
                var incidentref = new EntityReference(entity.LogicalName, entity.ID);
                var userref     = new EntityReference("systemuser", new Guid("76858628c4d2e911910400155d0a0438"));

                var grantaccessrequest = new GrantAccessRequest
                {
                    PrincipalAccess = new PrincipalAccess
                    {
                        AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess | AccessRights.AppendAccess | AccessRights.AppendToAccess
                    },
                    Target = incidentref
                };
                service.Execute(incidentref);

                //optionset

                //for getting the optionset
                Entity status_value = service.Retrieve(entity.LogicalName, entity.Id, new ColumnSet("statuscode"));
                var    status_info  = (OptionSetValue)status_value.Attributes["statuscode"];
                var    status_value = status_info.Attributes["statuscode"];
                int    status_num   = status_value.Value;

                //for setting the optionset
                Entity status_ref = service.Retrieve(entity.LogicalName, entity.Id, new ColumnSet("statuscode"));
                status_ref.Attributes["statuscode"] = new OptionSetValue(10000);
                service.Update(status_ref);

                //optionset


                //LookupValue:
                //for getting the Lookup value

                Entity incidentref = service.Retrieve(entity.LogicalName, entity.Id, new ColumnSet("new_pendingat"));
                if (incidentref.Contains("new_pendingat"))
                {
                    var ownerdetails = (EntityReference)incidentref.Attributes["new_pendingat"];

                    var ownerstatus = service.Retrieve(ownerdetails.LogicalName, ownerdetails.Id, new ColumnSet("fullname"));
                    if (ownerstatus.Contains("fullname"))
                    {
                    }
                }
                //if ryou dont have Entity's logical Id and want to retrieve something from there

                QueryByAttribute querybyexpression = new QueryByAttribute("new_joborder");
                querybyexpression.AddAttributeValue("new_relatedcaseid", entity.Id);
                int count = querybyexpression.Values.Count;



                //
                QueryByAttribute querybyexpression = new QueryByAttribute("new_joborder");
                querybyexpression.AddAttributeValue("new_relatedcaseid", entity.Id);
                int count = querybyexpression.Values.Count;
                //

                QueryByAttribute querybyexpression = new QueryByAttribute("new_joborder");
                querybyexpression.AddAttributeValue("new_relatedcaseid", entity.Id);
                int count = querybyexpression.Values.Count;
            }

            catch (Exception ex)
            {
                throw new Exception("" + ex.Message);
            }
        }
    }
コード例 #29
0
ファイル: UserAccess.cs プロジェクト: cesugden/Scripts
        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;
            }
        }
コード例 #31
0
        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))
                {
                    String ldapPath = String.Empty;
                    Guid   businessUnitId;

                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Call this method to create any data that this sample requires.
                    CreateRequiredRecords();

                    // Retrieve the sales people that will be added to the team.
                    salesPersons = SystemUserProvider.RetrieveSalespersons(_serviceProxy, ref ldapPath);

                    // Get the ID's of the current user and business unit.
                    var who         = new WhoAmIRequest();
                    var whoResponse = (WhoAmIResponse)_serviceProxy.Execute(who);
                    _currentUserId = whoResponse.UserId;
                    businessUnitId = whoResponse.BusinessUnitId;

                    // Create a access team.
                    var team = new Team
                    {
                        AdministratorId = new EntityReference(
                            "systemuser", _currentUserId),
                        Name           = "UserAccess Test Team",
                        BusinessUnitId = new EntityReference(
                            "businessunit", businessUnitId),
                        TeamType = new OptionSetValue((int)TeamTeamType.Access),
                    };

                    _teamId = _serviceProxy.Create(team);
                    Console.WriteLine("Created an access team named '{0}'.", team.Name);

                    // Add two sales people to the access team.
                    var addToTeamRequest = new AddMembersTeamRequest
                    {
                        TeamId    = _teamId,
                        MemberIds = new[] { salesPersons[0], salesPersons[1] }
                    };
                    _serviceProxy.Execute(addToTeamRequest);
                    Console.WriteLine("Added two sales people to the team.");

                    // Grant the team read/write access to an account.
                    var accountReference   = new EntityReference(Account.EntityLogicalName, _accountId);
                    var teamReference      = new EntityReference(Team.EntityLogicalName, _teamId);
                    var grantAccessRequest = new GrantAccessRequest
                    {
                        PrincipalAccess = new PrincipalAccess
                        {
                            AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess,
                            Principal  = teamReference
                        },
                        Target = accountReference
                    };
                    _serviceProxy.Execute(grantAccessRequest);
                    Console.WriteLine("Granted read/write access on the account record to the team.");

                    // Retrieve and display access information for the account.
                    RetrieveAndDisplayEntityAccess(accountReference);

                    // Display the account access for the team and its members.
                    var currentUserReference = new EntityReference(
                        SystemUser.EntityLogicalName, _currentUserId);
                    RetrieveAndDisplayPrincipalAccess(accountReference, currentUserReference,
                                                      "Current User");
                    var firstSalesPersonReference = new EntityReference(
                        SystemUser.EntityLogicalName, salesPersons[0]);
                    RetrieveAndDisplayPrincipalAccess(accountReference, firstSalesPersonReference,
                                                      "Sales Person");
                    var secondSalesPersonReference = new EntityReference(
                        SystemUser.EntityLogicalName, salesPersons[1]);
                    RetrieveAndDisplayPrincipalAccess(accountReference, secondSalesPersonReference,
                                                      "Sales Person");

                    // Delete all records created by this sample.
                    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;
            }
        }
コード例 #32
0
        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))
                {
                    String ldapPath = String.Empty;
                    Guid businessUnitId;

                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Call this method to create any data that this sample requires.
                    CreateRequiredRecords();

                    // Retrieve the sales people that will be added to the team.
                    salesPersons = SystemUserProvider.RetrieveSalespersons(_serviceProxy, ref ldapPath);

                    // Get the ID's of the current user and business unit.
                    var who = new WhoAmIRequest();
                    var whoResponse = (WhoAmIResponse)_serviceProxy.Execute(who);
                    _currentUserId = whoResponse.UserId;
                    businessUnitId = whoResponse.BusinessUnitId;

                    //<snippetCreateAndShareAccessTeam1>
                    // Create a access team.
                    var team = new Team
                    {
                        AdministratorId = new EntityReference(
                            "systemuser", _currentUserId),
                        Name = "UserAccess Test Team",
                        BusinessUnitId = new EntityReference(
                            "businessunit", businessUnitId),
                        TeamType = new OptionSetValue((int)TeamTeamType.Access),
                    };

                    _teamId = _serviceProxy.Create(team);
                    Console.WriteLine("Created an access team named '{0}'.", team.Name);

                    // Add two sales people to the access team.
                    var addToTeamRequest = new AddMembersTeamRequest
                    {
                        TeamId = _teamId,
                        MemberIds = new[] { salesPersons[0], salesPersons[1] }
                    };
                    _serviceProxy.Execute(addToTeamRequest);
                    Console.WriteLine("Added two sales people to the team.");
                    
                    // Grant the team read/write access to an account.
                    var accountReference = new EntityReference(Account.EntityLogicalName, _accountId);
                    var teamReference = new EntityReference(Team.EntityLogicalName, _teamId);
                    var grantAccessRequest = new GrantAccessRequest
                    {
                        PrincipalAccess = new PrincipalAccess
                        {
                            AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess,
                            Principal = teamReference
                        },
                        Target = accountReference
                    };
                    _serviceProxy.Execute(grantAccessRequest);
                    Console.WriteLine("Granted read/write access on the account record to the team.");
                    //</snippetCreateAndShareAccessTeam1>

                    // Retrieve and display access information for the account.
                    RetrieveAndDisplayEntityAccess(accountReference);

                    // Display the account access for the team and its members.
                    var currentUserReference = new EntityReference(
                        SystemUser.EntityLogicalName, _currentUserId);
                    RetrieveAndDisplayPrincipalAccess(accountReference, currentUserReference,
                        "Current User");
                    var firstSalesPersonReference = new EntityReference(
                        SystemUser.EntityLogicalName, salesPersons[0]);
                    RetrieveAndDisplayPrincipalAccess(accountReference, firstSalesPersonReference,
                        "Sales Person");
                    var secondSalesPersonReference = new EntityReference(
                        SystemUser.EntityLogicalName, salesPersons[1]);
                    RetrieveAndDisplayPrincipalAccess(accountReference, secondSalesPersonReference,
                        "Sales Person");
                    
                    // Delete all records created by this sample.
                    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;
            }
        }
コード例 #33
0
ファイル: SharingRecords.cs プロジェクト: cesugden/Scripts
        /// <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;
            }
        }