Beispiel #1
0
        public static Expression GraphDiffConfiguration(Type entityType, string mapSuffix = "")
        {
            Type iUpdateConfigurationType = typeof(IUpdateConfiguration <>).MakeGenericType(new[] { entityType });
            Type funcType = typeof(Func <,>).MakeGenericType(new[] { iUpdateConfigurationType, typeof(object) });

            MethodInfo ownedCollectionMethod2 = typeof(UpdateConfigurationExtensions).GetMethods().Where(m => m.Name == nameof(UpdateConfigurationExtensions.OwnedCollection) && m.GetParameters().Count() == 2).First();
            MethodInfo ownedCollectionMethod3 = typeof(UpdateConfigurationExtensions).GetMethods().Where(m => m.Name == nameof(UpdateConfigurationExtensions.OwnedCollection) && m.GetParameters().Count() == 3).First();

            var entity = Expression.Parameter(entityType, "entity");
            var compositionProperties = RelationshipHelper.GetAllCompositionAndAggregationRelationshipPropertyIncludes(true, entityType).Where(p => !p.Contains("."));

            if (compositionProperties.Count() > 0)
            {
                var map = Expression.Parameter(iUpdateConfigurationType, "map" + mapSuffix);
                MethodCallExpression ownedExpression = null;

                foreach (var compositionProperty in compositionProperties)
                {
                    var collectionProperty = Expression.PropertyOrField(entity, compositionProperty);
                    var collectionItemType = entityType.GetProperty(compositionProperty).PropertyType.GetGenericArguments().First();

                    Type iCollectionType    = typeof(ICollection <>).MakeGenericType(new[] { collectionItemType });
                    Type funcTypeExpression = typeof(Func <,>).MakeGenericType(new[] { entityType, iCollectionType });

                    var lambdaExpression = (Expression)typeof(LamdaHelper).GetMethod(nameof(Lambda)).MakeGenericMethod(funcTypeExpression).Invoke(null, new object[] { collectionProperty, new ParameterExpression[] { entity } });

                    MethodInfo ownedCollectionMethod2Generic = ownedCollectionMethod2.MakeGenericMethod(entityType, collectionItemType);
                    MethodInfo ownedCollectionMethod3Generic = ownedCollectionMethod3.MakeGenericMethod(entityType, collectionItemType);

                    var collectionPropertyconfiguration = GraphDiffConfiguration(collectionItemType, mapSuffix + compositionProperty);

                    if (collectionPropertyconfiguration == null)
                    {
                        if (ownedExpression == null)
                        {
                            ownedExpression = Expression.Call(ownedCollectionMethod2Generic, map, lambdaExpression);
                        }
                        else
                        {
                            ownedExpression = Expression.Call(ownedCollectionMethod2Generic, ownedExpression, lambdaExpression);
                        }
                    }
                    else
                    {
                        if (ownedExpression == null)
                        {
                            ownedExpression = Expression.Call(ownedCollectionMethod3Generic, map, lambdaExpression, collectionPropertyconfiguration);
                        }
                        else
                        {
                            ownedExpression = Expression.Call(ownedCollectionMethod3Generic, ownedExpression, lambdaExpression, collectionPropertyconfiguration);
                        }
                    }
                }

                return((Expression)typeof(LamdaHelper).GetMethod(nameof(Lambda)).MakeGenericMethod(funcType).Invoke(null, new object[] { ownedExpression, new ParameterExpression[] { map } }));
            }

            return(null);
        }
        public virtual async Task <(TDto Dto, int TotalCount)> GetByIdWithPagedCollectionPropertyAsync(CancellationToken cancellationToken,
                                                                                                       object id,
                                                                                                       string collectionExpression,
                                                                                                       string search           = "",
                                                                                                       LambdaExpression filter = null,
                                                                                                       string orderBy          = null,
                                                                                                       int?pageNo   = null,
                                                                                                       int?pageSize = null)
        {
            int?skip = null;

            if (pageNo.HasValue && pageSize.HasValue)
            {
                skip = (pageNo.Value - 1) * pageSize.Value;
            }

            await AuthorizeResourceOperationAsync(ResourceCollectionsCore.CRUD.Operations.Read, ResourceCollectionsCore.CRUD.Operations.ReadOwner);

            var collectionItemType       = RelationshipHelper.GetCollectionExpressionType(collectionExpression, typeof(TDto));
            var collectionItemMappedType = Mapper.ConfigurationProvider.GetAllTypeMaps().First(m => m.DestinationType == collectionItemType).SourceType;
            var filterConverted          = MapWhereClause(collectionItemType, collectionItemMappedType, filter);

            var bo = await Repository.GetByIdWithPagedCollectionPropertyAsync(cancellationToken, id, collectionExpression, search, filterConverted, orderBy, skip, pageSize);

            await AuthorizeResourceOperationAsync(bo, ResourceCollectionsCore.CRUD.Operations.Read, ResourceCollectionsCore.CRUD.Operations.ReadOwner);

            return(Mapper.Map <TDto>(bo.Entity), bo.TotalCount);
        }
Beispiel #3
0
        private void ToEditTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            // Update the spouse Divorce date info
            if (SpousesCombobox.SelectedItem != null)
            {
                #region Perform the businless logic for updating the divorce date

                DateTime divorceDate = App.StringToDate(ToEditTextBox.Text);

                if (divorceDate == DateTime.MinValue)
                {
                    // Clear the divorce date
                    RelationshipHelper.UpdateDivorceDate(family.Current, (Person)SpousesCombobox.SelectedItem, null);
                }
                else
                {
                    RelationshipHelper.UpdateDivorceDate(family.Current, (Person)SpousesCombobox.SelectedItem, divorceDate);
                }

                // Let the collection know that it has been updated
                family.OnContentChanged();

                #endregion
            }
        }
