Exemple #1
0
        /// <summary>
        /// Public method for verifying if a given principal (user or machine) is a member of a given group.
        /// </summary>
        /// <param name="principalName">string</param>
        /// <param name="type">PrincipalType</param>
        /// <param name="groupName">string</param>
        /// <returns>bool</returns>
        public static bool IsMemberOf(string principalName, PrincipalType type, string groupName)
        {
            bool             returnValue = false;
            PrincipalContext context     = new PrincipalContext(ContextType.Domain);

            try
            {
                switch (type)
                {
                case PrincipalType.Machine:
                    using (var comp = ComputerPrincipal.FindByIdentity(context, principalName))
                    {
                        returnValue = IsMemberOf(groupName, comp);
                    }
                    break;

                case PrincipalType.User:
                    using (var user = UserPrincipal.FindByIdentity(context, principalName))
                    {
                        returnValue = IsMemberOf(groupName, user);
                    }
                    break;
                }

                return(returnValue);
            }
            catch
            {
                throw;
            }
            finally
            {
                context = null;
            }
        }
        public void Inverts_and_sets_foreign_key_if_matching_non_shadow_property_added_on_principal_type()
        {
            var relationshipBuilder = PrincipalType
                                      .Relationship(DependentType, "InverseReferenceNav", "SomeNav", ConfigurationSource.Convention)
                                      .IsUnique(true, ConfigurationSource.Convention);

            var fk = (IForeignKey)relationshipBuilder.Metadata;

            Assert.Same(fk, PrincipalType.Metadata.GetForeignKeys().Single());
            Assert.Equal("InverseReferenceNavKayPee", fk.Properties.Single().Name);
            Assert.Same(fk.DeclaringEntityType, PrincipalType.Metadata);
            Assert.Same(fk.PrincipalEntityType, DependentType.Metadata);
            Assert.True(fk.IsUnique);

            var property = DependentType.Property(DependentEntity.SomeNavIDProperty, ConfigurationSource.Convention);

            Assert.Same(property, new ForeignKeyPropertyDiscoveryConvention().Apply(property));
            Assert.Same(property, new ForeignKeyPropertyDiscoveryConvention().Apply(property));

            var newFk = DependentType.Metadata.GetForeignKeys().Single();

            Assert.NotSame(fk, newFk);
            Assert.Equal(property.Metadata, newFk.Properties.Single());
            Assert.Same(newFk.DeclaringEntityType, fk.PrincipalEntityType);
            Assert.Same(newFk.PrincipalEntityType, fk.DeclaringEntityType);
            Assert.True(newFk.IsUnique);
        }
		public D2LPrincipal( IAccessToken accessToken ) {
			m_accessToken = accessToken;

			m_tenantId = new Lazy<Guid>( GetTenantId );

			m_scopes = new Lazy<List<Scope>>(
				() => m_accessToken.GetScopes().ToList()
			);

			long userId;
			if ( !m_accessToken.TryGetUserId( out userId ) ) {
				m_principalType = PrincipalType.Service;
				return;
			}

			m_userId = userId;

			long actualUserId;
			if ( !m_accessToken.TryGetActualUserId( out actualUserId ) ) {
				// Doing this means that code that wants to ignore
				// impersonation can do so with less branching.
				m_actualUserId = userId;
				return;
			}

			m_actualUserId = actualUserId;
		}
Exemple #4
0
        public void Does_not_invert_if_both_entity_types_can_have_non_pk_fk_property()
        {
            DependentType.Property(DependentEntity.PeEKaYProperty, ConfigurationSource.Convention);
            PrincipalType.Property(PrincipalEntity.DependentEntityKayPeeProperty, ConfigurationSource.Convention);

            var relationshipBuilder = DependentType.Relationship(
                DependentType,
                PrincipalType,
                null,
                null,
                null,
                null,
                ConfigurationSource.Convention,
                isUnique: true);

            var newRelationshipBuilder = new ForeignKeyPropertyDiscoveryConvention().Apply(relationshipBuilder);

            Assert.NotSame(relationshipBuilder, newRelationshipBuilder);
            Assert.Same(PrincipalType.Metadata, newRelationshipBuilder.Metadata.EntityType);

            newRelationshipBuilder = new ForeignKeyPropertyDiscoveryConvention().Apply(newRelationshipBuilder);

            var fk = (IForeignKey)newRelationshipBuilder.Metadata;

            Assert.Same(DependentType.Metadata.GetPrimaryKey(), fk.PrincipalKey);
            Assert.True(fk.IsUnique);
            Assert.False(fk.IsRequired);
        }
