예제 #1
0
        public async Task <Guid> AddUserToRecordAccessTeamAsync(Guid idTeamTemplate, EntityReference record, Guid idUser)
        {
            var teamId = await this.FindRecordAccessTeamIdAsync(record.Id, idTeamTemplate);

            if (teamId.HasValue)
            {
                if (await IsUserTeamMemberAsync(idUser, teamId.Value))
                {
                    return(teamId.Value);
                }
            }

            var request = new AddUserToRecordTeamRequest()
            {
                TeamTemplateId = idTeamTemplate,
                Record         = record,
                SystemUserId   = idUser,
            };

            var response = await _service.ExecuteAsync <AddUserToRecordTeamResponse>(request);

            StoreRecordAccessGroupCacheValue(idTeamTemplate, record.Id, response.AccessTeamId);

            return(response.AccessTeamId);
        }
        public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx)
        {
            AddUserToRecordTeamRequest addReq = (AddUserToRecordTeamRequest)request;

            EntityReference target         = addReq.Record;
            Guid            systemuserId   = addReq.SystemUserId;
            Guid            teamTemplateId = addReq.TeamTemplateId;

            if (target == null)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "Can not add to team without target");
            }

            if (systemuserId == Guid.Empty)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "Can not add to team without user");
            }

            if (teamTemplateId == Guid.Empty)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "Can not add to team without team");
            }
            IOrganizationService service = ctx.GetOrganizationService();

            AddUserToRecordTeamRequest addRequest = new AddUserToRecordTeamRequest
            {
                SystemUserId   = systemuserId,
                Record         = target,
                TeamTemplateId = teamTemplateId
            };

            AddUserToRecordTeamResponse response = (AddUserToRecordTeamResponse)service.Execute(addRequest);

            return(response);
        }
        public static AddUserToRecordTeamResponse AddUserToAccessTeam(this IOrganizationService service, EntityReference record, Guid userId, Guid teamTemplateId)
        {
            AddUserToRecordTeamRequest teamAddRequest2 = new AddUserToRecordTeamRequest();

            teamAddRequest2.Record         = record;
            teamAddRequest2.SystemUserId   = userId;
            teamAddRequest2.TeamTemplateId = teamTemplateId;
            return((AddUserToRecordTeamResponse)service.Execute(teamAddRequest2));
        }
예제 #4
0
        public void When_a_request_is_called_User_Is_Added_To_Record_Team()
        {
            var context = new XrmFakedContext();

            var teamTemplate = new TeamTemplate
            {
                Id = Guid.NewGuid(),
                DefaultAccessRightsMask = (int)AccessRights.ReadAccess
            };

            var user = new SystemUser
            {
                Id = Guid.NewGuid()
            };

            var account = new Account
            {
                Id = Guid.NewGuid()
            };

            context.Initialize(new Entity[]
            {
                teamTemplate, user, account
            });

            var executor = new AddUserToRecordTeamRequestExecutor();

            var req = new AddUserToRecordTeamRequest
            {
                Record         = account.ToEntityReference(),
                SystemUserId   = user.Id,
                TeamTemplateId = teamTemplate.Id
            };

            executor.Execute(req, context);

            var team = context.CreateQuery <Team>().FirstOrDefault(p => p.TeamTemplateId.Id == teamTemplate.Id);

            Assert.NotNull(team);

            var teamMembership = context.CreateQuery <TeamMembership>().FirstOrDefault(p => p.SystemUserId == user.Id && p.TeamId == team.Id);

            Assert.NotNull(teamMembership);

            var poa = context.CreateQuery("principalobjectaccess").FirstOrDefault(p => (Guid)p["objectid"] == account.Id &&
                                                                                  (Guid)p["principalid"] == team.Id);

            Assert.NotNull(poa);

            var response = context.AccessRightsRepository.RetrievePrincipalAccess(account.ToEntityReference(),
                                                                                  user.ToEntityReference());

            Assert.Equal((AccessRights)teamTemplate.DefaultAccessRightsMask, response.AccessRights);
        }
