Exemple #1
0
 public Task PushPage(Page page, FreshBasePageModel model, bool modal = false,
                      bool animate = true)
 {
     return(modal
         ? Navigation.PushModalAsync(CreateContainerPageSafe(page))
         : NavigationDetail.PushAsync(page, animate));
 }
Exemple #2
0
        /// <summary>
        /// Order entities according to principal self navigation count ascendingly
        /// for defining state appropriately.
        /// </summary>
        /// <example>
        /// firstCategory which has null value on ParentCategory property has 0 principal self
        /// navigation count. If ParentCategory of secondCategory is firstCategory, then secondCategory
        /// has 1 principal self navigation count, if ParentCategory of thirdCateogry is secondCategory,
        /// then it has 2 principal self navigaiton count. In this case, state of enitites must be defined
        /// in ascending order. In our example, the order is like below:
        /// 1. firstCategory, 2. secondCategory, 3. thirdCateogry.
        /// </example>
        /// <exception cref="ArgumentNullException">
        /// When entityCollection is null.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// When entities in collection do not have same type.
        /// </exception>
        /// <param name="entityCollection">EntityCollection to define state define order.</param>
        /// <returns>Orderer entity collection suiting for defining state.</returns>
        private IEnumerable <object> DefineStateDefineOrder(IEnumerable <object> entityCollection)
        {
            if (entityCollection == null)
            {
                throw new ArgumentNullException(nameof(entityCollection));
            }

            if (!entityCollection.Any())
            {
                return(entityCollection);
            }

            // Get type of entity
            string entityTypeName = entityCollection.First().GetType().Name;

            // All entities must have same type in collection.
            if (entityCollection
                .Any(m => m != null && m.GetType().Name != entityTypeName))
            {
                throw new InvalidOperationException(string.Format(
                                                        "All entities must have same type in collection to define state define order."
                                                        + " Entity type: {0}.",
                                                        entityTypeName));
            }

            // Check if entity has navigation propert to itself. If not, then
            // there is no need to order them, otherwise order.
            IGraphEntityTypeManager entityTypeManager = GetEntityTypeManager(entityTypeName);
            NavigationDetail        navigationDetail  = entityTypeManager.GetNavigationDetail();
            bool hasPrinciplaSelfNavigationProperty   = navigationDetail
                                                        .Relations
                                                        .Any(m => m.Direction == NavigationDirection.From &&
                                                             m.PropertyTypeName == entityTypeName);

            if (!hasPrinciplaSelfNavigationProperty)
            {
                return(entityCollection);
            }

            // Initialize store for ordered entities.
            Dictionary <object, int> principalCountStore =
                new Dictionary <object, int>();

            for (int i = 0; i < entityCollection.Count(); i++)
            {
                dynamic entity             = entityCollection.ElementAt(i);
                int     principalSelfCount = CalculatePrincipalSelfNavigationCount(
                    entity, principalCountStore);
            }

            // Order according to principal slef navigation properties ascendingly.
            return(principalCountStore.OrderBy(m => m.Value).Select(m => m.Key));
        }
        public MainPage()
        {
            this.InitializeComponent();
            App.Customers.Add(new Customer()
            {
                Name = "Björn Johansson", PNr = 8912022738
            });
            App.Customers.Add(new Customer()
            {
                Name = "Fredrik Karlsson", PNr = 9202131242
            });
            App.Customers.Add(new Customer()
            {
                Name = "Amanda Andersson", PNr = 9412038234
            });
            App.Customers.Add(new Customer()
            {
                Name = "Alexander Johansson", PNr = 8205021523
            });
            App.Customers.Add(new Customer()
            {
                Name = "Alex Larsen", PNr = 6305151526
            });
            App.Customers.Add(new Customer()
            {
                Name = "Anders Larsson", PNr = 6908172592
            });
            App.Customers.Add(new Customer()
            {
                Name = "Anders Ohlsen", PNr = 7811022849
            });
            App.Customers.Add(new Customer()
            {
                Name = "Pontus Fyhrberg", PNr = 7412199572
            });



            //CustomersListView.ItemsSource = App.Customers.OrderBy(x => x.Name);
            NavigationDetail.Navigate(typeof(Startsida));

            //string appName = Windows.ApplicationModel.Package.Current.DisplayName;
        }