Exemple #5
0
        public void Foreign_key_matching_given_property_is_found()
        {
            DependentType.GetOrAddProperty("SomeNavID", typeof(int), shadowProperty: true);
            DependentType.GetOrAddProperty("SomeNavPeEKaY", typeof(int), shadowProperty: true);
            DependentType.GetOrAddProperty("PrincipalEntityID", typeof(int), shadowProperty: true);
            DependentType.GetOrAddProperty("PrincipalEntityPeEKaY", typeof(int), shadowProperty: true);
            var fkProperty1 = DependentType.GetOrAddProperty("No", typeof(int), shadowProperty: true);
            var fkProperty2 = DependentType.GetOrAddProperty("IAmYourFk", typeof(int), shadowProperty: true);

            var fk = DependentType.GetOrAddForeignKey(new[] { fkProperty1, fkProperty2 }, PrincipalType.GetOrAddKey(
                                                          new[]
            {
                PrincipalType.GetOrAddProperty("Id1", typeof(int), shadowProperty: true),
                PrincipalType.GetOrAddProperty("Id2", typeof(int), shadowProperty: true)
            }));

            Assert.Same(
                fk,
                new ForeignKeyConvention().TryGetForeignKey(
                    PrincipalType,
                    DependentType,
                    "SomeNav",
                    "SomeInverse",
                    new[] { fkProperty1, fkProperty2 },
                    new Property[0],
                    isUnique: false));
        }
Exemple #6
0
        public async Task <IEnumerable <IFabricPrincipal> > SearchPrincipalsAsync(
            string searchText,
            PrincipalType principalType,
            string searchType,
            string tenantId = null)
        {
            switch (searchType)
            {
            case SearchTypes.Wildcard:
                _azureQuery = new AzureWildcardQuery();
                break;

            case SearchTypes.Exact:
                _azureQuery = new AzureExactMatchQuery();
                break;

            default:
                throw new DirectorySearchException($"{searchType} is not a valid search type");
            }

            switch (principalType)
            {
            case PrincipalType.User:
                return(await GetUserPrincipalsAsync(searchText, tenantId).ConfigureAwait(false));

            case PrincipalType.Group:
                return(await GetGroupPrincipalsAsync(searchText, tenantId).ConfigureAwait(false));

            default:
                return(await GetUserAndGroupPrincipalsAsync(searchText, tenantId).ConfigureAwait(false));
            }
        }
Exemple #7
0
        public void Creates_foreign_key_using_given_dependent_and_principal_properties()
        {
            DependentType.GetOrAddProperty("SomeNavID", typeof(int), shadowProperty: true);
            DependentType.GetOrAddProperty("SomeNavPeEKaY", typeof(int), shadowProperty: true);
            DependentType.GetOrAddProperty("PrincipalEntityID", typeof(int), shadowProperty: true);
            DependentType.GetOrAddProperty("PrincipalEntityPeEKaY", typeof(int), shadowProperty: true);
            var fkProperty1           = DependentType.GetOrAddProperty("ThatsNotTrue!", typeof(int), shadowProperty: true);
            var fkProperty2           = DependentType.GetOrAddProperty("ThatsImpossible!", typeof(int), shadowProperty: true);
            var principalKeyProperty1 = PrincipalType.GetOrAddProperty("SearchYourFeelings", typeof(int), shadowProperty: true);
            var principalKeyProperty2 = PrincipalType.GetOrAddProperty("YouKnowItToBeTrue!", typeof(int), shadowProperty: true);

            var fk = (IForeignKey) new ForeignKeyConvention().FindOrCreateForeignKey(
                PrincipalType,
                DependentType,
                "SomeNav",
                "SomeInverse",
                new[] { fkProperty1, fkProperty2 },
                new[] { principalKeyProperty1, principalKeyProperty2 },
                isUnique: false);

            Assert.Same(fkProperty1, fk.Properties[0]);
            Assert.Same(fkProperty2, fk.Properties[1]);
            Assert.Same(principalKeyProperty1, fk.ReferencedProperties[0]);
            Assert.Same(principalKeyProperty2, fk.ReferencedProperties[1]);
            Assert.False(fk.IsUnique);
            Assert.True(fk.IsRequired);
        }
