Exemple #1
0
        /// <summary>
        /// Add a group of interdependent properties (i.e. if one of them changes, all of them change)
        /// </summary>
        /// <typeparam name="Type">The type</typeparam>
        /// <param name="propertyNamesDest">The list of property names</param>
        protected static void AddDependencyGroup <Type>(params string[] propertyNamesDest)
        {
            var type = typeof(Type);

            if (!ValidatePublicPropertyNames(type, propertyNamesDest))
            {
                throw new ArgumentException("A destination property is not a property of the given type", "propertyNamesDest");
            }

            if (!DependentProperties.ContainsKey(type))
            {
                DependentProperties[type] = new Dictionary <string, List <string> >();
            }

            foreach (var propertyNameSource in propertyNamesDest)
            {
                if (!DependentProperties[type].ContainsKey(propertyNameSource))
                {
                    DependentProperties[type][propertyNameSource] = new List <string>();
                }

                foreach (var name in propertyNamesDest)
                {
                    if (name == propertyNameSource)
                    {
                        continue;
                    }
                    if (DependentProperties[type][propertyNameSource].Any(item => item == name))
                    {
                        continue;
                    }
                    DependentProperties[type][propertyNameSource].Add(name);
                }
            }
        }
Exemple #2
0
 /// <summary>
 /// Constructs the object; remembers the callers' type for looking up dependent properties
 /// efficiently
 /// </summary>
 /// <param name="callerType">The callers (i.e. derived class) type</param>
 protected NotifyPropertyChangedImpl(Type callerType)
 {
     if (DependentProperties.ContainsKey(callerType))
     {
         CallerType = callerType;
     }
 }
Exemple #3
0
        public IEnumerable <ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule()
            {
                ErrorMessage   = FormatErrorMessage(metadata.GetDisplayName()),
                ValidationType = "requiredifany",
            };

            var properties = new List <string>();
            var values     = new List <object>();

            for (int i = 0; i < DependentProperties.Count(); i++)
            {
                string depProp = BuildDependentPropertyId(metadata, context as ViewContext, DependentProperties[i]);

                // find the value on the control we depend on;
                // if it's a bool, format it javascript style
                // (the default is True or False!)
                string targetValue = (TargetValues[i] ?? "").ToString();
                if (TargetValues[i].GetType() == typeof(bool))
                {
                    targetValue = targetValue.ToLower();
                }

                properties.Add(depProp);
                values.Add(targetValue);
            }

            rule.ValidationParameters.Add("dependentproperties", String.Join("|", properties));
            rule.ValidationParameters.Add("targetvalues", String.Join("|", values));

            yield return(rule);
        }
Exemple #4
0
 /// <summary>
 /// Manages a property modification and its notifications. A function is provided to check whether the new value is different from the current one.
 /// This function will be invoked by this method, and if it returns <c>True</c>, it will invoke the provided update action. The <see cref="ViewModelBase.PropertyChanging"/>
 /// event will be raised prior to the update action, and the <see cref="ViewModelBase.PropertyChanged"/> event will be raised after.
 /// </summary>
 /// <remarks>This method does not register <see cref="IActionItem"/> into the associated <see cref="ITransactionalActionStack"/>.</remarks>
 /// <param name="hasChangedFunction">A function that check if the new value is different and therefore if the update must be actually done.</param>
 /// <param name="updateAction">The update action that will actually manage the update of the property.</param>
 /// <param name="propertyNames">The names of the properties that must be notified as changing/changed. At least one property name must be provided.</param>
 /// <returns><c>True</c> if the update was done and events were raised, <c>False</c> if <see cref="hasChangedFunction"/> is not <c>null</c> and returned false.</returns>
 protected virtual bool SetValueUncancellable(Func <bool> hasChangedFunction, Action updateAction, params string[] propertyNames)
 {
     foreach (var propertyName in propertyNames)
     {
         uncancellableChanges.Add(propertyName);
         string[] dependentProperties;
         if (DependentProperties.TryGetValue(propertyName, out dependentProperties))
         {
             dependentProperties.ForEach(x => uncancellableChanges.Add(x));
         }
     }
     try
     {
         var result = SetValue(hasChangedFunction, updateAction, propertyNames);
         return(result);
     }
     finally
     {
         foreach (var propertyName in propertyNames)
         {
             uncancellableChanges.Remove(propertyName);
             string[] dependentProperties;
             if (DependentProperties.TryGetValue(propertyName, out dependentProperties))
             {
                 dependentProperties.ForEach(x => uncancellableChanges.Remove(x));
             }
         }
     }
 }