예제 #5
0
        private void AddUserToAccessTeam(string accessTeamName, EntityReference record, Guid userId, IOrganizationService service)
        {
            var req = new AddUserToRecordTeamRequest();

            req.Record       = record;
            req.SystemUserId = userId;
            var q = new QueryExpression("teamtemplate");

            q.Criteria.AddCondition("teamtemplatename", ConditionOperator.Equal, accessTeamName);
            var tt = orgAdminService.RetrieveMultiple(q);

            req.TeamTemplateId = tt.Entities.First().Id;
            service.Execute(req);
        }
        public void AdduserToAccessTeam(Guid userId, EntityReference recordEntityReference, string teamTemplateName)
        {
            Guid templateTeamid = Guid.Empty;

            using (OrganizationServiceContext context = new OrganizationServiceContext(ServiceProxy))
            {
                templateTeamid = (Guid)(context.CreateQuery("teamtemplate").Single(tt => (string)tt["teamtemplatename"] == teamTemplateName)["teamtemplateid"]);
            }
            AddUserToRecordTeamRequest AddUserToRecordTeamRequest = new AddUserToRecordTeamRequest()
            {
                SystemUserId   = userId,
                Record         = recordEntityReference,
                TeamTemplateId = templateTeamid
            };

            ServiceProxy.Execute(AddUserToRecordTeamRequest);
        }
예제 #7
0
        public void SimpleDeleteTest()
        {
            var contact = new Contact()
            {
                FirstName = "test 1"
            };

            contact.Id = testUser1Service.Create(contact);

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

            contact2.Id = testUser2Service.Create(contact2);

            try
            {
                testUser1Service.Delete("contact", contact2.Id);
                throw new XunitException();
            }
            catch (Exception ex)
            {
                if (!ex.Message.Contains("permission to access entity 'contact' for delete"))
                {
                    throw;
                }
            }

            var req = new AddUserToRecordTeamRequest();

            req.Record       = contact2.ToEntityReference();
            req.SystemUserId = testUser1.Id;

            var q = new QueryExpression("teamtemplate");

            q.Criteria.AddCondition("teamtemplatename", ConditionOperator.Equal, "TestDeleteContact");
            var tt = orgAdminService.RetrieveMultiple(q);

            req.TeamTemplateId = tt.Entities.First().Id;

            orgAdminService.Execute(req);

            //that user 1 can now delete contact 2
            testUser1Service.Delete("contact", contact2.Id);
        }