Beispiel #4
0
        public static bool IsSpecialOperationOrSUPWithoutRelation(
            int operationId, IList <string> opTypes)
        {
            bool isSuplementaryWithNoRelatedOperations = opTypes.Contains(OperationType.SUP) &&
                                                         !RelationshipHelper.HasOperationRelatedOperations(operationId, OperationType.SUP);

            return(IsSpecialOperation(opTypes) || isSuplementaryWithNoRelatedOperations);
        }
        public virtual object GetCreateDefaultCollectionItemDto(string collectionExpression)
        {
            AuthorizeResourceOperationAsync(ResourceCollectionsCore.CRUD.Operations.Create, ResourceCollectionsCore.CRUD.Operations.Update).Wait();

            var type = RelationshipHelper.GetCollectionExpressionCreateType(collectionExpression, typeof(TUpdateDto));

            return(Activator.CreateInstance(type));
        }
Beispiel #6
0
        public virtual async Task <ActionResult> Collection(string id, string collection, int p = 1, int pageSize = 10, string orderBy = "Id desc", string search = "")
        {
            if (!RelationshipHelper.IsValidCollectionExpression(collection, typeof(TDto)))
            {
                return(HandleReadException());
            }

            if (RelationshipHelper.IsCollectionExpressionCollectionItem(collection))
            {
                return(await CollectionItemDetails(id, collection));
            }

            var cts = TaskHelper.CreateChildCancellationTokenSource(ClientDisconnectedToken());

            try
            {
                Type collectionItemType = RelationshipHelper.GetCollectionExpressionType(collection, typeof(TDto));
                var  result             = await Service.GetByIdWithPagedCollectionPropertyAsync(cts.Token, id, collection, search, UIHelper.GetFilter(collectionItemType, HttpContext.Request.Query), orderBy, p, pageSize);

                object list = RelationshipHelper.GetCollectionExpressionData(collection, typeof(TDto), result.Dto);

                var webApiPagedResponseDtoType = typeof(WebApiPagedResponseDto <>).MakeGenericType(collectionItemType);
                var response = Activator.CreateInstance(webApiPagedResponseDtoType);

                response.SetPropValue(nameof(WebApiPagedResponseDto <Object> .Page), p);
                response.SetPropValue(nameof(WebApiPagedResponseDto <Object> .PageSize), pageSize);
                response.SetPropValue(nameof(WebApiPagedResponseDto <Object> .Records), result.TotalCount);
                response.SetPropValue(nameof(WebApiPagedResponseDto <Object> .Rows), list);
                response.SetPropValue(nameof(WebApiPagedResponseDto <Object> .OrderBy), orderBy);
                response.SetPropValue(nameof(WebApiPagedResponseDto <Object> .Search), search);

                ViewBag.Search   = search;
                ViewBag.Page     = p;
                ViewBag.PageSize = pageSize;
                ViewBag.OrderBy  = orderBy;

                ViewBag.Collection = collection;
                ViewBag.Id         = id;

                //For the time being collection properties are read only. DDD states that only the Aggregate Root should get updated.
                ViewBag.DisableCreate       = true;
                ViewBag.DisableEdit         = true;
                ViewBag.DisableDelete       = true;
                ViewBag.DisableSorting      = false;
                ViewBag.DisableEntityEvents = true;
                ViewBag.DisableSearch       = false;

                ViewBag.PageTitle = Title;
                ViewBag.Admin     = Admin;

                return(View("~/Views/Bootstrap4/List.cshtml", response));
                //return View("List", response);
            }
            catch
            {
                return(HandleReadException());
            }
        }
Beispiel #7
0
        public override void Execute(UMLRelationship r, ActionMap map, List <PreFile> prefiles)
        {
            UMLClass a            = null;
            UMLClass b            = null;
            UMLClass ac           = null;
            int      defaultDetsA = 0;
            int      defaultDetsB = 0;
            PreFile  prefA;
            PreFile  prefB;
            PreRET   temp;

            RelationshipHelper.GetClasses(r, ref a, ref b, this.IsAlternate, ref defaultDetsA, ref defaultDetsB);


            if (r is UMLAssociation)
            {
                ac = ((UMLAssociation)r).AssociationClass;
            }

            prefA = PreFileHelper.GetPreFileWithClass(a, prefiles);
            prefB = PreFileHelper.GetPreFileWithClass(b, prefiles);

            if (prefA == null)
            {
                if (prefB == null)
                {
                    prefA = new PreFile();
                    prefA.Rets.Add(new PreRET());
                    prefA.Rets.Add(new PreRET());
                    prefA.Rets[0].Classes.Add(a);
                    prefA.Rets[1].Classes.Add(b);
                    prefiles.Add(prefA);

                    if (ac != null)
                    {
                        prefA.Rets.Add(new PreRET());
                        prefA.Rets[2].Classes.Add(ac);
                    }
                }
                else
                {
                    temp = new PreRET();
                    temp.Classes.Add(a);
                    prefB.Rets.Add(temp);
                }
            }
            else
            {
                if (prefB == null)
                {
                    temp = new PreRET();
                    temp.Classes.Add(b);
                    prefA.Rets.Add(temp);
                }
            }
        }
        public static async Task LoadCollectionPropertyAsync(this DbContext context, object entity, string collectionExpression, string search = "", string orderBy = null, bool ascending = false, int?skip = null, int?take = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            string collectionProperty = RelationshipHelper.GetCollectionExpressionCurrentCollection(collectionExpression, entity.GetType());
            object collectionItemId   = RelationshipHelper.GetCollectionExpressionCurrentCollectionItem(collectionExpression);

            var collectionItemType = entity.GetType().GetGenericArguments(collectionProperty).Single();

            Type iQueryableType = typeof(IQueryable <>).MakeGenericType(new[] { collectionItemType });

            var query = context.Entry(entity)
                        .Collection(collectionProperty)
                        .Query();

            if (collectionItemId != null)
            {
                var whereClause = Utilities.SearchForEntityById(collectionItemType, collectionItemId);
                typeof(LamdaHelper).GetMethod(nameof(LamdaHelper.Where)).MakeGenericMethod(collectionItemType).Invoke(null, new object[] { query, whereClause });
            }
            else
            {
                if (!string.IsNullOrEmpty(search))
                {
                    query = (IQueryable)typeof(Utilities).GetMethod(nameof(Utilities.CreateSearchQuery)).MakeGenericMethod(collectionItemType).Invoke(null, new object[] { query, search });
                }

                if (!string.IsNullOrWhiteSpace(orderBy))
                {
                    query = (IQueryable)typeof(Utilities).GetMethod(nameof(Utilities.QueryableOrderBy)).MakeGenericMethod(collectionItemType).Invoke(null, new object[] { query, orderBy, ascending });
                }

                if (skip.HasValue)
                {
                    typeof(Queryable).GetMethod(nameof(System.Linq.Queryable.Skip)).MakeGenericMethod(collectionItemType).Invoke(null, new object[] { query, skip.Value });
                }

                if (take.HasValue)
                {
                    typeof(Queryable).GetMethod(nameof(System.Linq.Queryable.Take)).MakeGenericMethod(collectionItemType).Invoke(null, new object[] { query, take.Value });
                }
            }

            await((Task)(typeof(EntityFrameworkQueryableExtensions).GetMethod(nameof(EntityFrameworkQueryableExtensions.LoadAsync)).MakeGenericMethod(collectionItemType).Invoke(null, new object[] { query, cancellationToken }))).ConfigureAwait(false);

            if (collectionItemId != null && RelationshipHelper.CollectionExpressionHasMoreCollections(collectionExpression))
            {
                var items = entity.GetPropValue(collectionProperty) as IEnumerable;
                if (items != null)
                {
                    foreach (var item in items)
                    {
                        await context.LoadCollectionPropertyAsync(item, RelationshipHelper.GetCollectionExpressionNextCollection(collectionExpression), search, orderBy, ascending, skip, take);
                    }
                }
            }
        }
        private void SpouseStatusListbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (SpouseStatusListbox.SelectedItem != null)
            {
                RelationshipHelper.UpdateSpouseStatus(family.Current, (Person)SpousesCombobox.SelectedItem, (SpouseModifier)SpouseStatusListbox.SelectedItem);

                // The ToEditTextBox is only edittable for current spouses.
                ToEditTextBox.IsEnabled = ((SpouseModifier)SpouseStatusListbox.SelectedItem == SpouseModifier.Former);
            }
            family.OnContentChanged();
        }