Exemple #8
0
        public D2LPrincipal(IAccessToken accessToken)
        {
            m_accessToken = accessToken;

            m_tenantId = new Lazy <Guid>(GetTenantId);

            m_scopes = new Lazy <List <Scope> >(
                () => m_accessToken.GetScopes().ToList()
                );

            long userId;

            if (!m_accessToken.TryGetUserId(out userId))
            {
                m_principalType = PrincipalType.Service;
                return;
            }

            m_userId = userId;

            long actualUserId;

            if (!m_accessToken.TryGetActualUserId(out actualUserId))
            {
                // Doing this means that code that wants to ignore
                // impersonation can do so with less branching.
                m_actualUserId = userId;
                return;
            }

            m_actualUserId = actualUserId;
        }
        /// <summary>
        /// Add the specified <c>Principal</c> to the list of <c>Queue</c> members.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.addprincipaltoqueuerequest(v=crm.8).aspx
        /// </para>
        /// </summary>
        /// <param name="queueId"><c>Queue</c> Id</param>
        /// <param name="principalType"><c>System User</c> or <c>Team</c>. If the passed-in <c>PrincipalType.Team</c> , add each team member to the queue.</param>
        /// <param name="principalId"><c>Principal</c> Id</param>
        /// <returns>
        /// <see cref="AddPrincipalToQueueResponse"/>
        /// </returns>
        public AddPrincipalToQueueResponse AddPrincipalToQueue(Guid queueId, PrincipalType principalType, Guid principalId)
        {
            ExceptionThrow.IfGuidEmpty(queueId, "queueId");
            ExceptionThrow.IfGuidEmpty(principalId, "principalId");

            Entity principalEntity = null;

            switch (principalType)
            {
            case PrincipalType.SystemUser:
                SystemUserHelper systemuserHelper = new SystemUserHelper(this.OrganizationService);
                principalEntity = systemuserHelper.Get(principalId, "fullname");
                break;

            case PrincipalType.Team:
                TeamHelper teamHelper = new TeamHelper(this.OrganizationService);
                principalEntity = teamHelper.Get(principalId, "name");
                break;
            }

            ExceptionThrow.IfNull(principalEntity, "principal", string.Format("Principal not found with '{0}'", principalId.ToString()));

            AddPrincipalToQueueRequest request = new AddPrincipalToQueueRequest()
            {
                QueueId   = queueId,
                Principal = principalEntity
            };

            return((AddPrincipalToQueueResponse)this.OrganizationService.Execute(request));
        }
        private void AssertPrincipalExists(string name, PrincipalType principalType)
        {
            var escapedName = name.EscapeApostraphes().SurroundWithBrackets();

            Context.Assert($"(SELECT COUNT(*) FROM {principalType.GetUsersTable()} WHERE name = '{escapedName}') = 0",
                           $"User {name} does not exist.");
        }
Exemple #11
0
        private static ADPrincipal ConstructADPrincipal(DirectoryEntry de)
        {
            string        id     = de.Guid.ToString();
            string        name   = ( string )de.Properties[PRINCIPAL_NAME].Value;
            string        adPath = de.Path.Replace("LDAP://", "");
            PrincipalType type   = de.SchemaClassName.Equals("group", StringComparison.OrdinalIgnoreCase)
                                         ? PrincipalType.Group
                                         : PrincipalType.User;
            string email       = ( string )de.Properties[EMAIL_ADDRESS].Value ?? "";
            string displayName = ( string )de.Properties[DISPLAY_NAME].Value ?? "";
            string description = ( string )de.Properties[DESCRIPTION].Value ?? "";

            IList grpl = de.Properties[GROUPS];

            string[] groups;
            if (grpl != null)
            {
                groups = new string[grpl.Count];
                grpl.CopyTo(groups, 0);
            }
            else
            {
                groups = new string[0];
            }
            return(new ADPrincipal(id, name, adPath, type, email, displayName, description, groups));
        }