예제 #8
0
        public static AddUserToRecordTeamResponse AddUserToRecordTeam(this IOrganizationService service, EntityReference record, Guid userid, Guid templateid)
        {
            //USER CANNOT BE ADDDED IF DISABLED
            if (service.isUserDisabled(userid))
            {
                return(null);
            }


            var addUserToRecordTeamRequest = new AddUserToRecordTeamRequest
            {
                Record         = record,
                SystemUserId   = userid,
                TeamTemplateId = templateid
            };


            return((AddUserToRecordTeamResponse)service.Execute(addUserToRecordTeamRequest));
        }
        /// <summary>
        /// Executes the workflow activity.
        /// </summary>
        /// <param name="executionContext">The execution context.</param>
        protected override void Execute(CodeActivityContext executionContext)
        {
            // Create the tracing service
            ITracingService tracingService = executionContext.GetExtension<ITracingService>();

            if (tracingService == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");
            }

            tracingService.Trace("Entered " + _processName + ".Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
                executionContext.ActivityInstanceId,
                executionContext.WorkflowInstanceId);

            // Create the context
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();

            if (context == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
            }

            tracingService.Trace(_processName + ".Execute(), Correlation Id: {0}, Initiating User: {1}",
                context.CorrelationId,
                context.InitiatingUserId);

            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                Guid connectionId = Connection.Get(executionContext).Id;
                Entity connection = service.Retrieve("connection", connectionId, new ColumnSet("record1id", "record2id"));

                EntityReference connectedFromId = (EntityReference)connection["record1id"];
                EntityReference connectedToId = (EntityReference)connection["record2id"];

                //only run this if the connection is to a user record
                if (connectedToId.LogicalName.ToUpper() == "SYSTEMUSER")
                {
                    Guid teamTemplateId;
                    string teamTemplateName = TeamTemplateName.Get(executionContext);

                    //look up team template by name
                    QueryByAttribute querybyexpression = new QueryByAttribute("teamtemplate");
                    querybyexpression.ColumnSet = new ColumnSet("teamtemplatename", "teamtemplateid");
                    querybyexpression.Attributes.AddRange("teamtemplatename");
                    querybyexpression.Values.AddRange(teamTemplateName);
                    EntityCollection retrieved = service.RetrieveMultiple(querybyexpression);

                    //if we find something, we're set
                    if (retrieved.Entities.Count > 0)
                    {
                        teamTemplateId = retrieved.Entities[0].Id;
                    }
                    else
                    {
                        //throw exception if unable to find a matching template
                        throw new Exception("could not find team template named: " + teamTemplateName);
                    }

                    AddUserToRecordTeamRequest teamAddRequest = new AddUserToRecordTeamRequest();
                    teamAddRequest.Record = connectedFromId;
                    teamAddRequest.SystemUserId = connectedToId.Id;
                    teamAddRequest.TeamTemplateId = teamTemplateId;

                    AddUserToRecordTeamResponse response = (AddUserToRecordTeamResponse)service.Execute(teamAddRequest);
                }
            }
            catch (FaultException<OrganizationServiceFault> e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());

                // Handle the exception.
                throw;
            }
            catch (Exception e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());
                throw;
            }

            tracingService.Trace("Exiting " + _processName + ".Execute(), Correlation Id: {0}", context.CorrelationId);
        }
        public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx)
        {
            AddUserToRecordTeamRequest addReq = (AddUserToRecordTeamRequest)request;

            EntityReference target         = addReq.Record;
            Guid            systemuserId   = addReq.SystemUserId;
            Guid            teamTemplateId = addReq.TeamTemplateId;

            if (target == null)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "Can not add to team without target");
            }

            if (systemuserId == Guid.Empty)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "Can not add to team without user");
            }

            if (teamTemplateId == Guid.Empty)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "Can not add to team without team");
            }

            IOrganizationService service = ctx.GetOrganizationService();

            Entity teamTemplate = ctx.CreateQuery("teamtemplate").FirstOrDefault(p => p.Id == teamTemplateId);

            if (teamTemplate == null)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "Team template with id=" + teamTemplateId + " does not exist");
            }

            Entity user = ctx.CreateQuery("systemuser").FirstOrDefault(p => p.Id == systemuserId);

            if (user == null)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "User with id=" + teamTemplateId + " does not exist");
            }


            Entity team = ctx.CreateQuery("team").FirstOrDefault(p => ((EntityReference)p["teamtemplateid"]).Id == teamTemplateId);

            if (team == null)
            {
                team = new Entity("team")
                {
                    ["teamtemplateid"] = new EntityReference("teamtemplate", teamTemplateId)
                };
                team.Id = service.Create(team);
            }

            Entity tm = new Entity("teammembership")
            {
                ["systemuserid"] = systemuserId,
                ["teamid"]       = team.Id
            };

            tm.Id = service.Create(tm);

            Entity poa = new Entity("principalobjectaccess")
            {
                ["objectid"]         = target.Id,
                ["principalid"]      = team.Id,
                ["accessrightsmask"] = teamTemplate.Contains("defaultaccessrightsmask") ? teamTemplate["defaultaccessrightsmask"] : 0
            };

            poa.Id = service.Create(poa);

            ctx.AccessRightsRepository.GrantAccessTo(target, new PrincipalAccess
            {
                Principal  = user.ToEntityReference(),
                AccessMask = (AccessRights)poa["accessrightsmask"]
            });

            return(new AddUserToRecordTeamResponse
            {
                ResponseName = "AddUserToRecordTeam"
            });
        }
예제 #11
0
        public void SimpleUpdateTest()
        {
            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 update contact 2
            var updateContact = new Entity("contact");

            updateContact.Id           = contact2.Id;
            updateContact["firstname"] = "fred";
            try
            {
                testUser1Service.Update(updateContact);
                throw new XunitException();
            }
            catch (Exception ex)
            {
                if (!ex.Message.Contains("does not have write access"))
                {
                    throw;
                }
            }

            var req = new AddUserToRecordTeamRequest();

            req.Record       = contact2.ToEntityReference();
            req.SystemUserId = testUser1.Id;

            var q = new QueryExpression("teamtemplate");

            q.Criteria.AddCondition("teamtemplatename", ConditionOperator.Equal, "TestWriteContact");
            var tt = orgAdminService.RetrieveMultiple(q);

            req.TeamTemplateId = tt.Entities.First().Id;

            orgAdminService.Execute(req);

            //that user 1 can now see contact 2
            updateContact              = new Entity("contact");
            updateContact.Id           = contact2.Id;
            updateContact["firstname"] = "fred";
            testUser1Service.Update(updateContact);

            var removereq = new RemoveUserFromRecordTeamRequest();

            removereq.Record         = contact2.ToEntityReference();
            removereq.SystemUserId   = testUser1.Id;
            removereq.TeamTemplateId = tt.Entities.First().Id;

            orgAdminService.Execute(removereq);

            //check that user 1 cannot see contact 2
            updateContact              = new Entity("contact");
            updateContact.Id           = contact2.Id;
            updateContact["firstname"] = "bob";
            try
            {
                testUser1Service.Update(updateContact);
                throw new XunitException();
            }
            catch (Exception ex)
            {
                if (!ex.Message.Contains("does not have write access"))
                {
                    throw;
                }
            }
        }