Beispiel #10
0
        public virtual IActionResult NewCollectionItem(string collection)
        {
            if (!RelationshipHelper.IsValidCollectionItemCreateExpression(collection, typeof(TUpdateDto)))
            {
                return(BadRequestProblem(Messages.CollectionInvalid));
            }

            var response = Service.GetCreateDefaultCollectionItemDto(collection);

            return(Ok(response));
        }
Beispiel #11
0
        private void ParentsEditListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Update the parents
            if (ParentsEditListBox.SelectedItem != null)
            {
                RelationshipHelper.ChangeParents(family, family.Current, (ParentSet)ParentsEditListBox.SelectedValue);

                // Let the collection know that it has been updated
                family.OnContentChanged();
            }
        }
Beispiel #12
0
        // GET: Relationships
        public async Task <IActionResult> Index()
        {
            if (!UserHelper.IsLoggedIn(this))
            {
                UserHelper.RequireLogin(this);
            }
            var id = UserHelper.GetSessionUserId(this);
            var theWizardsGameShopContext = _context.Relationship.Include(r => r.SenderNavigation).Include(r => r.ReceiverNavigation).Where(r => (bool)r.IsAccepted);

            ViewData["friendRequests"] = RelationshipHelper.getRequestsReceived(id, _context);
            return(View(await theWizardsGameShopContext.ToListAsync()));
        }
Beispiel #13
0
        public virtual ActionResult CreateCollectionItem(string collection)
        {
            if (!RelationshipHelper.IsValidCollectionItemCreateExpression(collection, typeof(TUpdateDto)))
            {
                return(HandleReadException());
            }

            ViewBag.Collection      = collection.Replace("/", ".");
            ViewBag.CollectionIndex = Guid.NewGuid().ToString();

            var instance = Service.GetCreateDefaultCollectionItemDto(collection);

            return(PartialView("_CreateCollectionItem", instance));
        }
Beispiel #14
0
        private void SetCompositionPropertyForeignKeysAndAudit(Object entity, string modifiedBy, DateTime dateModified)
        {
            if (entity.HasProperty(nameof(IEntity.Id)))
            {
                var id                    = entity.GetPropValue(nameof(IEntity.Id));
                var idPropertyName        = entity.GetType().Name + nameof(IEntity.Id);
                var compositionProperties = RelationshipHelper.GetAllCompositionAndAggregationRelationshipPropertyIncludes(true, entity.GetType()).Where(p => !p.Contains("."));
                foreach (var compositionProperty in compositionProperties)
                {
                    var prop       = typeof(TEntity).GetProperty(compositionProperty);
                    var collection = prop.GetValue(entity) as IEnumerable;
                    if (collection != null)
                    {
                        foreach (var item in collection)
                        {
                            if (item.HasProperty(idPropertyName))
                            {
                                item.SetPropValue(idPropertyName, id);

                                var auditable = item as IEntityAuditable;
                                if (auditable != null)
                                {
                                    bool   containsId = false;
                                    string itemId     = "";
                                    if (item.HasProperty(nameof(IEntity.Id)))
                                    {
                                        containsId = true;
                                        itemId     = item.GetPropValue(nameof(IEntity.Id)).ToString();
                                    }

                                    if (!string.IsNullOrWhiteSpace(auditable.UserCreated) || (containsId && (string.IsNullOrWhiteSpace(itemId) || itemId == "0" || itemId == Guid.Empty.ToString())))
                                    {
                                        auditable.UserCreated = modifiedBy;
                                        auditable.DateCreated = dateModified;
                                    }
                                    else
                                    {
                                        auditable.UserModified = modifiedBy;
                                        auditable.DateModified = dateModified;
                                    }
                                }
                                SetCompositionPropertyForeignKeysAndAudit(item, modifiedBy, dateModified);
                            }
                        }
                    }
                }
            }
        }
        public virtual async Task <ActionResult> CreateCollectionItem(string collection)
        {
            if (!RelationshipHelper.IsValidCollectionItemCreateExpression(collection, typeof(TUpdateDto)))
            {
                return(HandleReadException());
            }

            var cts = TaskHelper.CreateNewCancellationTokenSource();

            ViewBag.Collection      = collection.Replace("/", ".");
            ViewBag.CollectionIndex = Guid.NewGuid().ToString();

            var instance = await Service.NewCollectionItemAsync <dynamic>(collection, cts.Token);

            return(PartialView("_CreateCollectionItem", instance));
        }