Exemple #4
0
        /// <summary>
        /// Calculate count of principal self navigation properties for
        /// ordering to be able to successfully define order.
        /// </summary>
        /// <remarks>
        /// If Category has principal navigation to itself named ParentCategory, we need to
        /// find count of them to be able to define order appropriately. We need to define state of
        /// them in ascending order.
        /// </remarks>
        /// <example>
        /// firstCategory which has null value on ParentCategory property has 0 principal self
        /// navigation count. If ParentCategory of secondCategory is firstCategory, then secondCategory
        /// has 1 principal self navigation count, if ParentCategory of thirdCateogry is secondCategory,
        /// then it has 2 principal self navigaiton count.
        /// </example>
        /// <typeparam name="TEntity">Type of entity.</typeparam>
        /// <param name="entity">Entity to find principla self navigaiton count.</param>
        /// <param name="store">Store to add calculated count and check first.</param>
        /// <returns>Count of principal self navigation count.</returns>
        private int CalculatePrincipalSelfNavigationCount <TEntity>(
            TEntity entity,
            Dictionary <object, int> store)
            where TEntity : class
        {
            if (store.ContainsKey(entity))
            {
                return(store[entity]);
            }

            string typeName = entity.GetType().Name;

            // Get navigation details and find properties which is refers to itslef.
            IGraphEntityManager <TEntity> entityManager          = GetEntityManager <TEntity>();
            NavigationDetail navigationDetail                    = entityManager.GetNavigationDetail();
            List <string>    selfReferringPrincipalPropertyNames = navigationDetail
                                                                   .Relations
                                                                   .Where(m => m.Direction == NavigationDirection.From &&
                                                                          m.PropertyTypeName == typeName)
                                                                   .Select(m => m.PropertyName)
                                                                   .ToList();

            // Loop through principal navigation properties and add their count.
            int principalSelfCount = 0;

            foreach (string propertyName in selfReferringPrincipalPropertyNames)
            {
                TEntity principalEntity = entity.GetPropertyValue(propertyName) as TEntity;

                // If principla entity is null then continue
                if (principalEntity == null)
                {
                    continue;
                }

                // Othewise calculate principal count as 1 + count for principal entity
                principalSelfCount++;
                principalSelfCount += CalculatePrincipalSelfNavigationCount(principalEntity, store);
            }

            store.Add(entity, principalSelfCount);
            return(principalSelfCount);
        }
Exemple #5
0
        /// <summary>
        /// Get navigation details according to name of type
        /// </summary>
        /// <returns>Navigation details of type</returns>
        public NavigationDetail GetNavigationDetail()
        {
            // Try to get from store
            if (Store.NavigationDetail.ContainsKey(EntityTypeName))
            {
                return(Store.NavigationDetail[EntityTypeName]);
            }

            NavigationDetail navigationDetail = ContextHelper
                                                .ObjectContext
                                                .MetadataWorkspace
                                                .GetItems <EntityType>(DataSpace.CSpace)
                                                .Where(m => m.Name.Equals(EntityTypeName))
                                                .Select(n => new NavigationDetail(n))
                                                .FirstOrDefault();

            // Add to store
            Store.NavigationDetail.Add(EntityTypeName, navigationDetail);
            return(navigationDetail);
        }
 private void TextBlock_Tapped_3(object sender, TappedRoutedEventArgs e)
 {
     NavigationDetail.Navigate(typeof(Redigera));
     MySplitView.IsPaneOpen = false;
 }
 private void Registrera_Tapped_1(object sender, TappedRoutedEventArgs e)
 {
     NavigationDetail.Navigate(typeof(Registrera));
     MySplitView.IsPaneOpen = false;
 }
 private void Startsida_Tapped(object sender, TappedRoutedEventArgs e)
 {
     NavigationDetail.Navigate(typeof(Startsida));
     MySplitView.IsPaneOpen = false;
 }