Exemple #12
0
        public void Inverts_if_principal_entity_type_can_have_nullable_fk_property_for_non_required_relationship()
        {
            DependentType.Property(DependentEntity.PeEKaYProperty, ConfigurationSource.Convention);
            var fkProperty = PrincipalType.Property(PrincipalEntity.DependentEntityKayPeeProperty, ConfigurationSource.Convention).Metadata;

            var relationshipBuilder = DependentType.Relationship(
                PrincipalType,
                DependentType,
                null,
                null,
                null,
                null,
                ConfigurationSource.Convention,
                isUnique: true,
                isRequired: false);

            var newRelationshipBuilder = new ForeignKeyPropertyDiscoveryConvention().Apply(relationshipBuilder);

            Assert.NotSame(relationshipBuilder, newRelationshipBuilder);
            Assert.Same(PrincipalType.Metadata, newRelationshipBuilder.Metadata.EntityType);

            newRelationshipBuilder = new ForeignKeyPropertyDiscoveryConvention().Apply(newRelationshipBuilder);

            var fk = (IForeignKey)PrincipalType.Metadata.GetForeignKeys().Single();

            Assert.Same(fk, newRelationshipBuilder.Metadata);
            Assert.Same(fkProperty, fk.Properties.Single());
            Assert.Same(DependentType.Metadata.GetPrimaryKey(), fk.PrincipalKey);
            Assert.True(fk.IsUnique);
            Assert.False(fk.IsRequired);
            Assert.Empty(DependentType.Metadata.GetForeignKeys());
        }
Exemple #13
0
 public OtoContext(DbContextOptions options,
                   PrincipalType type = PrincipalType.Student,
                   bool isRequired    = false) : base(options)
 {
     _type       = type;
     _isRequired = isRequired;
 }
Exemple #14
0
        public override int GetHashCode()
        {
            var hashCode = -109350059;

            hashCode = hashCode * -1521134295 + PrincipalType.GetHashCode();
            hashCode = hashCode * -1521134295 + PrincipalId.GetHashCode();
            return(hashCode);
        }
        public virtual string QueryText(string searchText, PrincipalType principalType)
        {
            var encodedSearchText = Encoder.LdapFilterEncode(searchText);
            var filter            = GetFilter(encodedSearchText);
            var nameFilter        = $"(|(sAMAccountName={filter})(givenName={filter})(sn={filter})(cn={filter}))";

            return(GetCategoryFilter(nameFilter, principalType));
        }
        public IEnumerable <FabricPrincipal> SearchPrincipals(string searchText, PrincipalType principalType)
        {
            var ldapQuery = BuildLdapQuery(searchText, principalType);

            var principals = FindPrincipalsWithDirectorySearcher(ldapQuery);

            return(principals);
        }
Exemple #17
0
        public void Foreign_key_matching_principal_type_name_plus_PK_name_is_found()
        {
            var fkProperty = DependentType.AddProperty("PrincipalEntityPeEKaY", typeof(int));

            var fk = DependentType.AddForeignKey(PrincipalType.GetKey(), fkProperty);

            Assert.Same(fk, new ForeignKeyConvention().FindOrCreateForeignKey(PrincipalType, DependentType, "SomeNav", "SomeInverse", isUnqiue: false));
        }
Exemple #18
0
 public FakeKerberosPrincipal(PrincipalType type, string principalName, string realm, byte[] password)
 {
     this.Type          = type;
     this.PrincipalName = principalName;
     this.Realm         = realm;
     this.Expires       = DateTimeOffset.UtcNow.AddMonths(1);
     this._password     = password;
 }
		public D2LPrincipal( IAccessToken accessToken ) {
			m_accessToken = accessToken;

			m_userId = accessToken.GetUserId();
			m_tenantId = new Lazy<Guid>( GetTenantId );
			m_principalType = string.IsNullOrEmpty( m_userId ) ? PrincipalType.Service : PrincipalType.User;
			m_scopes = new Lazy<List<Scope>>( () => m_accessToken.GetScopes().ToList() );
		}
        /// <summary>
        ///     Build the url that identify the collection where are the
        ///     calendar of principal.
        /// </summary>
        /// <param name="type">A principal can represent either a user or group.</param>
        /// <param name="principalId">
        ///     If the principal represents a user then put ith email here
        ///     otherwise put the name of the group here.
        /// </param>
        /// <returns>The url where to find the calendars of the principal.</returns>
        public static string BuildHomeSetUrl(PrincipalType type, string principalId)
        {
            //take the beginning of the url depending of the king of principal
            var colUrl = type == PrincipalType.User ? _userCollectionUrl : _groupCollectionUrl;

            //add the identifier of the pricipal
            return($"{_baseUrl}{colUrl}{principalId}/");
        }