Beispiel #16
0
        /// <summary>
        /// Handles adding new people and choosing the parents within the Intermediate Add section.
        /// </summary>
        private void IntermediateAddButton_Click(object sender, RoutedEventArgs e)
        {
            Person newPerson = new Person(FirstNameInputTextBox.Text, LastNameInputTextBox.Text);

            newPerson.IsLiving = (IsLivingInputCheckbox.IsChecked == null) ? true : (bool)IsLivingInputCheckbox.IsChecked;

            DateTime birthdate = App.StringToDate(BirthDateInputTextBox.Text);

            if (birthdate != DateTime.MinValue)
            {
                newPerson.BirthDate = birthdate;
            }

            newPerson.BirthPlace = BirthPlaceInputTextBox.Text;

            switch ((FamilyMemberComboBoxValue)FamilyMemberComboBox.SelectedValue)
            {
            case FamilyMemberComboBoxValue.Brother:
                newPerson.Gender = Gender.Male;
                RelationshipHelper.AddParent(family, newPerson, (ParentSet)ParentsListBox.SelectedValue);
                break;

            case FamilyMemberComboBoxValue.Sister:
                newPerson.Gender = Gender.Female;
                RelationshipHelper.AddParent(family, newPerson, (ParentSet)ParentsListBox.SelectedValue);
                break;

            case FamilyMemberComboBoxValue.Son:
                newPerson.Gender = Gender.Male;
                RelationshipHelper.AddParent(family, newPerson, (ParentSet)ParentsListBox.SelectedValue);
                break;

            case FamilyMemberComboBoxValue.Daughter:
                newPerson.Gender = Gender.Female;
                RelationshipHelper.AddParent(family, newPerson, (ParentSet)ParentsListBox.SelectedValue);
                break;
            }

            FamilyMemberComboBox.SelectedIndex = -1;
            FamilyMemberAddButton.Focus();

            // Use animation to hide the Details Add Intermediate section
            ((Storyboard)Resources["CollapseDetailsAddIntermediate"]).Begin(this);

            family.OnContentChanged(newPerson);
        }
        public static int CollectionPropertyCount(this DbContext context, object entity, string collectionExpression, string search = "")
        {
            string collectionProperty = RelationshipHelper.GetCollectionExpressionCurrentCollection(collectionExpression, entity.GetType());

            var collectionItemType = entity.GetType().GetGenericArguments(collectionProperty).Single();

            Type iQueryableType = typeof(IQueryable <>).MakeGenericType(new[] { collectionItemType });

            var query = context.Entry(entity)
                        .Collection(collectionProperty)
                        .Query();

            if (!string.IsNullOrEmpty(search))
            {
                query = (IQueryable)typeof(Utilities).GetMethod(nameof(Utilities.CreateSearchQuery)).MakeGenericMethod(collectionItemType).Invoke(null, new object[] { query, search });
            }

            return((int)(typeof(Utilities).GetMethod(nameof(Utilities.Count)).MakeGenericMethod(collectionItemType).Invoke(null, new object[] { query })));
        }
        public static async Task <int> CollectionPropertyCountAsync(this DbContext context, object entity, string collectionExpression, string search, CancellationToken cancellationToken)
        {
            string collectionProperty = RelationshipHelper.GetCollectionExpressionCurrentCollection(collectionExpression, entity.GetType());

            var collectionItemType = entity.GetType().GetGenericArguments(collectionProperty).Single();

            Type iQueryableType = typeof(IQueryable <>).MakeGenericType(new[] { collectionItemType });

            var query = context.Entry(entity)
                        .Collection(collectionProperty)
                        .Query();

            if (!string.IsNullOrEmpty(search))
            {
                query = (IQueryable)typeof(Utilities).GetMethod(nameof(Utilities.CreateSearchQuery)).MakeGenericMethod(collectionItemType).Invoke(null, new object[] { query, search });
            }

            return(await((Task <int>)(typeof(Utilities).GetMethod(nameof(Utilities.CountEFCoreAsync)).MakeGenericMethod(collectionItemType).Invoke(null, new object[] { query, cancellationToken }))).ConfigureAwait(false));
        }
Beispiel #19
0
        private async Task <ActionResult> CollectionItemDetails(string id, string collection)
        {
            if (!RelationshipHelper.IsValidCollectionExpression(collection, typeof(TDto)))
            {
                return(HandleReadException());
            }

            if (!RelationshipHelper.IsCollectionExpressionCollectionItem(collection))
            {
                return(HandleReadException());
            }

            var    cts  = TaskHelper.CreateChildCancellationTokenSource(ClientDisconnectedToken());
            Object data = null;

            try
            {
                var response = await Service.GetByIdWithPagedCollectionPropertyAsync(cts.Token, id, collection, "", null, null, null);

                var collectionItem = RelationshipHelper.GetCollectionExpressionData(collection, typeof(TDto), response.Dto);

                if (collectionItem == null)
                {
                    return(HandleReadException());
                }

                data = collectionItem;
            }
            catch
            {
                return(HandleReadException());
            }

            ViewBag.PageTitle = Title;
            ViewBag.Admin     = Admin;

            ViewBag.DisableEdit = true;
            ViewBag.Collection  = RelationshipHelper.GetCollectionExpressionWithoutCurrentCollectionItem(collection);
            ViewBag.Id          = id;

            return(View("~/Views/Bootstrap4/Details.cshtml", data));
            //return View("Details", data);
        }