Exemple #9
0
        /// <summary>
        /// Add all child or parents entities related to given entity
        /// and entity itself to the relatedEntityList.
        /// </summary>
        /// <exception cref="ArgumentNullException">
        /// When entity or relatedEntityList is null.
        /// </exception>
        /// <typeparam name="TEntity">Type of entity.</typeparam>
        /// <param name="entity">Entity to get all related entities.</param>
        /// <param name="relatedEntityList">List of entities to add.</param>
        public void GetAllEntities <TEntity>(
            TEntity entity,
            List <object> relatedEntityList)
            where TEntity : class
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }

            if (relatedEntityList == null)
            {
                throw new ArgumentNullException(nameof(relatedEntityList));
            }

            if (!relatedEntityList.Contains(entity))
            {
                relatedEntityList.Add(entity);
            }

            IGraphEntityManager <TEntity> graphEntityManager = GetEntityManager <TEntity>();
            NavigationDetail navigationDetail = graphEntityManager
                                                .GetNavigationDetail();

            List <PropertyInfo> navigationPropeties = navigationDetail
                                                      .Relations
                                                      .Select(n => entity.GetProperty(n.PropertyName))
                                                      .ToList();

            if (navigationPropeties != null &&
                navigationPropeties.Count > 0)
            {
                foreach (PropertyInfo childEntityProperty in navigationPropeties)
                {
                    if (childEntityProperty.PropertyType.IsCollectionType())
                    {
                        // If child entity is collection get all entities inside this collection.
                        IEnumerable <object> enumerableChildEntity =
                            entity.GetPropertyValue(childEntityProperty.Name) as IEnumerable <object>;

                        if (enumerableChildEntity != null)
                        {
                            for (int i = 0; i < enumerableChildEntity.Count(); i++)
                            {
                                dynamic childEntity = enumerableChildEntity.ElementAt(i);
                                if (childEntity != null &&
                                    !relatedEntityList.Contains(childEntity))
                                {
                                    GetAllEntities(
                                        childEntity,
                                        relatedEntityList);
                                }
                            }
                        }
                    }
                    else
                    {
                        // If child entity is not collection get its own.
                        dynamic childEntity = entity.GetPropertyValue(childEntityProperty.Name);

                        if (childEntity != null &&
                            !relatedEntityList.Contains(childEntity))
                        {
                            GetAllEntities(
                                childEntity,
                                relatedEntityList);
                        }
                    }
                }
            }
        }