Exemple #21
0
 public PeopleEditor(string siteURL, StringBuilder log,string searchString,PrincipalType searchType)
 {
     ViewModelLocator vmlocator = new ViewModelLocator();
     object[] args = new object[] { log, siteURL, this.Dispatcher, searchString, searchType };
     PeopleEditorViewModel vm = (PeopleEditorViewModel)vmlocator.GetViewModel(typeof(PeopleEditorViewModel), true, args);
     this.DataContext = vm;
     InitializeComponent();
     ldgIcon.StartRotating();
 }
        public void Read(TProtocol iprot)
        {
            bool   isset_principal_name = false;
            bool   isset_principal_type = false;
            TField field;

            iprot.ReadStructBegin();
            while (true)
            {
                field = iprot.ReadFieldBegin();
                if (field.Type == TType.Stop)
                {
                    break;
                }
                switch (field.ID)
                {
                case 1:
                    if (field.Type == TType.String)
                    {
                        Principal_name       = iprot.ReadString();
                        isset_principal_name = true;
                    }
                    else
                    {
                        TProtocolUtil.Skip(iprot, field.Type);
                    }
                    break;

                case 2:
                    if (field.Type == TType.I32)
                    {
                        Principal_type       = (PrincipalType)iprot.ReadI32();
                        isset_principal_type = true;
                    }
                    else
                    {
                        TProtocolUtil.Skip(iprot, field.Type);
                    }
                    break;

                default:
                    TProtocolUtil.Skip(iprot, field.Type);
                    break;
                }
                iprot.ReadFieldEnd();
            }
            iprot.ReadStructEnd();
            if (!isset_principal_name)
            {
                throw new TProtocolException(TProtocolException.INVALID_DATA);
            }
            if (!isset_principal_type)
            {
                throw new TProtocolException(TProtocolException.INVALID_DATA);
            }
        }
Exemple #23
0
        /// <summary>
        /// GetHashCode override
        /// </summary>
        /// <returns>The hash code of the object</returns>
        public override int GetHashCode()
        {
            int hash = 27;

            hash = (hash * 13) + PrincipalType.GetHashCode();
            hash = (hash * 13) + Name.GetHashCode();
            hash = (hash * 13) + Realm.GetHashCode();

            return(hash);
        }
Exemple #24
0
        public void Foreign_key_matching_principal_type_name_plus_Id_is_found()
        {
            var fkProperty = DependentType.GetOrAddProperty("PrincipalEntityID", typeof(int), shadowProperty: true);

            DependentType.GetOrAddProperty("PrincipalEntityPeEKaY", typeof(int), shadowProperty: true);

            var fk = DependentType.GetOrAddForeignKey(fkProperty, PrincipalType.GetPrimaryKey());

            Assert.Same(fk, new ForeignKeyConvention().FindOrCreateForeignKey(PrincipalType, DependentType, "SomeNav", "SomeInverse", isUnqiue: false));
        }
Exemple #25
0
        public int CompareTo(Subject other)
        {
            int result = PrincipalType.CompareTo(other.PrincipalType);

            if (result == 0)
            {
                return(DisplayName.CompareTo(other.DisplayName));
            }
            return(result);
        }
Exemple #26
0
        public PrincipalCollectionResult GetAllByEmailAndType(string email, PrincipalType principalType)
        {
            if (string.IsNullOrWhiteSpace(email))
            {
                throw new ArgumentException("Non-empty value expected", nameof(email));
            }

            var filter = string.Format(CommandParams.PrincipalByEmailAndType, UrlEncode(email), principalType.ToXmlString());

            return(CallPrincipalList(filter));
        }
		private async Task RunTest(
			string request_authorizationHeader,
			Type expectedExceptionType = null,
			PrincipalType? expected_principalType = null
		) {
			IAccessToken token = AccessTokenMock.Create().Object;

			IAccessTokenValidator tokenValidator = AccessTokenValidatorMock.Create(
				accessToken: ACCESS_TOKEN,
				accessTokenAfterValidation: token,
				expectedExceptionType: expectedExceptionType
			).Object;

			IRequestAuthenticator authenticator = new RequestAuthenticator( tokenValidator );

			var httpRequestMessage = new HttpRequestMessage()
				.WithAuthHeader( request_authorizationHeader );

			ID2LPrincipal principal = null;
			Exception exception = null;
			try {
				principal = await authenticator.AuthenticateAsync(
					httpRequestMessage
					).SafeAsync();
			} catch( Exception e ) {
				exception = e;
			}
			
			CheckExpectations(
				principal,
				exception,
				expectedExceptionType,
				expected_principalType );

			exception = null;

			HttpRequest httpRequest = RequestBuilder
				.Create()
				.WithAuthHeader( request_authorizationHeader );

			try {
				principal = await authenticator.AuthenticateAsync(
					httpRequest
				).SafeAsync();
			} catch( Exception e ) {
				exception = e;
			}
			
			CheckExpectations(
				principal,
				exception,
				expectedExceptionType,
				expected_principalType );
		}