Beispiel #20
0
        /// <summary>
        /// Event handler for deleting people.  Note that not all people can be deleted.  See "IsDeletable" property on the person class.
        /// </summary>

        private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            // Deleting a person requires deleting that person from their relations with other people
            // Call the relationship helper to handle delete.
            RelationshipHelper.DeletePerson(family, family.Current);

            if (family.Count > 0)
            {
                // Current person is deleted, choose someone else as the current person
                family.Current = family[0];

                family.OnContentChanged();
                SetDefaultFocus();
            }
            else
            {
                // Let the container window know that everyone has been deleted
                RaiseEvent(new RoutedEventArgs(EveryoneDeletedEvent));
            }
        }
Beispiel #21
0
        private async Task <ActionResult> CollectionItemDetails(string id, string collection)
        {
            if (!RelationshipHelper.IsValidCollectionExpression(collection, typeof(TDto)))
            {
                return(HandleReadException());
            }

            if (!RelationshipHelper.IsCollectionExpressionCollectionItem(collection))
            {
                return(HandleReadException());
            }

            var    cts  = TaskHelper.CreateChildCancellationTokenSource(ClientDisconnectedToken());
            Object data = null;

            try
            {
                var collectionItem = await Service.GetByIdChildCollectionItemAsync <dynamic>(id, collection.Substring(0, collection.LastIndexOf('\\')), collection.Substring(collection.LastIndexOf('\\')), cts.Token);

                if (collectionItem == null)
                {
                    return(HandleReadException());
                }

                data = collectionItem;
            }
            catch
            {
                return(HandleReadException());
            }

            ViewBag.PageTitle = Title;
            ViewBag.Admin     = Admin;

            ViewBag.DisableEdit = true;
            ViewBag.Collection  = RelationshipHelper.GetCollectionExpressionWithoutCurrentCollectionItem(collection);
            ViewBag.Id          = id;

            return(View("Details", data));
        }
        private async Task <IActionResult> GetCollectionItem(string id, string collection, [FromQuery] string fields)
        {
            if (!RelationshipHelper.IsValidCollectionExpression(collection, typeof(TDto)))
            {
                return(BadRequest(Messages.CollectionInvalid));
            }

            if (!RelationshipHelper.IsCollectionExpressionCollectionItem(collection))
            {
                return(BadRequest(Messages.CollectionInvalid));
            }

            var collectionItemType = RelationshipHelper.GetCollectionExpressionType(collection, typeof(TDto));

            if (!UIHelper.ValidFieldsFor(collectionItemType, fields))
            {
                return(BadRequest(Messages.FieldsInvalid));
            }

            var cts = TaskHelper.CreateChildCancellationTokenSource(ClientDisconnectedToken());

            var response = await Service.GetByIdWithPagedCollectionPropertyAsync(cts.Token, id, collection, "", null, null, null);

            var collectionItem = RelationshipHelper.GetCollectionExpressionData(collection, typeof(TDto), response.Dto);

            if (collectionItem == null)
            {
                return(NotFound());
            }

            var links = CreateLinksForCollectionItem(id, collection, fields);

            var linkedResourceToReturn = collectionItem.ShapeData(collectionItemType, fields)
                                         as IDictionary <string, object>;

            linkedResourceToReturn.Add("links", links);

            return(Ok(linkedResourceToReturn));
        }