Exemple #10
0
        /// <summary>
        /// Set property of parent entity to targetValue
        /// which has property value equals to currentValue.
        /// </summary>
        /// <typeparam name="TEntity">Type of entity.</typeparam>
        /// <param name="currentValue">Current value of property to replace.</param>
        /// <param name="targetValue">Target value to set value of property of parent.</param>
        private void ReplaceEntitiesInParents <TEntity>(
            TEntity currentValue,
            TEntity targetValue)
            where TEntity : class
        {
            IGraphEntityManager <TEntity> graphEntityManager = GetEntityManager <TEntity>();
            NavigationDetail navigationDetailOfCurrent       = graphEntityManager
                                                               .GetNavigationDetail();

            // Get parent properties of entity.
            // Properties which have navigation property type of which
            // is type of entity. Ignore navigation properties
            // which are mutual navigation properties with entity itself.
            string typeName = currentValue.GetType().Name;
            List <NavigationDetail> parentNavigationDetails = GetNavigationDetails()
                                                              .Select(n => new NavigationDetail()
            {
                SourceTypeName = n.SourceTypeName,
                Relations      = n.Relations
                                 .Where(r => r.PropertyTypeName.Equals(typeName) &&
                                        r.SourceMultiplicity == RelationshipMultiplicity.Many &&
                                        !navigationDetailOfCurrent
                                        .Relations
                                        .Any(c => c.PropertyTypeName.Equals(n.SourceTypeName) &&
                                             c.TargetMultiplicity == r.SourceMultiplicity &&
                                             c.FromKeyNames.SequenceEqual(r.FromKeyNames) &&
                                             c.ToKeyNames.SequenceEqual(r.ToKeyNames)))
                                 .ToList()
            })
                                                              .Where(n => n.Relations != null &&
                                                                     n.Relations.Count() > 0)
                                                              .ToList();

            // Get assembly to be able to get types according to type name
            Assembly entityAssembly = currentValue.GetType().Assembly;

            if (parentNavigationDetails != null && parentNavigationDetails.Count() > 0)
            {
                foreach (NavigationDetail parentNavigation in parentNavigationDetails)
                {
                    Type parentType = entityAssembly.GetTypes()
                                      .FirstOrDefault(t => t.Name.Equals(parentNavigation.SourceTypeName));

                    // Get local set of parent
                    IEnumerable <object> localParentSet = Context
                                                          .Set(parentType)
                                                          .Local
                                                          .CastToGeneric();

                    foreach (NavigationRelation navigationRelation in parentNavigation.Relations)
                    {
                        PropertyInfo childProperty =
                            parentType.GetProperty(navigationRelation.PropertyName);

                        if (!childProperty.PropertyType.IsCollectionType())
                        {
                            // Get all parent entities which have current entity inside
                            var containerParentCollection = localParentSet
                                                            .Where(m => m.GetPropertyValue(navigationRelation.PropertyName) != null &&
                                                                   m.GetPropertyValue(navigationRelation.PropertyName).Equals(currentValue))
                                                            .ToList();

                            // If collection is empty then skip.
                            if (containerParentCollection == null ||
                                containerParentCollection.Count == 0)
                            {
                                continue;
                            }

                            foreach (var containerParent in containerParentCollection)
                            {
                                // If parent is null then skip.
                                if (containerParent == null)
                                {
                                    continue;
                                }

                                // If parent with property value of currentValue found replace values

                                /*
                                 * If duplicate entity is in the entity, state of which has already
                                 * been defined and if state of this parent entity is Unchanged or
                                 * Modified, trying to change navigation property of this parent entity
                                 * will throw InvalidOperationException with following message:
                                 * "A referential integrity constraint violation occurred:
                                 *  A primary key property that is a part of referential integrity constraint
                                 *  cannot be changed when the dependent object is Unchanged unless it is being
                                 *  set to the association's principal object. The principal object must
                                 *  be tracked and not marked for deletion."
                                 * As a workaround I am storing current state of parent entity, changing the
                                 * state to Added, then replacing duplicate entity and in the end
                                 * I set state of parent entity to stored current state.
                                 */

                                // Store current state
                                var currentState = Context.Entry(containerParent).State;
                                // Change state to added
                                Context.Entry(containerParent).State = EntityState.Added;

                                // Replace value through
                                // context.Entry(containerParent).Member(propertyName).CurrentValue
                                // because otherwise EntityFramework will not be able to track entities
                                Context.Entry(containerParent)
                                .Member(navigationRelation.PropertyName).CurrentValue = targetValue;

                                // Restore state to current state
                                Context.Entry(containerParent).State = currentState;
                            }
                        }
                    }
                }
            }
        }