Exemple #28
0
 private void AssertPrincipalTypeForClaim(PrincipalType type, string claimName)
 {
     if (m_principalType != type)
     {
         string message = string.Format(
             "Cannot access {0} for principal type: {1}",
             claimName,
             m_principalType
             );
         throw new InvalidOperationException(message);
     }
 }
Exemple #29
0
        public override int GetHashCode()
        {
            unchecked
            {
                var hashCode = PrincipalName != null?PrincipalName.GetHashCode() : 0;

                hashCode = (hashCode * 397) ^ (PrincipalType != null ? PrincipalType.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (RightName != null ? RightName.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (AceType != null ? AceType.GetHashCode() : 0);
                return(hashCode);
            }
        }
Exemple #30
0
        public StatusInfo AddToGroupByType(string principalId, PrincipalType type)
        {
            if (string.IsNullOrWhiteSpace(principalId))
            {
                throw new ArgumentException("Non-empty value expected", nameof(principalId));
            }

            var groups = GetGroupsByType(type);
            var group  = groups.Values?.FirstOrDefault();

            return(group != null?AddToGroup(principalId, group.PrincipalId) : groups.Status);
        }
        public MiddlerMapRuleEnhancer AddPermission(string principalName, PrincipalType type, AccessMode accessMode,
                                                    string client = null, string sourceAddress = null)
        {
            var entry = new MiddlerRulePermission();

            entry.PrincipalName = principalName;
            entry.Type          = type;
            entry.AccessMode    = accessMode;
            entry.Client        = client;
            entry.SourceAddress = sourceAddress;
            MiddlerRule.Permissions.Add(entry);
            return(this);
        }
        /// <summary>
        /// Assign the specified record to a new owner (user or team).
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.assignrequest(v=crm.8).aspx
        /// </para>
        /// </summary>
        /// <param name="assigneeType">
        /// <see cref="PrincipalType"/>
        /// </param>
        /// <param name="assigneeId"></param>
        /// <param name="targetEntityLogicalName"></param>
        /// <param name="targetId"></param>
        public void Assign(PrincipalType assigneeType, Guid assigneeId, string targetEntityLogicalName, Guid targetId)
        {
            ExceptionThrow.IfGuidEmpty(assigneeId, "assigneeId");
            ExceptionThrow.IfGuidEmpty(targetId, "targetId");
            ExceptionThrow.IfNullOrEmpty(targetEntityLogicalName, "targetEntityLogicalName");

            Entity entity = new Entity(targetEntityLogicalName.Trim());

            entity.Id         = targetId;
            entity["ownerid"] = new EntityReference(assigneeType.Description(), assigneeId);

            this.OrganizationService.Update(entity);
        }
        /// <summary>
        /// Reassign all records that are owned by the security principal (user or team) to another security principal (user or team).
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.reassignobjectsownerrequest(v=crm.7).aspx
        /// </para>
        /// </summary>
        /// <param name="fromPrincipalType"></param>
        /// <param name="fromPrincipalId"></param>
        /// <param name="toPrincipalType"></param>
        /// <param name="toPrincipalId"></param>
        /// <returns>
        /// <see cref="ReassignObjectsOwnerResponse"/>
        /// </returns>
        public ReassignObjectsOwnerResponse ReassignOwnership(PrincipalType fromPrincipalType, Guid fromPrincipalId, PrincipalType toPrincipalType, Guid toPrincipalId)
        {
            ExceptionThrow.IfGuidEmpty(fromPrincipalId, "fromPrincipalId");
            ExceptionThrow.IfGuidEmpty(toPrincipalId, "toPrincipalId");

            ReassignObjectsOwnerRequest request = new ReassignObjectsOwnerRequest()
            {
                FromPrincipal = new EntityReference(fromPrincipalType.Description(), fromPrincipalId),
                ToPrincipal   = new EntityReference(toPrincipalType.Description(), toPrincipalId)
            };

            return((ReassignObjectsOwnerResponse)this.OrganizationService.Execute(request));
        }
Exemple #34
0
        /// <summary>
        /// Re-assign all records that are owned by a given user to another user or team.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.reassignobjectssystemuserrequest(v=crm.8).aspx
        /// </para>
        /// </summary>
        /// <param name="id"><c>System User</c> Id</param>
        /// <param name="assignedToPrincipalType">Assigned to <c>principal</c> <see cref="PrincipalType"/></param>
        /// <param name="assignedToId">Assigned to <c>principal</c> Id</param>
        /// <returns><see cref="ReassignObjectsSystemUserResponse"/></returns>
        public ReassignObjectsSystemUserResponse ReAssignOwnedObjects(Guid id, PrincipalType assignedToPrincipalType, Guid assignedToId)
        {
            ExceptionThrow.IfGuidEmpty(id, "id");
            ExceptionThrow.IfGuidEmpty(assignedToId, "assignedToId");

            ReassignObjectsSystemUserRequest request = new ReassignObjectsSystemUserRequest()
            {
                UserId            = id,
                ReassignPrincipal = new EntityReference(assignedToPrincipalType.Description(), assignedToId)
            };

            return((ReassignObjectsSystemUserResponse)this.OrganizationService.Execute(request));
        }
 public void Read(TProtocol iprot)
 {
     TField field;
     iprot.ReadStructBegin();
     while (true)
     {
         field = iprot.ReadFieldBegin();
         if (field.Type == TType.Stop)
         {
             break;
         }
         switch (field.ID)
         {
             case 1:
                 if (field.Type == TType.String)
                 {
                     Principal_name = iprot.ReadString();
                 }
                 else
                 {
                     TProtocolUtil.Skip(iprot, field.Type);
                 }
                 break;
             case 2:
                 if (field.Type == TType.I32)
                 {
                     Principal_type = (PrincipalType)iprot.ReadI32();
                 }
                 else
                 {
                     TProtocolUtil.Skip(iprot, field.Type);
                 }
                 break;
             default:
                 TProtocolUtil.Skip(iprot, field.Type);
                 break;
         }
         iprot.ReadFieldEnd();
     }
     iprot.ReadStructEnd();
 }
 public void Read(TProtocol iprot)
 {
     TField field;
       iprot.ReadStructBegin();
       while (true)
       {
     field = iprot.ReadFieldBegin();
     if (field.Type == TType.Stop) {
       break;
     }
     switch (field.ID)
     {
       case 1:
     if (field.Type == TType.Struct) {
       HiveObject = new HiveObjectRef();
       HiveObject.Read(iprot);
     } else {
       TProtocolUtil.Skip(iprot, field.Type);
     }
     break;
       case 2:
     if (field.Type == TType.String) {
       PrincipalName = iprot.ReadString();
     } else {
       TProtocolUtil.Skip(iprot, field.Type);
     }
     break;
       case 3:
     if (field.Type == TType.I32) {
       PrincipalType = (PrincipalType)iprot.ReadI32();
     } else {
       TProtocolUtil.Skip(iprot, field.Type);
     }
     break;
       case 4:
     if (field.Type == TType.Struct) {
       GrantInfo = new PrivilegeGrantInfo();
       GrantInfo.Read(iprot);
     } else {
       TProtocolUtil.Skip(iprot, field.Type);
     }
     break;
       default:
     TProtocolUtil.Skip(iprot, field.Type);
     break;
     }
     iprot.ReadFieldEnd();
       }
       iprot.ReadStructEnd();
 }
 public void send_revoke_role(string role_name, string principal_name, PrincipalType principal_type)
 {
     oprot_.WriteMessageBegin(new TMessage("revoke_role", TMessageType.Call, seqid_));
     revoke_role_args args = new revoke_role_args();
     args.Role_name = role_name;
     args.Principal_name = principal_name;
     args.Principal_type = principal_type;
     args.Write(oprot_);
     oprot_.WriteMessageEnd();
     oprot_.Transport.Flush();
 }
 public void send_list_roles(string principal_name, PrincipalType principal_type)
 {
     oprot_.WriteMessageBegin(new TMessage("list_roles", TMessageType.Call, seqid_));
     list_roles_args args = new list_roles_args();
     args.Principal_name = principal_name;
     args.Principal_type = principal_type;
     args.Write(oprot_);
     oprot_.WriteMessageEnd();
     oprot_.Transport.Flush();
 }
 public void send_list_privileges(string principal_name, PrincipalType principal_type, HiveObjectRef hiveObject)
 {
     oprot_.WriteMessageBegin(new TMessage("list_privileges", TMessageType.Call, seqid_));
     list_privileges_args args = new list_privileges_args();
     args.Principal_name = principal_name;
     args.Principal_type = principal_type;
     args.HiveObject = hiveObject;
     args.Write(oprot_);
     oprot_.WriteMessageEnd();
     oprot_.Transport.Flush();
 }
 public void send_grant_role(string role_name, string principal_name, PrincipalType principal_type, string grantor, PrincipalType grantorType, bool grant_option)
 {
     oprot_.WriteMessageBegin(new TMessage("grant_role", TMessageType.Call, seqid_));
     grant_role_args args = new grant_role_args();
     args.Role_name = role_name;
     args.Principal_name = principal_name;
     args.Principal_type = principal_type;
     args.Grantor = grantor;
     args.GrantorType = grantorType;
     args.Grant_option = grant_option;
     args.Write(oprot_);
     oprot_.WriteMessageEnd();
     oprot_.Transport.Flush();
 }
 public bool revoke_role(string role_name, string principal_name, PrincipalType principal_type)
 {
     send_revoke_role(role_name, principal_name, principal_type);
     return recv_revoke_role();
 }
 public List<Role> list_roles(string principal_name, PrincipalType principal_type)
 {
     send_list_roles(principal_name, principal_type);
     return recv_list_roles();
 }
 public List<HiveObjectPrivilege> list_privileges(string principal_name, PrincipalType principal_type, HiveObjectRef hiveObject)
 {
     send_list_privileges(principal_name, principal_type, hiveObject);
     return recv_list_privileges();
 }
 public bool grant_role(string role_name, string principal_name, PrincipalType principal_type, string grantor, PrincipalType grantorType, bool grant_option)
 {
     send_grant_role(role_name, principal_name, principal_type, grantor, grantorType, grant_option);
     return recv_grant_role();
 }
		private async Task RunTest(
			string request_xsrfHeader,
			string request_d2lApiCookie,
			string request_authorizationHeader,
			string accessToken_xsrfClaim,
			AuthenticationMode authMode,
			Type expectedExceptionType = null,
			PrincipalType? expected_principalType = null
		) {

			IAccessToken token = AccessTokenMock.Create(
				xsrfClaim: accessToken_xsrfClaim
			).Object;

			IAccessTokenValidator tokenValidator = AccessTokenValidatorMock.Create(
				accessToken: ACCESS_TOKEN,
				accessTokenAfterValidation: token,
				expectedExceptionType: expectedExceptionType
			).Object;

			IRequestAuthenticator authenticator = new RequestAuthenticator( tokenValidator );

			var httpRequestMessage = new HttpRequestMessage()
				.WithAuthHeader( request_authorizationHeader )
				.WithXsrfHeader( request_xsrfHeader )
				.WithCookie( RequestValidationConstants.D2L_AUTH_COOKIE_NAME, request_d2lApiCookie );

			ID2LPrincipal principal = null;
			Exception exception = null;
			try {
				principal = await authenticator.AuthenticateAsync(
					httpRequestMessage,
					authMode: authMode
					).SafeAsync();
			} catch( Exception e ) {
				exception = e;
			}
			
			CheckExpectations(
				principal,
				exception,
				expectedExceptionType,
				expected_principalType );

			exception = null;

			HttpRequest httpRequest = RequestBuilder.Create()
				.WithAuthHeader( request_authorizationHeader )
				.WithXsrfHeader( request_xsrfHeader )
				.WithCookie( RequestValidationConstants.D2L_AUTH_COOKIE_NAME, request_d2lApiCookie );

			try {
				principal = await authenticator.AuthenticateAsync(
					httpRequest,
					authMode: authMode
					).SafeAsync();
			} catch( Exception e ) {
				exception = e;
			}
			
			CheckExpectations(
				principal,
				exception,
				expectedExceptionType,
				expected_principalType );
		}
		private void AssertPrincipalTypeForClaim( PrincipalType type, string claimName ) {
			if ( m_principalType != type ) {
				string message = string.Format(
					"Cannot access {0} for principal type: {1}",
					claimName,
					m_principalType
				);
				throw new InvalidOperationException( message );
			}
		}
		private void CheckExpectations(
			ID2LPrincipal principal,
			Exception exception,
			Type expectedExceptionType,
			PrincipalType? expected_principalType
		) {
			if( expectedExceptionType != null ) {
				Assert.IsNull( principal );
				Assert.IsNotNull( exception );
				Assert.AreEqual( expectedExceptionType, exception.GetType() );
				return;
			}

			Assert.IsNotNull( principal );
			Assert.IsNull( exception );

			if( expected_principalType.HasValue ) {
				Assert.AreEqual( expected_principalType, principal.Type );
			}
		}