Beispiel #23
0
        public virtual (TDto Dto, int TotalCount) GetByIdWithPagedCollectionProperty(object id,
                                                                                     string collectionExpression,
                                                                                     string search           = "",
                                                                                     LambdaExpression filter = null,
                                                                                     string orderBy          = null,
                                                                                     int?pageNo   = null,
                                                                                     int?pageSize = null)
        {
            int?skip = null;

            if (pageNo.HasValue && pageSize.HasValue)
            {
                skip = (pageNo.Value - 1) * pageSize.Value;
            }

            var collectionItemType       = RelationshipHelper.GetCollectionExpressionType(collectionExpression, typeof(TDto));
            var collectionItemMappedType = Mapper.ConfigurationProvider.GetAllTypeMaps().First(m => m.DestinationType == collectionItemType).SourceType;
            var filterConverted          = MapWhereClause(collectionItemType, collectionItemMappedType, filter);

            var bo = Repository.GetByIdWithPagedCollectionProperty(id, collectionExpression, search, filterConverted, orderBy, skip, pageSize);

            return(Mapper.Map <TDto>(bo.Entity), bo.TotalCount);
        }
        public virtual object GetCreateDefaultCollectionItemDto(string collectionExpression)
        {
            var type = RelationshipHelper.GetCollectionExpressionCreateType(collectionExpression, typeof(TUpdateDto));

            return(Activator.CreateInstance(type));
        }
        public virtual async Task<IActionResult> GetCollectionProperty(string id, string collection, WebApiPagedSearchOrderingRequestDto resourceParameters)
        {
            if (string.IsNullOrEmpty(resourceParameters.OrderBy))
                resourceParameters.OrderBy = "Id";

            if (!RelationshipHelper.IsValidCollectionExpression(collection, typeof(TDto)))
            {
                return ApiErrorMessage(Messages.CollectionInvalid);
            }

            if (RelationshipHelper.IsCollectionExpressionCollectionItem(collection))
            {
                return await GetCollectionItem(id, collection, resourceParameters.Fields);
            }

            var collectionItemType = RelationshipHelper.GetCollectionExpressionType(collection, typeof(TDto));
            if (!TypeHelperService.TypeHasProperties(collectionItemType, resourceParameters.Fields))
            {
                return ApiErrorMessage(Messages.FieldsInvalid);
            }

            var cts = TaskHelper.CreateChildCancellationTokenSource(ClientDisconnectedToken());

            var dataTask = Service.GetByIdWithPagedCollectionPropertyAsync(cts.Token, id, collection, resourceParameters.Search, resourceParameters.OrderBy, resourceParameters.OrderType == "asc" ? true : false, resourceParameters.Page.HasValue ? resourceParameters.Page - 1 : null, resourceParameters.PageSize);

            var totalTask = Service.GetByIdWithPagedCollectionPropertyCountAsync(cts.Token, id, collection, resourceParameters.Search);

            await TaskHelper.WhenAllOrException(cts, dataTask, totalTask);

            var result = dataTask.Result;

            var total = totalTask.Result;

            IEnumerable<Object> list = ((IEnumerable<Object>)RelationshipHelper.GetCollectionExpressionData(collection, typeof(TDto), result));

            var paginationMetadata = new WebApiPagedResponseDto<TDto>
            {
                Page = resourceParameters.Page.HasValue ? resourceParameters.Page.Value : 1,
                PageSize = resourceParameters.PageSize.HasValue ? resourceParameters.PageSize.Value : list.Count(),
                Records = total,
                PreviousPageLink = null,
                NextPageLink = null
            };

            if (paginationMetadata.HasPrevious)
            {
                paginationMetadata.PreviousPageLink = CreateCollectionPropertyResourceUri(collection, resourceParameters, ResourceUriType.PreviousPage);
            }

            if (paginationMetadata.HasNext)
            {
                paginationMetadata.NextPageLink = CreateCollectionPropertyResourceUri(collection, resourceParameters, ResourceUriType.NextPage);
            }

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(paginationMetadata));

            var links = CreateLinksForCollectionProperty(collection, resourceParameters, paginationMetadata.HasNext, paginationMetadata.HasPrevious);

            var shapedData = IEnumerableExtensions.ShapeData(list, collectionItemType, resourceParameters.Fields);

            var shapedDataWithLinks = shapedData.Select(collectionPropertyDtoItem =>
            {
                var collectionPropertyDtoItemAsDictionary = collectionPropertyDtoItem as IDictionary<string, object>;
                var collectionPropertyDtoItemLinks = CreateLinksForCollectionItem(id, collection + "/" + collectionPropertyDtoItemAsDictionary["Id"].ToString(), resourceParameters.Fields);

                collectionPropertyDtoItemAsDictionary.Add("links", collectionPropertyDtoItem);

                return collectionPropertyDtoItemAsDictionary;
            });

            var linkedCollectionResource = new
            {
                value = shapedDataWithLinks
                ,
                links = links
            };

            return Ok(linkedCollectionResource);
        }
Beispiel #26
0
        public virtual async Task <ActionResult> Collection(string id, string collection, int page = 1, int pageSize = 10, string orderColumn = "Id", string orderType = "desc", string search = "")
        {
            if (!RelationshipHelper.IsValidCollectionExpression(collection, typeof(TDto)))
            {
                return(HandleReadException());
            }

            if (RelationshipHelper.IsCollectionExpressionCollectionItem(collection))
            {
                return(await CollectionItemDetails(id, collection));
            }

            var cts = TaskHelper.CreateChildCancellationTokenSource(ClientDisconnectedToken());

            try
            {
                var dataTask = Service.GetByIdWithPagedCollectionPropertyAsync(cts.Token, id, collection, search, orderColumn, orderType == "asc" ? true : false, page - 1, pageSize);

                var totalTask = Service.GetByIdWithPagedCollectionPropertyCountAsync(cts.Token, id, collection, search);

                await TaskHelper.WhenAllOrException(cts, dataTask, totalTask);

                var result = dataTask.Result;

                Type   collectionItemType = RelationshipHelper.GetCollectionExpressionType(collection, typeof(TDto));
                object list = RelationshipHelper.GetCollectionExpressionData(collection, typeof(TDto), result);

                var total = totalTask.Result;

                var webApiPagedResponseDtoType = typeof(WebApiPagedResponseDto <>).MakeGenericType(collectionItemType);
                var response = Activator.CreateInstance(webApiPagedResponseDtoType);

                response.SetPropValue(nameof(WebApiPagedResponseDto <Object> .Page), page);
                response.SetPropValue(nameof(WebApiPagedResponseDto <Object> .PageSize), pageSize);
                response.SetPropValue(nameof(WebApiPagedResponseDto <Object> .Records), total);
                response.SetPropValue(nameof(WebApiPagedResponseDto <Object> .Rows), list);
                response.SetPropValue(nameof(WebApiPagedResponseDto <Object> .OrderColumn), orderColumn);
                response.SetPropValue(nameof(WebApiPagedResponseDto <Object> .OrderType), orderType);
                response.SetPropValue(nameof(WebApiPagedResponseDto <Object> .Search), search);

                ViewBag.Search      = search;
                ViewBag.Page        = page;
                ViewBag.PageSize    = pageSize;
                ViewBag.OrderColumn = orderColumn;
                ViewBag.OrderType   = orderType;

                ViewBag.Collection = collection;
                ViewBag.Id         = id;

                //For the time being collection properties are read only. DDD states that only the Aggregate Root should get updated.
                ViewBag.DisableCreate       = true;
                ViewBag.DisableEdit         = true;
                ViewBag.DisableDelete       = true;
                ViewBag.DisableSorting      = false;
                ViewBag.DisableEntityEvents = true;
                ViewBag.DisableSearch       = false;

                ViewBag.PageTitle = Title;
                ViewBag.Admin     = Admin;
                return(View("List", response));
            }
            catch
            {
                return(HandleReadException());
            }
        }