예제 #12
0
        public void SimpleReadTest()
        {
            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 see contact 2
            try
            {
                var checkContact = testUser1Service.Retrieve("contact", contact2.Id, new ColumnSet(true));
                throw new XunitException();
            }
            catch (Exception ex)
            {
                if (!ex.Message.Contains("does not have permission"))
                {
                    throw;
                }
            }

            var req = new AddUserToRecordTeamRequest();

            req.Record       = contact2.ToEntityReference();
            req.SystemUserId = testUser1.Id;

            var q = new QueryExpression("teamtemplate");

            q.Criteria.AddCondition("teamtemplatename", ConditionOperator.Equal, "TestReadContact");
            var tt = orgAdminService.RetrieveMultiple(q);

            req.TeamTemplateId = tt.Entities.First().Id;

            orgAdminService.Execute(req);

            //that user 1 can now see contact 2
            var checkContact2 = testUser1Service.Retrieve("contact", contact2.Id, new ColumnSet(true));

            var removereq = new RemoveUserFromRecordTeamRequest();

            removereq.Record         = contact2.ToEntityReference();
            removereq.SystemUserId   = testUser1.Id;
            removereq.TeamTemplateId = tt.Entities.First().Id;

            orgAdminService.Execute(removereq);

            //check that user 1 cannot see contact 2
            try
            {
                var checkContact = testUser1Service.Retrieve("contact", contact2.Id, new ColumnSet(true));
                throw new XunitException();
            }
            catch (Exception ex)
            {
                if (!ex.Message.Contains("does not have permission"))
                {
                    throw;
                }
            }
        }
예제 #13
0
        /// <summary>
        /// Executes the workflow activity.
        /// </summary>
        /// <param name="executionContext">The execution context.</param>
        protected override void Execute(CodeActivityContext executionContext)
        {
            // Create the tracing service
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            if (tracingService == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");
            }

            tracingService.Trace("Entered " + _processName + ".Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
                                 executionContext.ActivityInstanceId,
                                 executionContext.WorkflowInstanceId);

            // Create the context
            IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>();

            if (context == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
            }

            tracingService.Trace(_processName + ".Execute(), Correlation Id: {0}, Initiating User: {1}",
                                 context.CorrelationId,
                                 context.InitiatingUserId);

            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                Guid   connectionId = Connection.Get(executionContext).Id;
                Entity connection   = service.Retrieve("connection", connectionId, new ColumnSet("record1id", "record2id"));

                EntityReference connectedFromId = (EntityReference)connection["record1id"];
                EntityReference connectedToId   = (EntityReference)connection["record2id"];

                //only run this if the connection is to a user record
                if (connectedToId.LogicalName.ToUpper() == "SYSTEMUSER")
                {
                    Guid   teamTemplateId;
                    string teamTemplateName = TeamTemplateName.Get(executionContext);

                    //look up team template by name
                    QueryByAttribute querybyexpression = new QueryByAttribute("teamtemplate");
                    querybyexpression.ColumnSet = new ColumnSet("teamtemplatename", "teamtemplateid");
                    querybyexpression.Attributes.AddRange("teamtemplatename");
                    querybyexpression.Values.AddRange(teamTemplateName);
                    EntityCollection retrieved = service.RetrieveMultiple(querybyexpression);

                    //if we find something, we're set
                    if (retrieved.Entities.Count > 0)
                    {
                        teamTemplateId = retrieved.Entities[0].Id;
                    }
                    else
                    {
                        //throw exception if unable to find a matching template
                        throw new Exception("could not find team template named: " + teamTemplateName);
                    }

                    AddUserToRecordTeamRequest teamAddRequest = new AddUserToRecordTeamRequest();
                    teamAddRequest.Record         = connectedFromId;
                    teamAddRequest.SystemUserId   = connectedToId.Id;
                    teamAddRequest.TeamTemplateId = teamTemplateId;

                    AddUserToRecordTeamResponse response = (AddUserToRecordTeamResponse)service.Execute(teamAddRequest);
                }
            }
            catch (FaultException <OrganizationServiceFault> e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());

                // Handle the exception.
                throw;
            }
            catch (Exception e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());
                throw;
            }

            tracingService.Trace("Exiting " + _processName + ".Execute(), Correlation Id: {0}", context.CorrelationId);
        }