Exemple #5
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            for (int i = 0; i < DependentProperties.Count(); i++)
            {
                // get a reference to the property this validation depends upon
                var containerType = validationContext.ObjectInstance.GetType();
                var field         = containerType.GetProperty(this.DependentProperties[i]);

                if (field != null)
                {
                    // get the value of the dependent property
                    var dependentvalue = field.GetValue(validationContext.ObjectInstance, null);

                    // compare the value against the target value
                    if ((dependentvalue == null && this.TargetValues[i] == null) ||
                        (dependentvalue != null && dependentvalue.Equals(this.TargetValues[i])))
                    {
                        // match => means we should try validating this field
                        if (!_innerAttribute.IsValid(value))
                        {
                            // validation failed - return an error
                            return(new ValidationResult(this.ErrorMessage, new[] { validationContext.MemberName }));
                        }
                    }
                }
            }

            return(ValidationResult.Success);
        }
 protected bool SetValueUncancellable <T>(ref T field, T value, Action updateAction, [ItemNotNull, NotNull] params string[] propertyNames)
 {
     foreach (var propertyName in propertyNames)
     {
         uncancellableChanges.Add(propertyName);
         string[] dependentProperties;
         if (DependentProperties.TryGetValue(propertyName, out dependentProperties))
         {
             dependentProperties.ForEach(x => uncancellableChanges.Add(x));
         }
     }
     try
     {
         var result = SetValue(ref field, value, updateAction, false, propertyNames);
         return(result);
     }
     finally
     {
         foreach (var propertyName in propertyNames)
         {
             uncancellableChanges.Remove(propertyName);
             string[] dependentProperties;
             if (DependentProperties.TryGetValue(propertyName, out dependentProperties))
             {
                 dependentProperties.ForEach(x => uncancellableChanges.Remove(x));
             }
         }
     }
 }
Exemple #7
0
        protected ControlPointViewModelBase([NotNull] CurveViewModelBase curve)
            : base(curve.SafeArgument(nameof(curve)).ServiceProvider)
        {
            Curve = curve;

            DependentProperties.Add(nameof(Point), new[] { nameof(ActualKey), nameof(ActualPoint), nameof(ActualValue) });
        }