Beispiel #27
0
        private void AddExistingButton_Click(object sender, RoutedEventArgs e)
        {
            Person existingPerson = (Person)ExistingPeopleListBox.SelectedItem;

            bool SelectParent = false;
            ParentSetCollection possibleParents = family.Current.PossibleParentSets;

            // Perform the action based on the selected relationship
            switch ((FamilyMemberComboBoxValue)ExistingFamilyMemberComboBox.SelectedValue)
            {
            case FamilyMemberComboBoxValue.Father:
                existingPerson.Gender = Gender.Male;
                RelationshipHelper.AddParent(family, family.Current, existingPerson);
                SetNextFamilyMemberAction(FamilyMemberComboBoxValue.Mother);
                break;

            case FamilyMemberComboBoxValue.Mother:
                existingPerson.Gender = Gender.Female;
                RelationshipHelper.AddParent(family, family.Current, existingPerson);
                SetNextFamilyMemberAction(FamilyMemberComboBoxValue.Brother);
                break;

            case FamilyMemberComboBoxValue.Brother:
                existingPerson.Gender = Gender.Male;

                // Check to see if there are multiple parents
                if (possibleParents.Count > 1)
                {
                    SelectParent = true;
                }
                else
                {
                    RelationshipHelper.AddSibling(family, family.Current, existingPerson);
                }
                break;

            case FamilyMemberComboBoxValue.Sister:
                existingPerson.Gender = Gender.Female;

                // Check to see if there are multiple parents
                if (possibleParents.Count > 1)
                {
                    SelectParent = true;
                }
                else
                {
                    RelationshipHelper.AddSibling(family, family.Current, existingPerson);
                }
                break;

            case FamilyMemberComboBoxValue.Spouse:
                RelationshipHelper.AddSpouse(family, family.Current, existingPerson, SpouseModifier.Current);
                SetNextFamilyMemberAction(FamilyMemberComboBoxValue.Son);
                break;

            case FamilyMemberComboBoxValue.Son:
                existingPerson.Gender = Gender.Male;

                if (family.Current.Spouses.Count > 1)
                {
                    possibleParents = family.Current.MakeParentSets();
                    SelectParent    = true;
                }
                else
                {
                    RelationshipHelper.AddChild(family, family.Current, existingPerson);
                }

                break;

            case FamilyMemberComboBoxValue.Daughter:
                existingPerson.Gender = Gender.Female;
                if (family.Current.Spouses.Count > 1)
                {
                    possibleParents = family.Current.MakeParentSets();
                    SelectParent    = true;
                }
                else
                {
                    RelationshipHelper.AddChild(family, family.Current, existingPerson);
                }

                break;
            }

            if (SelectParent)
            {
                ShowDetailsAddIntermediate(possibleParents);
            }
            else
            {
                // Use animation to hide the Details Add section
                ((Storyboard)Resources["CollapseAddExisting"]).Begin(this);

                FamilyMemberComboBox.SelectedIndex = -1;
                FamilyMemberAddButton.Focus();
            }
        }
Beispiel #28
0
        public virtual async Task <ActionResult> Collection(string id, string collection, int page = 1, int pageSize = 10, string orderBy = "Id desc", string search = "")
        {
            if (!RelationshipHelper.IsValidCollectionExpression(collection, typeof(TDto)))
            {
                return(HandleReadException());
            }

            if (RelationshipHelper.IsCollectionExpressionCollectionItem(collection))
            {
                return(await CollectionItemDetails(id, collection));
            }

            var cts = TaskHelper.CreateChildCancellationTokenSource(ClientDisconnectedToken());

            try
            {
                var searchDto = new WebApiSearchQueryParamsDto()
                {
                    Page     = page,
                    PageSize = pageSize,
                    Search   = search,
                    OrderBy  = orderBy
                };

                var resp = await Service.GetByIdChildCollectionAsync <dynamic>(id, collection, searchDto, cts.Token);

                var response = new WebApiPagedResponseDto <dynamic>
                {
                    Page     = page,
                    PageSize = pageSize,
                    Records  = resp.pagingInfo.Records,
                    Rows     = resp.data.Value.ToList(),
                    OrderBy  = orderBy,
                    Search   = search
                };

                ViewBag.Search   = search;
                ViewBag.Page     = page;
                ViewBag.PageSize = pageSize;
                ViewBag.OrderBy  = orderBy;

                ViewBag.Collection = collection;
                ViewBag.Id         = id;

                //For the time being collection properties are read only. DDD states that only the Aggregate Root should get updated.
                ViewBag.DisableCreate       = true;
                ViewBag.DisableEdit         = true;
                ViewBag.DisableDelete       = true;
                ViewBag.DisableSorting      = false;
                ViewBag.DisableEntityEvents = true;
                ViewBag.DisableSearch       = false;

                ViewBag.PageTitle = Title;
                ViewBag.Admin     = Admin;
                return(View("List", response));
            }
            catch
            {
                return(HandleReadException());
            }
        }