Exemple #11
0
        /// <summary>
        /// Get parents of entity which contains this entity
        /// </summary>
        /// <exception cref="ArgumentNullException">
        /// When entity is null
        /// </exception>
        /// <typeparam name="TEntity">Type of entity.</typeparam>
        /// <param name="entity">Entity to get parent.</param>
        /// <param name="onlyPrincipal">Get only one-to-one parent of entity</param>
        /// <returns>Principal parent of entity.</returns>
        public IEnumerable <object> GetParents <TEntity>(
            TEntity entity,
            bool onlyPrincipal)
            where TEntity : class
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }

            string typeName = entity.GetType().Name;
            List <RelationshipMultiplicity> principalRelationshipMultiplicity =
                new List <RelationshipMultiplicity>()
            {
                RelationshipMultiplicity.One,
                RelationshipMultiplicity.ZeroOrOne
            };

            IGraphEntityTypeManager graphEntityTypeMangeer    = GetEntityTypeManager(typeName);
            NavigationDetail        navigationDetailOfCurrent = graphEntityTypeMangeer
                                                                .GetNavigationDetail();

            // Get only those parent property navigation details
            // which has navigation property to this entity
            var parentNavigationDetails = navigationDetailOfCurrent
                                          .Relations
                                          .Where(r => r.Direction == NavigationDirection.From)
                                          .Select(r =>
            {
                IGraphEntityTypeManager typeManager =
                    GetEntityTypeManager(r.PropertyTypeName);
                return(new
                {
                    SourceTypeName = r.PropertyTypeName,
                    Relation = typeManager
                               .GetNavigationDetail()
                               .Relations
                               .FirstOrDefault(pr =>
                                               pr.PropertyTypeName.Equals(typeName) &&
                                               pr.SourceMultiplicity == r.TargetMultiplicity &&
                                               pr.TargetMultiplicity == r.SourceMultiplicity &&
                                               pr.ToKeyNames.SequenceEqual(r.ToKeyNames))
                });
            })
                                          .Where(r => r.Relation != null);

            if (onlyPrincipal)
            {
                parentNavigationDetails = parentNavigationDetails
                                          .Where(r => principalRelationshipMultiplicity
                                                 .Contains(r.Relation.TargetMultiplicity));
            }

            List <string> parentPropertyNames = navigationDetailOfCurrent
                                                .Relations
                                                .Where(r => parentNavigationDetails.Any(p =>
                                                                                        p.SourceTypeName == r.PropertyTypeName &&
                                                                                        p.Relation.SourceMultiplicity == r.TargetMultiplicity &&
                                                                                        p.Relation.TargetMultiplicity == r.SourceMultiplicity &&
                                                                                        p.Relation.ToKeyNames.SequenceEqual(r.ToKeyNames)))
                                                .Select(r => r.PropertyName)
                                                .ToList();

            if (parentPropertyNames != null &&
                parentPropertyNames.Count > 0)
            {
                foreach (string propertyName in parentPropertyNames)
                {
                    object parent = entity.GetPropertyValue(propertyName);
                    if (parent != null)
                    {
                        yield return(parent);
                    }
                }
            }
        }
        /// <summary>
        /// Construct filter expression for entity.
        /// </summary>
        /// <param name="entity">Entity to construct filter expression for.</param>
        /// <param name="typeOfFilter">Type of filter expression.</param>
        /// <returns>Filter expression according to entity.</returns>
        public Expression <Func <TEntity, bool> > ConstructFilterExpression(
            TEntity entity,
            FilterType typeOfFilter)
        {
            Expression <Func <TEntity, bool> > filterExpression = null;
            IEnumerable <string> primaryKeyNames = GetPrimaryKeys();

            if (primaryKeyNames.Count() == 0)
            {
                throw new ArgumentException(string.Format(
                                                "'{0}' has no configured primary key.",
                                                typeof(TEntity).Name));
            }

            List <Expression>        equalityExpressions = new List <Expression>();
            IEnumerable <Expression> singleExpressionList;

            ParameterExpression parameterExp = Expression.Parameter(typeof(TEntity), "m");
            Expression          pkFilter     = null;
            Expression          ukFilter     = null;

            bool primaryKeysHaveDefaultValues = entity.HasDefaultValues(primaryKeyNames);

            if (!primaryKeysHaveDefaultValues &&
                typeOfFilter != FilterType.OnlyUnique)
            {
                // If primary keys do not have their default values
                // add this check to equlity expression list
                singleExpressionList = parameterExp
                                       .ConstructEqualityExpressions(
                    entity,
                    primaryKeyNames);

                pkFilter = singleExpressionList.ConstructAndChain();
            }

            if (typeOfFilter != FilterType.OnlyId &&
                (primaryKeysHaveDefaultValues ||
                 typeOfFilter != FilterType.IdOptionalUnique))
            {
                IEnumerable <PropertiesWithSource> uniqueProperties =
                    MappingStorage.Instance.UniqueProperties.Where(
                        m => m.SourceType.Equals(entity.GetType()));

                if (uniqueProperties.Count() > 0)
                {
                    foreach (PropertiesWithSource unique in uniqueProperties)
                    {
                        /*
                         ***********************************************************
                         * If any of current set of properties
                         * marked as unique is foreign key,
                         * has default value, and appropriate navigation property is not
                         * null and also origin of this foreign
                         * key has any store generated primary key then this
                         * uniqueness must be ignored.
                         * For example if PersonId (int) and DocumentType (short) has been
                         * set as composite unique in PersonDocument and
                         * if PersonId is foreign key to Person, which in its term has
                         * Primary key which is store generated and if there is no navigation
                         * property to Person from PersonDocument or PersonDocument.Person is not null
                         * then PersonId = 0 and DocumentType = 5 should not
                         * be treated as unique, because the real value of PersonId
                         * will be computed when data will be inserted.
                         ***********************************************************
                         */

                        IGraphEntityTypeManager uniqueSourceTypeManager = ContextFactory
                                                                          .GetEntityTypeManager(unique.SourceType.Name);

                        bool uniquenessMustBeIgnored = false;

                        var uniquePropertyNames = unique.Properties.Select(m => m.Name).ToList();
                        var uniqueForeignKeys   = uniqueSourceTypeManager
                                                  .GetForeignKeyDetails()
                                                  .Select(m => new
                        {
                            TargetClass = m.FromDetails.ContainerClass,
                            Keys        = m.ToDetails.Keys.Intersect(uniquePropertyNames)
                        })
                                                  .Where(m => m.Keys != null &&
                                                         m.Keys.Any());

                        NavigationDetail navigationDetailsOfCurrent = GetNavigationDetail();

                        // If unuque property is foreign key
                        if (uniqueForeignKeys != null &&
                            uniqueForeignKeys.Any())
                        {
                            foreach (var uniqueFk in uniqueForeignKeys)
                            {
                                // If foreign key has default value
                                if (uniqueFk.Keys.Any(u => entity.HasDefaultValue(u)))
                                {
                                    // Get navigation relation according to foreign key
                                    NavigationRelation navigationRelation = navigationDetailsOfCurrent
                                                                            .Relations
                                                                            .FirstOrDefault(r => r.Direction == NavigationDirection.From &&
                                                                                            r.PropertyTypeName.Equals(uniqueFk.TargetClass) &&
                                                                                            r.ToKeyNames.Intersect(uniqueFk.Keys).Any());

                                    // If corresponding navigation property is not null
                                    // or there is no such navigation property
                                    if (navigationRelation == null ||
                                        entity.GetPropertyValue(navigationRelation.PropertyName) != null)
                                    {
                                        bool foreignKeyHasStoreGeneratedPrimaryKey =
                                            uniqueFk.Keys.Any(k =>
                                        {
                                            // Get origin of foreign key and check
                                            // if it has store generated key.
                                            string foreignKeyOrigin = uniqueSourceTypeManager
                                                                      .GetOriginOfForeignKey(k);
                                            IGraphEntityTypeManager foreignKeyOriginTypeManger = ContextFactory
                                                                                                 .GetEntityTypeManager(foreignKeyOrigin);
                                            return(foreignKeyOriginTypeManger.HasStoreGeneratedKey());
                                        });

                                        // If origin of foreign key has store generated Primary key
                                        if (foreignKeyHasStoreGeneratedPrimaryKey)
                                        {
                                            uniquenessMustBeIgnored = true;
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        // If uniqueness must be ignored then skip this iteration
                        if (uniquenessMustBeIgnored)
                        {
                            continue;
                        }

                        singleExpressionList = parameterExp
                                               .ConstructEqualityExpressions(
                            entity,
                            unique.Properties
                            .Select(m => m.Name).ToList());
                        equalityExpressions.Add(singleExpressionList.ConstructAndChain());
                    }

                    if (equalityExpressions.Count > 0)
                    {
                        ukFilter = equalityExpressions.ConstructOrChain();
                    }
                }
            }

            equalityExpressions.Clear();
            if (pkFilter != null)
            {
                equalityExpressions.Add(pkFilter);
            }

            if (ukFilter != null)
            {
                equalityExpressions.Add(ukFilter);
            }

            if (equalityExpressions.Count > 0)
            {
                Expression filterBaseExpression = typeOfFilter == FilterType.IdAndUnique
                    ? equalityExpressions.ConstructAndChain()
                    : equalityExpressions.ConstructOrChain();

                filterExpression = Expression.Lambda <Func <TEntity, bool> >(
                    filterBaseExpression, parameterExp);
            }

            return(filterExpression);
        }
Exemple #13
0
 public Task PopToRoot(bool animate = true)
 {
     return(NavigationDetail.PopToRootAsync(animate));
 }
Exemple #14
0
 public Task PopPage(bool modal = false, bool animate = true)
 {
     return(modal
         ? Navigation.PopModalAsync(animate)
         : NavigationDetail.PopAsync(animate));
 }