Exemple #8
0
        protected CombinedObservableNode(ObservableViewModel ownerViewModel, string name, IEnumerable <SingleObservableNode> combinedNodes, Index index)
            : base(ownerViewModel, index)
        {
            // ReSharper disable once DoNotCallOverridableMethodsInConstructor
            DependentProperties.Add(nameof(Value), new[] { nameof(HasMultipleValues), nameof(IsPrimitive), nameof(HasList), nameof(HasDictionary) });
            this.combinedNodes = new List <SingleObservableNode>(combinedNodes);
            Name        = name;
            DisplayName = this.combinedNodes.First().DisplayName;

            combinedNodeInitialValues         = new List <object>();
            distinctCombinedNodeInitialValues = new HashSet <object>();

            bool isReadOnly = false;
            bool isVisible  = false;
            bool nullOrder  = false;

            foreach (var node in this.combinedNodes)
            {
                if (node.IsDisposed)
                {
                    throw new InvalidOperationException("One of the combined node is already disposed.");
                }

                if (node.IsReadOnly)
                {
                    isReadOnly = true;
                }

                if (node.IsVisible)
                {
                    isVisible = true;
                }

                if (node.Order == null)
                {
                    nullOrder = true;
                }

                if (order == node.Order || (!nullOrder && order == null))
                {
                    order = node.Order;
                }

                combinedNodeInitialValues.Add(node.Value);
                distinctCombinedNodeInitialValues.Add(node.Value);
            }
            IsReadOnly = isReadOnly;
            IsVisible  = isVisible;

            ResetInitialValues = new AnonymousCommand(ServiceProvider, () =>
            {
                using (Owner.BeginCombinedAction(Owner.FormatCombinedUpdateMessage(this, null), Path))
                {
                    CombinedNodes.Zip(combinedNodeInitialValues).ForEach(x => x.Item1.Value = x.Item2);
                    Refresh();
                }
            });
        }
 protected DirectoryBaseViewModel(SessionViewModel session)
     : base(session)
 {
     SubDirectories = new ReadOnlyObservableCollection <DirectoryViewModel>(subDirectories);
     // ReSharper disable DoNotCallOverridableMethodsInConstructor - looks like an issue in resharper
     DependentProperties.Add(nameof(Parent), new[] { nameof(Path), nameof(Package), nameof(Root) });
     // ReSharper restore DoNotCallOverridableMethodsInConstructor
     RegisterMemberCollectionForActionStack(nameof(Assets), Assets);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="SolutionPlatformViewModel"/> class.
 /// </summary>
 /// <param name="serviceProvider">The service provider for this view model.</param>
 /// <param name="solutionPlatform">The solution platform represented by the view model.</param>
 /// <param name="isAlreadyInstalled">Indicates whether this plaform is already installed in the related package.</param>
 /// <param name="initiallySelected">Indicates whether this plaform should be initially selected.</param>
 public SolutionPlatformViewModel(IViewModelServiceProvider serviceProvider, SolutionPlatform solutionPlatform, bool isAlreadyInstalled, bool initiallySelected)
     : base(serviceProvider)
 {
     SolutionPlatform     = solutionPlatform;
     IsAvailableOnMachine = solutionPlatform.IsAvailable;
     IsSelected           = initiallySelected;
     IsAlreadyInstalled   = isAlreadyInstalled;
     DependentProperties.Add(nameof(IsSelected), new[] { nameof(MarkedToRemove) });
     SelectedTemplate = AvailableTemplates.FirstOrDefault();
 }
Exemple #11
0
 protected NodeViewModel(GraphViewModel ownerViewModel, Index index)
     : base(ownerViewModel.ServiceProvider)
 {
     DependentProperties.Add(nameof(Path), new[] { nameof(DisplayPath) });
     Owner      = ownerViewModel;
     Index      = index;
     Guid       = Guid.NewGuid();
     IsVisible  = true;
     IsReadOnly = false;
 }
        protected EntityHierarchyElementViewModel([NotNull] EntityHierarchyEditorViewModel editor, [NotNull] EntityHierarchyViewModel asset, [NotNull] IEnumerable <EntityDesign> childEntities, object assetSideInstance)
            : base(editor, asset, childEntities)
        {
            this.assetSideInstance = assetSideInstance;
            LoadCommand            = new AnonymousTaskCommand <bool>(ServiceProvider, recursive => RequestLoading(!IsLoaded, recursive));
            LockCommand            = new AnonymousTaskCommand <bool>(ServiceProvider, recursive => RequestLocking(!IsLocked, recursive));

            DependentProperties.Add(nameof(IsLoaded), new[] { nameof(IsSelectable) });
            DependentProperties.Add(nameof(IsLocked), new[] { nameof(IsSelectable) });
        }
 public TemplateDescriptionGroupViewModel(IViewModelServiceProvider serviceProvider, string name)
     : base(serviceProvider)
 {
     if (name == null)
     {
         throw new ArgumentNullException(nameof(name));
     }
     Name      = name;
     Templates = new ObservableList <ITemplateDescriptionViewModel>();
     DependentProperties.Add(nameof(Parent), new[] { nameof(Path) });
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="ViewportViewModel"/> class.
        /// </summary>
        /// <param name="serviceProvider">The service provider to use with this view model.</param>
        public ViewportViewModel(IViewModelServiceProvider serviceProvider)
            : base(serviceProvider)
        {
            DependentProperties.Add(nameof(ContentWidth), new[] { nameof(ActualContentWidth) });
            DependentProperties.Add(nameof(ContentHeight), new[] { nameof(ActualContentHeight) });
            DependentProperties.Add(nameof(ScaleFactor), new[] { nameof(ActualContentWidth), nameof(ActualContentHeight) });

            FitOnScreenCommand     = new AnonymousCommand(ServiceProvider, FitOnScreen);
            ScaleToRealSizeCommand = new AnonymousCommand(ServiceProvider, ScaleToRealSize);
            ZoomInCommand          = new AnonymousCommand(ServiceProvider, () => ZoomIn(ViewportWidth * 0.5, ViewportHeight * 0.5));
            ZoomOutCommand         = new AnonymousCommand(ServiceProvider, () => ZoomOut(ViewportWidth * 0.5, ViewportHeight * 0.5));
        }
        public SpriteBordersViewModel(SpriteInfoViewModel sprite, IObjectNode spriteNode)
            : base(sprite)
        {
            textureRegionNode = spriteNode[nameof(SpriteInfo.TextureRegion)];
            textureRegionNode.ValueChanged += OnTextureRegionValueChanged;

            var spriteBordersNode = spriteNode[nameof(SpriteInfo.Borders)];

            borderBinding = new MemberGraphNodeBinding <Vector4>(spriteBordersNode, nameof(Borders), OnPropertyChanging, OnPropertyChanged, UndoRedoService);

            DependentProperties.Add(nameof(Borders), new[] { nameof(ActualBorders) });
            DependentProperties.Add(nameof(ScaleFactor), new[] { nameof(ActualBorders) });
        }
Exemple #16
0
 public SpriteSheetPreviewViewModel(SessionViewModel session)
     : base(session)
 {
     PreviewPreviousFrameCommand = new AnonymousCommand(ServiceProvider, () => { if (PreviewFrameCount > 0)
                                                                                 {
                                                                                     PreviewCurrentFrame = 1 + (PreviewCurrentFrame + PreviewFrameCount - 2) % PreviewFrameCount;
                                                                                 }
                                                        });
     PreviewNextFrameCommand = new AnonymousCommand(ServiceProvider, () => { if (PreviewFrameCount > 0)
                                                                             {
                                                                                 PreviewCurrentFrame = 1 + (PreviewCurrentFrame + PreviewFrameCount) % PreviewFrameCount;
                                                                             }
                                                    });
     DependentProperties.Add(nameof(DisplayMode), new[] { nameof(PreviewCurrentFrame), nameof(PreviewFrameCount) });
 }
Exemple #17
0
        public TextureRegionViewModel(SpriteInfoViewModel sprite, IMemberNode textureRegionNode)
            : base(sprite)
        {
            if (sprite.Editor.Cache != null)
            {
                RefreshImageSize();
            }
            else
            {
                sprite.Editor.Initialized += EditorInitialized;
            }
            textureRegionBinding = new MemberGraphNodeBinding <RectangleF, Rectangle>(textureRegionNode, nameof(Region), OnPropertyChanging, OnPropertyChanged, x => (Rectangle)x, UndoRedoService);

            DependentProperties.Add(nameof(Region), new[] { nameof(ActualLeft), nameof(ActualTop), nameof(ActualWidth), nameof(ActualHeight), nameof(ActualRightOffset), nameof(ActualBottomOffset) });
            DependentProperties.Add(nameof(ScaleFactor), new[] { nameof(ActualLeft), nameof(ActualTop), nameof(ActualWidth), nameof(ActualHeight), nameof(ActualRightOffset), nameof(ActualBottomOffset) });
            DependentProperties.Add(nameof(ImageWidth), new[] { nameof(ActualRightOffset), nameof(ActualBottomOffset) });
            DependentProperties.Add(nameof(ImageHeight), new[] { nameof(ActualRightOffset), nameof(ActualBottomOffset) });
        }
Exemple #18
0
        public SpriteCenterViewModel(SpriteInfoViewModel sprite, IObjectNode spriteNode)
            : base(sprite)
        {
            var spriteCenterNode = spriteNode[nameof(SpriteInfo.Center)];

            spriteCenterNodeBinding = new MemberGraphNodeBinding <Vector2>(spriteCenterNode, nameof(Center), OnPropertyChanging, OnPropertyChanged, UndoRedoService);
            var centerFromMiddleNode = spriteNode[nameof(SpriteInfo.CenterFromMiddle)];

            centerFromMiddleBinding = new MemberGraphNodeBinding <bool>(centerFromMiddleNode, nameof(CenterFromMiddle), OnPropertyChanging, OnPropertyChanged, UndoRedoService);

            var textureRegionNode = spriteNode[nameof(SpriteInfo.TextureRegion)];

            textureRegionBinding = new MemberGraphNodeBinding <Rectangle>(textureRegionNode, nameof(ActualCenter), OnPropertyChanging, OnPropertyChanged, UndoRedoService);

            DependentProperties.Add(nameof(Center), new[] { nameof(ActualCenter) });
            DependentProperties.Add(nameof(CenterFromMiddle), new[] { nameof(ActualCenter) });
            DependentProperties.Add(nameof(ScaleFactor), new[] { nameof(ActualCenter) });
        }
Exemple #19
0
        public PackageViewModel(SessionViewModel session, PackageContainer packageContainer, bool packageAlreadyInSession)
            : base(session)
        {
            PackageContainer = packageContainer;
            Package          = PackageContainer.Package;
            HasBeenUpgraded  = Package.IsDirty;
            DependentProperties.Add(nameof(PackagePath), new[] { nameof(Name), nameof(RootDirectory) });
            Dependencies    = new DependencyCategoryViewModel(nameof(Dependencies), this, session, Package.RootAssets);
            AssetMountPoint = new AssetMountPointViewModel(this);
            content.Add(AssetMountPoint);
            content.Add(Dependencies);
            RenameCommand = new AnonymousCommand(ServiceProvider, () => IsEditing = true);
            IsLoaded      = Package.State >= PackageState.AssetsReady;

            // IsDeleted will make the package added to Session.LocalPackages, so let's do it last
            InitialUndelete(!packageAlreadyInSession);

            DeletedAssets.CollectionChanged += DeletedAssetsChanged;
        }
Exemple #20
0
        public SpriteSheetEditorViewModel([NotNull] SpriteSheetViewModel spriteSheet)
            : base(spriteSheet)
        {
            Viewport = new ViewportViewModel(ServiceProvider);

            // Commands
            DisplaySpriteSheetPropertiesCommand = new AnonymousCommand(ServiceProvider, DisplaySpriteSheetProperties);
            RemoveImageCommand              = new AnonymousCommand(ServiceProvider, RemoveSelectedImages);
            SelectNextSpriteCommand         = new AnonymousCommand <int>(ServiceProvider, SelectNextSprite);
            MoveImageCommand                = new AnonymousCommand <int>(ServiceProvider, MoveImage);
            AddNewImageCommand              = new AnonymousCommand(ServiceProvider, AddNewImage);
            UseWholeImageCommand            = new AnonymousCommand(ServiceProvider, UseWholeImage);
            FocusOnRegionCommand            = new AnonymousCommand(ServiceProvider, FocusOnRegion);
            DuplicateSelectedImagesCommand  = new AnonymousCommand(ServiceProvider, DuplicateSelectedImages);
            CopyImageCommand                = new AnonymousCommand(ServiceProvider, CopyImages, CanCopyImages);
            PasteImageCommand               = new AnonymousCommand(ServiceProvider, PasteImages, () => pasteMonitor.Get(CanPasteImages));
            FindSpriteRegionCommand         = new AnonymousCommand <WindowsPoint>(ServiceProvider, FindSpriteRegion);
            ToggleSelectionHighlightCommand = new AnonymousCommand(ServiceProvider, () => SelectionHighlightEnabled = !SelectionHighlightEnabled);
            ToggleToolModeCommand           = new AnonymousCommand <SpriteSheetEditorToolMode>(ServiceProvider, ToggleToolMode);
            ToggleUseMagicWandCommand       = new AnonymousCommand(ServiceProvider, () => ToggleToolMode(SpriteSheetEditorToolMode.MagicWand));

            SelectedSprites = new ObservableList <object>();
            SelectedSprites.CollectionChanged += SelectedImagesCollectionChanged;
            ServiceProvider.Get <SelectionService>().RegisterSelectionScope(id => Sprites.FirstOrDefault(x => x.Id == id), obj => (obj as SpriteInfoViewModel)?.Id, SelectedSprites);
            sprites = new ObservableList <SpriteInfoViewModel>(Asset.Asset.Sprites.Select((x, i) => new SpriteInfoViewModel(this, x)
            {
                Index = i
            }));
            Sprites.CollectionChanged += ImageCollectionChanged;
            DependentProperties.Add(nameof(ToolMode), new[] { nameof(UsingPixelTool) });
            magicWandUseTransparency = !Asset.Asset.ColorKeyEnabled;

            var rootNode = Session.AssetNodeContainer.GetNode(spriteSheet.Asset);

            spritesNode                = rootNode[nameof(SpriteSheetAsset.Sprites)].Target;
            colorKeyNodeBinding        = new MemberGraphNodeBinding <Color>(rootNode[nameof(SpriteSheetAsset.ColorKeyColor)], nameof(ColorKey), OnPropertyChanging, OnPropertyChanged, UndoRedoService);
            colorKeyEnabledNodeBinding = new MemberGraphNodeBinding <bool>(rootNode[nameof(SpriteSheetAsset.ColorKeyEnabled)], nameof(ColorKeyEnabled), OnPropertyChanging, OnPropertyChanged, UndoRedoService);
            typeNodeBinding            = new MemberGraphNodeBinding <SpriteSheetType>(rootNode[nameof(SpriteSheetAsset.Type)], nameof(Type), OnPropertyChanging, OnPropertyChanged, UndoRedoService);

            // TODO: dispose this
            spritesNode.ItemChanged += SpritesContentChanged;
        }
Exemple #21
0
        internal LauncherViewModel(IViewModelServiceProvider serviceProvider, NugetStore store)
            : base(serviceProvider)
        {
            if (store == null)
            {
                throw new ArgumentNullException(nameof(store));
            }
            DependentProperties.Add("ActiveVersion", new[] { "ActiveDocumentationPages" });
            this.store   = store;
            store.Logger = this;

            DisplayReleaseAnnouncement();

            VsixPackage = new VsixVersionViewModel(this, store);
            // Commands
            InstallLatestVersionCommand = new AnonymousTaskCommand(ServiceProvider, InstallLatestVersion)
            {
                IsEnabled = false
            };
            OpenUrlCommand   = new AnonymousTaskCommand <string>(ServiceProvider, OpenUrl);
            ReconnectCommand = new AnonymousTaskCommand(ServiceProvider, async() =>
            {
                // We are back online (or so we think)
                IsOffline = false;
                await FetchOnlineData();
            });
            StartStudioCommand = new AnonymousTaskCommand(ServiceProvider, StartStudio)
            {
                IsEnabled = false
            };

            foreach (var devVersion in LauncherSettings.DeveloperVersions)
            {
                var version = new XenkoDevVersionViewModel(this, store, null, devVersion, false);
                xenkoVersions.Add(version);
            }
            FetchOnlineData().Forget();
            LoadRecentProjects();
            uninstallHelper = new UninstallHelper(serviceProvider, store);
            GameStudioSettings.RecentProjectsUpdated += (sender, e) => Dispatcher.InvokeAsync(LoadRecentProjects).Forget();
        }
Exemple #22
0
        protected override void InvokeInternal(CommandProcessorContext cpc)
        {
            DesignerInfo designerInfo;

            Debug.Assert(cpc.Artifact != null, "Artifact was null");
            if (Association != null &&
                cpc.Artifact != null &&
                cpc.Artifact.DesignerInfo() != null &&
                cpc.Artifact.DesignerInfo().TryGetDesignerInfo(OptionsDesignerInfo.ElementName, out designerInfo))
            {
                // APPDB_SCENARIO: We cannot use referential constraints for 0..1:0..1 or 1:1 associations, since these exist as configured
                //                 0..1:* or 1:* associations and so introducing a referential constraint would cause validation errors.
                // Must use Referential Constraint for 1:0..1 relationship as using an AssociationSetMapping results in illegal reference to the same ID column twice (since the PK is also the FK)
                if (Association.IsOneToZeroOrOne ||
                    (UseReferentialConstraint && !(Association.IsZeroOrOneToZeroOrOne || Association.IsOneToOne)))
                {
                    // We're including fk columns, so the update will consist of a ref constraint
                    var createRefConCommand = new CreateOrUpdateReferentialConstraintCommand(
                        (c, subCpc) =>
                    {
                        var cmd                 = c as CreateOrUpdateReferentialConstraintCommand;
                        cmd.PrincipalEnd        = PrincipalEnd;
                        cmd.DependentEnd        = DependentEnd;
                        cmd.PrincipalProperties = PrincipalProperties;
                        cmd.DependentProperties = DependentProperties;

                        return(cmd.PrincipalEnd != null && cmd.DependentEnd != null);
                    });

                    CommandProcessor.InvokeSingleCommand(cpc, createRefConCommand);
                }
                else
                {
                    // We're not including fk columns, so the update will consist of an association set mapping and a deletes of the fk columns (if they exist)
                    // otherwise update AssociationSetMapping appropriately
                    var createMapCommand = new CreateOrUpdateAssociationSetMappingCommand(
                        (c, subCpc) =>
                    {
                        var cmd                    = c as CreateOrUpdateAssociationSetMappingCommand;
                        cmd.Association            = Association;
                        cmd.AssociationSet         = AssociationSet;
                        cmd.EntityContainerMapping = EntityContainerMapping;
                        cmd.StorageEntitySet       = StorageEntitySet;

                        return(cmd.Association != null && cmd.AssociationSet != null && cmd.EntityContainerMapping != null &&
                               cmd.StorageEntitySet != null);
                    });

                    CommandProcessor.InvokeSingleCommand(cpc, createMapCommand);

                    // Delete the fk properties in the conceptual layer if they exist. Do not delete primary key properties though!
                    if (!IncludeFkProperties)
                    {
                        var propertiesToDelete =
                            DependentProperties.Where(p => p.EntityType != null && !p.EntityType.ResolvableKeys.Contains(p)).ToList();
                        foreach (var p in propertiesToDelete)
                        {
                            var deletePropertyCmd = new DeletePropertyCommand(
                                (c, subCpc) =>
                            {
                                var cmd       = c as DeletePropertyCommand;
                                cmd.EFElement = p;
                                return(cmd.EFElement != null);
                            });

                            CommandProcessor.InvokeSingleCommand(cpc, deletePropertyCmd);
                        }
                    }

                    // Add or update the EndProperty elements for the AssociationSetMapping. Try to work out which end is the principal
                    // end by looking at the multiplicity, since we don't have a referential constraint in this case.
                    AssociationSetEnd principalSetEnd;
                    AssociationSetEnd dependentSetEnd;

                    Debug.Assert(
                        AssociationSet.AssociationSetEnds().First().Role.Target != null,
                        "Role Target for Association End was null, AssociationSetMapping update failed");
                    if (AssociationSet.AssociationSetEnds().First().Role.Target != null)
                    {
                        if (Association.End1.Multiplicity.Value == ModelConstants.Multiplicity_Many)
                        {
                            principalSetEnd = AssociationSet.AssociationSetEnds().Last();
                            dependentSetEnd = AssociationSet.AssociationSetEnds().First();
                        }
                        else
                        {
                            principalSetEnd = AssociationSet.AssociationSetEnds().First();
                            dependentSetEnd = AssociationSet.AssociationSetEnds().Last();
                        }

                        var dependentEndPropertyCmd = new CreateOrUpdateEndPropertyCommand(
                            (c, subCpc) =>
                        {
                            var cmd = c as CreateOrUpdateEndPropertyCommand;
                            cmd.AssociationSetEnd       = dependentSetEnd;
                            cmd.AssociationSetMapping   = createMapCommand.AssociationSetMapping;
                            cmd.StorageKeyProperties    = StorageDependentTypeKeyProperties;
                            cmd.ConceptualKeyProperties =
                                ConceptualDependentType.SafeInheritedAndDeclaredProperties.Where(p => p.IsKeyProperty);

                            return(cmd.AssociationSetEnd != null && cmd.AssociationSetMapping != null);
                        });

                        var principalEndPropertyCmd = new CreateOrUpdateEndPropertyCommand(
                            (c, subCpc) =>
                        {
                            var cmd = c as CreateOrUpdateEndPropertyCommand;
                            cmd.AssociationSetEnd       = principalSetEnd;
                            cmd.AssociationSetMapping   = createMapCommand.AssociationSetMapping;
                            cmd.StorageKeyProperties    = StorageDependentTypeForeignKeyProperties;
                            cmd.ConceptualKeyProperties =
                                ConceptualPrincipalType.SafeInheritedAndDeclaredProperties.Where(p => p.IsKeyProperty);

                            return(cmd.AssociationSetEnd != null && cmd.AssociationSetMapping != null);
                        });

                        CommandProcessor.InvokeSingleCommand(cpc, dependentEndPropertyCmd);
                        CommandProcessor.InvokeSingleCommand(cpc, principalEndPropertyCmd);
                    }
                }
            }
        }
        protected CombinedNodeViewModel(GraphViewModel ownerViewModel, string name, IEnumerable <SingleNodeViewModel> combinedNodes, Index index)
            : base(ownerViewModel, index)
        {
            // ReSharper disable once DoNotCallOverridableMethodsInConstructor
            DependentProperties.Add(nameof(Value), new[] { nameof(HasMultipleValues), nameof(IsPrimitive), nameof(HasCollection), nameof(HasDictionary) });
            this.combinedNodes = new List <SingleNodeViewModel>(combinedNodes);
            Name        = name;
            DisplayName = this.combinedNodes.First().DisplayName;

            combinedNodeInitialValues         = new List <object>();
            distinctCombinedNodeInitialValues = new HashSet <object>();

            bool isReadOnly = false;
            bool isVisible  = false;
            bool nullOrder  = false;

            foreach (var node in this.combinedNodes)
            {
                if (node.IsDestroyed)
                {
                    throw new InvalidOperationException("One of the combined node is already disposed.");
                }

                if (node.IsReadOnly)
                {
                    isReadOnly = true;
                }

                if (node.IsVisible)
                {
                    isVisible = true;
                }

                if (node.Order == null)
                {
                    nullOrder = true;
                }

                if (order == node.Order || (!nullOrder && order == null))
                {
                    order = node.Order;
                }

                // Note: sometimes member info could be different for the same member if we select objects of types that inherit from another
                // This will just affect the view order, so it shouldn't be a problem.
                if (memberInfo == null)
                {
                    memberInfo = node.MemberInfo;
                }

                combinedNodeInitialValues.Add(node.Value);
                distinctCombinedNodeInitialValues.Add(node.Value);
            }
            IsReadOnly = isReadOnly;
            IsVisible  = isVisible;

            ResetInitialValues = new AnonymousCommand(ServiceProvider, () =>
            {
                using (Owner.BeginCombinedAction(Owner.FormatCombinedUpdateMessage(this, null), Path))
                {
                    CombinedNodes.Zip(combinedNodeInitialValues).ForEach(x => x.Item1.Value = x.Item2);
                    Refresh();
                }
            });
        }
Exemple #24
0
 private DragContainer()
 {
     DependentProperties.Add(nameof(IsAccepted), new[] { nameof(IsRejected) });
 }