Beispiel #29
0
        /// <summary>
        /// Handles adding new people
        /// </summary>
        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            // To make it a little more user friendly, set the next action for the family member button to be the same as the current relationship being added.
            SetNextFamilyMemberAction((FamilyMemberComboBoxValue)FamilyMemberComboBox.SelectedValue);

            // The new person to be added
            Person newPerson = new Person(FirstNameInputTextBox.Text, LastNameInputTextBox.Text)
            {
                IsLiving = (IsLivingInputCheckbox.IsChecked == null) ? true : (bool)IsLivingInputCheckbox.IsChecked
            };

            DateTime birthdate = App.StringToDate(BirthDateInputTextBox.Text);

            if (birthdate != DateTime.MinValue)
            {
                newPerson.BirthDate = birthdate;
            }

            newPerson.BirthPlace = BirthPlaceInputTextBox.Text;

            bool SelectParent = false;
            ParentSetCollection possibleParents = family.Current.PossibleParentSets;

            // Perform the action based on the selected relationship
            switch ((FamilyMemberComboBoxValue)FamilyMemberComboBox.SelectedValue)
            {
            case FamilyMemberComboBoxValue.Father:
                newPerson.Gender = Gender.Male;
                RelationshipHelper.AddParent(family, family.Current, newPerson);
                SetNextFamilyMemberAction(FamilyMemberComboBoxValue.Mother);
                break;

            case FamilyMemberComboBoxValue.Mother:
                newPerson.Gender = Gender.Female;
                RelationshipHelper.AddParent(family, family.Current, newPerson);
                SetNextFamilyMemberAction(FamilyMemberComboBoxValue.Brother);
                break;

            case FamilyMemberComboBoxValue.Brother:
                newPerson.Gender = Gender.Male;

                // Check to see if there are multiple parents
                if (possibleParents.Count > 1)
                {
                    SelectParent = true;
                }
                else
                {
                    RelationshipHelper.AddSibling(family, family.Current, newPerson);
                }

                break;

            case FamilyMemberComboBoxValue.Sister:
                newPerson.Gender = Gender.Female;

                // Check to see if there are multiple parents
                if (possibleParents.Count > 1)
                {
                    SelectParent = true;
                }
                else
                {
                    RelationshipHelper.AddSibling(family, family.Current, newPerson);
                }

                break;

            case FamilyMemberComboBoxValue.Spouse:
                RelationshipHelper.AddSpouse(family, family.Current, newPerson, SpouseModifier.Current);
                SetNextFamilyMemberAction(FamilyMemberComboBoxValue.Son);
                break;

            case FamilyMemberComboBoxValue.Son:
                newPerson.Gender = Gender.Male;

                if (family.Current.Spouses.Count > 1)
                {
                    possibleParents = family.Current.MakeParentSets();
                    SelectParent    = true;
                }
                else
                {
                    RelationshipHelper.AddChild(family, family.Current, newPerson);
                }

                break;

            case FamilyMemberComboBoxValue.Daughter:
                newPerson.Gender = Gender.Female;
                if (family.Current.Spouses.Count > 1)
                {
                    possibleParents = family.Current.MakeParentSets();
                    SelectParent    = true;
                }
                else
                {
                    RelationshipHelper.AddChild(family, family.Current, newPerson);
                }

                break;
            }

            if (SelectParent)
            {
                ShowDetailsAddIntermediate(possibleParents);
            }
            else
            {
                // Use animation to hide the Details Add section
                ((Storyboard)Resources["CollapseDetailsAdd"]).Begin(this);

                FamilyMemberComboBox.SelectedIndex = -1;
                FamilyMemberAddButton.Focus();
            }

            family.OnContentChanged(newPerson);
        }
        public virtual async Task <IActionResult> GetByIdChildCollection(string id, string collection, WebApiSearchQueryParamsDto resourceParameters)
        {
            if (string.IsNullOrEmpty(resourceParameters.OrderBy))
            {
                resourceParameters.OrderBy = "Id";
            }


            //order by
            if (!UIHelper.ValidOrderByFor <TDto>(resourceParameters.OrderBy))
            {
                return(BadRequest(Messages.OrderByInvalid));
            }

            if (!RelationshipHelper.IsValidCollectionExpression(collection, typeof(TDto)))
            {
                return(BadRequest(Messages.CollectionInvalid));
            }

            if (RelationshipHelper.IsCollectionExpressionCollectionItem(collection))
            {
                return(await GetCollectionItem(id, collection, resourceParameters.Fields));
            }

            var collectionItemType = RelationshipHelper.GetCollectionExpressionType(collection, typeof(TDto));

            //fields
            if (!UIHelper.ValidFieldsFor(collectionItemType, resourceParameters.Fields))
            {
                return(BadRequest(Messages.FieldsInvalid));
            }

            //filter
            if (!UIHelper.ValidFilterFor(collectionItemType, HttpContext.Request.Query))
            {
                return(BadRequest(Messages.FiltersInvalid));
            }

            var filter = UIHelper.GetFilter(collectionItemType, HttpContext.Request.Query);

            var cts = TaskHelper.CreateChildCancellationTokenSource(ClientDisconnectedToken());

            var result = await Service.GetByIdWithPagedCollectionPropertyAsync(cts.Token, id, collection, resourceParameters.Search, filter, resourceParameters.OrderBy, resourceParameters.Page, resourceParameters.PageSize);

            IEnumerable <Object> list = ((IEnumerable <Object>)RelationshipHelper.GetCollectionExpressionData(collection, typeof(TDto), result.Dto));

            var paginationMetadata = new PagingInfoDto
            {
                Page             = resourceParameters.Page,
                PageSize         = resourceParameters.PageSize,
                Records          = result.TotalCount,
                PreviousPageLink = null,
                NextPageLink     = null
            };

            if (paginationMetadata.HasPrevious)
            {
                paginationMetadata.PreviousPageLink = CreateCollectionPropertyResourceUri(collection, resourceParameters, ResourceUriType.PreviousPage);
            }

            if (paginationMetadata.HasNext)
            {
                paginationMetadata.NextPageLink = CreateCollectionPropertyResourceUri(collection, resourceParameters, ResourceUriType.NextPage);
            }

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(paginationMetadata).Replace(Environment.NewLine, ""));

            var links = CreateLinksForCollectionProperty(collection, resourceParameters, paginationMetadata.HasNext, paginationMetadata.HasPrevious);

            var shapedData = UIHelper.ShapeListData(list, collectionItemType, resourceParameters.Fields);

            var shapedDataWithLinks = shapedData.Select(collectionPropertyDtoItem =>
            {
                var collectionPropertyDtoItemAsDictionary = collectionPropertyDtoItem as IDictionary <string, object>;
                var collectionPropertyDtoItemLinks        = CreateLinksForCollectionItem(id, collection + "/" + collectionPropertyDtoItemAsDictionary["Id"].ToString(), resourceParameters.Fields);

                collectionPropertyDtoItemAsDictionary.Add("links", collectionPropertyDtoItem);

                return(collectionPropertyDtoItemAsDictionary);
            }).ToList();

            var linkedCollectionResource = new WebApiListResponseDto <IDictionary <string, object> >
            {
                Value = shapedDataWithLinks
                ,
                Links = links
            };

            return(Ok(linkedCollectionResource));
        }