Beispiel #1
0
        private void SetArtifactLink(UnfoldScope scope)
        {
            var container = scope.Automation.Owner;

            // Determine created item
            IItemContainer createdItem = null;

            createdItem = this.Solution.Find <IProject>(p => p.PhysicalPath == this.projectCreated).SingleOrDefault();
            if (createdItem == null)
            {
                createdItem = this.Solution.Find <IItem>(pi => pi.PhysicalPath == this.projectItemCreated).SingleOrDefault();
            }

            if (createdItem != null)
            {
                if (this.UriService.CanCreateUri <IItemContainer>(createdItem))
                {
                    // Set the artifact link
                    SolutionArtifactLinkReference
                    .SetReference(container, this.UriService.CreateUri <IItemContainer>(createdItem))
                    .Tag = BindingSerializer.Serialize(scope.ReferenceTag);
                }
                else
                {
                    tracer.Warn(Properties.Resources.InstantiationTemplateWizard_CantCreateUri, createdItem.GetLogicalPath());
                }
            }
        }
Beispiel #2
0
            public void WhenChangingSavedValidatorBindingSettings_ThenPersistsChanges()
            {
                var settings = new ValidationBindingSettings
                {
                    TypeId     = "Foo",
                    Properties =
                    {
                        new PropertyBindingSettings
                        {
                            Name  = "Message",
                            Value = "Hello",
                        },
                        new PropertyBindingSettings
                        {
                            Name          = "From",
                            ValueProvider = new ValueProviderBindingSettings
                            {
                                TypeId = "CurrentUserProvider",
                            }
                        },
                    },
                };

                ((PropertySchema)this.property).RawValidationRules = BindingSerializer.Serialize <ValidationBindingSettings[]>(new ValidationBindingSettings[] { settings });

                ((BindingSettings)this.property.ValidationSettings.First()).Properties[0].Value = "World";
                ((BindingSettings)this.property.ValidationSettings.First()).Properties[1].ValueProvider.TypeId = "AnotherProvider";

                var saved = BindingSerializer.Deserialize <ValidationBindingSettings[]>(((PropertySchema)this.property).RawValidationRules);

                Assert.Equal(1, saved.Length);
                Assert.Equal("World", saved[0].Properties[0].Value);
                Assert.Equal("AnotherProvider", saved[0].Properties[1].ValueProvider.TypeId);
            }
        /// <summary>
        /// 读取模组资源;
        /// </summary>
        public ModificationResource Read(Modification modification)
        {
            ModificationResource resource = new ModificationResource();

            serializer.Serialize(modification.BaseContent, ref resource);
            return(resource);
        }
Beispiel #4
0
        /// <summary>
        /// Initializes the child element after it is created and added to the parent for the given item.
        /// </summary>
        protected override void InitializeCreatedElement(string itemId, IAbstractElement childElement)
        {
            Guard.NotNull(() => childElement, childElement);

            // Get the solution item for this imported file.
            var solutionItem = GetItemInSolution(itemId);

            if (solutionItem != null)
            {
                tracer.Info(
                    Resources.CreateElementFromFileCommand_TraceAddingReference, this.CurrentElement.InstanceName, childElement.InstanceName, solutionItem.GetLogicalPath());

                // Create artifact link
                var reference = SolutionArtifactLinkReference.AddReference(childElement, this.UriService.CreateUri(solutionItem));
                reference.AddTag(this.Tag);
                reference.AddTag(BindingSerializer.Serialize(new ReferenceTag
                {
                    SyncNames = this.SyncName
                }));
            }
            else
            {
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
                                                                  Resources.CreateElementFromFileCommand_ErrorNoSolutionItem, this.CurrentElement.InstanceName, childElement.InstanceName));
            }
        }
Beispiel #5
0
        /// <summary>
        /// Saves the <see cref="Collection{T}"/> instances as a serialized string.
        /// </summary>
        public override void SetValue(object component, object value)
        {
            var values = value as Collection <T>;

            if (values != null)
            {
                var serializedValue = values.Count == 0 ? null : BindingSerializer.Serialize(values);
                base.SetValue(component, serializedValue);
            }
        }
Beispiel #6
0
        /// <summary>
        /// Processes the document
        /// </summary>
        /// <param name="document">The document to process.</param>
        public void ProcessSchema(XDocument document)
        {
            Guard.NotNull(() => document, document);

            this.IsModified = false;

            // Locate all <commandSettings>
            var commandSettings = document.Descendants(CommandSettingsElementName)
                                  .Distinct();

            if (commandSettings.Any())
            {
                tracer.Info(Resources.CommandSettingsUpgradeProcessor_TraceDeserialize);

                // Enumerate each <commandSettings> element
                commandSettings.ForEach(cmdSettingsElement =>
                {
                    var id = cmdSettingsElement.Attribute(CommandSettingsIdName) != null ? cmdSettingsElement.Attribute(CommandSettingsIdName).Value : string.Empty;
                    var cmdPropsElement = cmdSettingsElement.Descendants(CommandSettingsPropertiesElementName).FirstOrDefault();
                    if (cmdPropsElement != null)
                    {
                        // Determine if has any <propertySettings>
                        var propSettingsElements = cmdPropsElement.Descendants(PropertySettingsElementName);
                        if (propSettingsElements.Any())
                        {
                            tracer.Info(Resources.CommandSettingsUpgradeProcessor_TraceDeserializeCommandSettings, id);

                            var bindings = new List <IPropertyBindingSettings>();
                            var processedPropertySettings = new List <XElement>();

                            // Enumerate each <propertySettings> element
                            propSettingsElements.ForEach(propSettingElement =>
                            {
                                // Ensure we have not already processed this <propertySettings> element
                                // (i.e. that it is not a nested <propertySettings> element)
                                if (!processedPropertySettings.Contains(propSettingElement))
                                {
                                    // Add to processed cache
                                    processedPropertySettings.Add(propSettingElement);

                                    // Create bindings
                                    AddPropertySettings(cmdPropsElement, bindings, propSettingElement, processedPropertySettings);
                                }
                            });

                            // Update value of <properties> element
                            cmdPropsElement.SetValue(BindingSerializer.Serialize <IEnumerable <IPropertyBindingSettings> >(bindings));
                            this.IsModified = true;
                        }
                    }
                });
            }
        }
        private void UpdateReferenceTagTo1113()
        {
            var references = this.CurrentElement.References.Where(r => r.Tag == this.ReferenceTag);

            foreach (var reference in references)
            {
                reference.Tag = BindingSerializer.Serialize(new ReferenceTag {
                    SyncNames = true, TargetFileName = string.Empty
                });
            }
            this.ReferenceTag = string.Empty;
        }
        /// <summary>
        /// Saves the new instances as a serialized string.
        /// </summary>
        public override void SetValue(object component, object value)
        {
            var values = value as ICollection <object>;

            if (values != null)
            {
                var serializedValue = values.Count == 0 ? null : BindingSerializer.Serialize(values);
                var property        = GetPropertySettings(component);
                if (property != null)
                {
                    property.Value = serializedValue;
                }
            }
        }
        private static string GetSerializedLinkExistsCondition()
        {
            // Set the conditions
            var condition =
                new[]
            {
                new ConditionBindingSettings
                {
                    TypeId = typeof(ArtifactReferenceExistsCondition).FullName,
                }
            };

            return(BindingSerializer.Serialize(condition));
        }
Beispiel #10
0
        private static readonly string guidanceIconPath = ""; //"Resources/CommandShowGuidance.png";

        /// <summary>
        /// Ensures the associated commands and launchpoint automation are created and configured correctly.
        /// </summary>
        internal void EnsureGuidanceExtensionAutomation()
        {
            IPatternElementSchema element            = this.Extends as IPatternElementSchema;
            Func <bool>           existanceCondition = () => !string.IsNullOrEmpty(this.ExtensionId);

            // Configure the instantiate command, event.
            var instantiateCommand = element.EnsureCommandAutomation <InstantiateGuidanceWorkflowCommand>(Properties.Resources.GuidanceExtension_InstantiateCommandName,
                                                                                                          existanceCondition);

            if (instantiateCommand != null)
            {
                instantiateCommand.SetPropertyValue <InstantiateGuidanceWorkflowCommand, string>(cmd => cmd.ExtensionId, this.ExtensionId);
                instantiateCommand.SetPropertyValue <InstantiateGuidanceWorkflowCommand, string>(cmd => cmd.DefaultInstanceName, this.GuidanceInstanceName);
                instantiateCommand.SetPropertyValue <InstantiateGuidanceWorkflowCommand, bool>(cmd => cmd.SharedInstance, this.GuidanceSharedInstance);
                instantiateCommand.SetPropertyValue <InstantiateGuidanceWorkflowCommand, bool>(cmd => cmd.ActivateOnInstantiation, this.GuidanceActivateOnCreation);
            }

            element.EnsureEventLaunchPoint <IOnElementInstantiatedEvent>(Properties.Resources.GuidanceExtension_InstantiateEventName,
                                                                         instantiateCommand, () => !String.IsNullOrEmpty(this.ExtensionId));

            // Configure the activate command and menu.
            var activateCommand = element.EnsureCommandAutomation <ActivateGuidanceWorkflowCommand>(Properties.Resources.GuidanceExtension_ActivateCommandName,
                                                                                                    existanceCondition);

            var activateMenu = element.EnsureMenuLaunchPoint(Resources.GuidanceExtension_ActivateContextMenuName,
                                                             activateCommand, Resources.GuidanceExtension_ActivateMenuItemText, guidanceIconPath,
                                                             existanceCondition);

            if (activateMenu != null)
            {
                // Set the conditions
                activateMenu.Conditions = BindingSerializer.Serialize(
                    new List <ConditionBindingSettings>
                {
                    new ConditionBindingSettings
                    {
                        TypeId     = typeof(ElementReferenceExistsCondition).FullName,
                        Properties =
                        {
                            new PropertyBindingSettings
                            {
                                Name  = Reflector <ElementReferenceExistsCondition> .GetPropertyName(cond => cond.Kind),
                                Value = ReferenceKindConstants.GuidanceTopic
                            },
                        }
                    }
                });
            }
        }
Beispiel #11
0
            private IAutomationSettingsSchema AssertActivateContextMenu(bool verifySettings)
            {
                var menu = this.container.AutomationSettings.FirstOrDefault(set => set.Name.Equals(Properties.Resources.GuidanceExtension_ActivateContextMenuName));

                Assert.NotNull(menu);

                var menuSettings = menu.GetExtensions <MenuSettings>().FirstOrDefault();

                Assert.NotNull(menuSettings);

                if (verifySettings)
                {
                    Assert.Equal(CustomizationState.False, menu.IsCustomizable);
                    Assert.True(menu.IsSystem);

                    var command         = AssertActivateCommand(false);
                    var commandSettings = command.GetExtensions <ICommandSettings>().FirstOrDefault();

                    Assert.Equal(menuSettings.Text, Properties.Resources.GuidanceExtension_ActivateMenuItemText);
                    Assert.Equal(menuSettings.CommandId, commandSettings.Id);
                    Assert.Equal(menuSettings.WizardId, Guid.Empty);

                    var conditions = BindingSerializer.Serialize(
                        new[]
                    {
                        new ConditionBindingSettings
                        {
                            TypeId     = typeof(ElementReferenceExistsCondition).FullName,
                            Properties =
                            {
                                new PropertyBindingSettings
                                {
                                    Name  = Reflector <ElementReferenceExistsCondition> .GetPropertyName(cond => cond.Kind),
                                    Value = ReferenceKindConstants.GuidanceTopic
                                },
                            }
                        }
                    });

                    Assert.Equal(menuSettings.Conditions, conditions);
                }

                return(menu);
            }
        public void WhenSerialingAnObjectWithAStringProperty_ThenItDeserializesItProperly()
        {
            var foos = new List <Foo> {
                new Foo {
                    Bar = 1, Baz = "Baz1"
                }, new Foo {
                    Bar = 2, Baz = "Baz2"
                }
            };

            var ser = BindingSerializer.Serialize(foos);

            var dserFoos = BindingSerializer.Deserialize <List <Foo> >(ser);

            Assert.Equal(dserFoos.Count, foos.Count);
            Assert.Equal(dserFoos.ElementAt(0).Bar, foos.ElementAt(0).Bar);
            Assert.Equal(dserFoos.ElementAt(0).Baz, foos.ElementAt(0).Baz);
            Assert.Equal(dserFoos.ElementAt(1).Bar, foos.ElementAt(1).Bar);
            Assert.Equal(dserFoos.ElementAt(1).Baz, foos.ElementAt(1).Baz);
        }
            public void WhenItemAlreadyExistsAndTargetFileNameHasExtension_ThenVsItemRenamedWithVerifiedName()
            {
                var projectItem = Mock.Get <EnvDTE.ProjectItem>(this.solutionItem.Object.As <EnvDTE.ProjectItem>());

                var          parent      = Mock.Get <IProject>(this.solutionItem.Object.Parent as IProject);
                Mock <IItem> anotherItem = new Mock <IItem>();

                anotherItem.Setup(i => i.Name).Returns(this.OwnerElement.Object.InstanceName + ".cs");
                parent.Setup(p => p.Items).Returns(new[] { solutionItem.Object, anotherItem.Object });


                var reference = Mock.Get <IReference>(this.OwnerElement.Object.References.First());

                reference.Setup(r => r.Tag).Returns(BindingSerializer.Serialize <ReferenceTag>(new ReferenceTag {
                    TargetFileName = "TestElementName1.cs"
                }));

                Command.Execute();

                projectItem.VerifySet(pi => pi.Name = "TestElementName1.cs", Times.Once());
            }
Beispiel #14
0
            public override void Initialize()
            {
                base.Initialize();

                this.status = new Mock <ICommandStatus>();

                this.bindingFactory = new Mock <IBindingFactory>();
                this.statusBinding  = new Mock <IDynamicBinding <ICommandStatus> >
                {
                    DefaultValue = DefaultValue.Mock
                };
                this.statusBinding.Setup(b => b.Value).Returns(this.status.Object);
                this.statusBinding.Setup(b => b.Evaluate(It.IsAny <IDynamicBindingContext>())).Returns(true);

                this.bindingFactory.Setup(f => f.CreateBinding <ICommandStatus>(It.IsAny <IBindingSettings>())).Returns(this.statusBinding.Object);
                this.Settings.Setup(x => x.CustomStatus).Returns(BindingSerializer.Serialize(new BindingSettings {
                    TypeId = "Foo"
                }));

                this.Automation.BindingFactory = this.bindingFactory.Object;
            }
        public void WhenRoundTrippingFullBinding_ThenSucceeds()
        {
            IBindingSettings binding = new BindingSettings
            {
                TypeId     = "foo",
                Properties =
                {
                    new PropertyBindingSettings
                    {
                        Name          = "Name",
                        Value         = "Value",
                        ValueProvider = new ValueProviderBindingSettings
                        {
                            TypeId     = "ValueProvider",
                            Properties =
                            {
                                new PropertyBindingSettings
                                {
                                    Name  = "Id",
                                    Value = "1"
                                }
                            }
                        }
                    }
                }
            };

            var serialized   = BindingSerializer.Serialize(binding);
            var deserialized = BindingSerializer.Deserialize <IBindingSettings>(serialized);

            Assert.Equal(binding.TypeId, deserialized.TypeId);
            Assert.Equal(binding.Properties.Count, deserialized.Properties.Count);
            Assert.Equal(binding.Properties[0].Name, deserialized.Properties[0].Name);
            Assert.Equal(binding.Properties[0].Value, deserialized.Properties[0].Value);
            Assert.Equal(binding.Properties[0].ValueProvider.TypeId, deserialized.Properties[0].ValueProvider.TypeId);
            Assert.Equal(binding.Properties[0].ValueProvider.Properties[0].Name, deserialized.Properties[0].ValueProvider.Properties[0].Name);
            Assert.Equal(binding.Properties[0].ValueProvider.Properties[0].Value, deserialized.Properties[0].ValueProvider.Properties[0].Value);
        }
            private IAutomationSettingsSchema AssertSelectContextMenu(bool verifySettings)
            {
                var menu = this.container.AutomationSettings.FirstOrDefault(set => set.Name.Equals(Properties.Resources.ArtifactExtension_SelectContextMenuName));

                Assert.NotNull(menu);

                var menuSettings = menu.GetExtensions <MenuSettings>().FirstOrDefault();

                Assert.NotNull(menuSettings);

                if (verifySettings)
                {
                    Assert.Equal(CustomizationState.False, menu.IsCustomizable);
                    Assert.True(menu.IsSystem);

                    var command         = AssertSelectCommand(false);
                    var commandSettings = command.GetExtensions <ICommandSettings>().FirstOrDefault();

                    Assert.Equal(menuSettings.Text, Resources.ArtifactExtension_SelectMenuItemText);
                    Assert.Equal(menuSettings.CommandId, commandSettings.Id);
                    Assert.Equal(menuSettings.WizardId, Guid.Empty);

                    var conditions = BindingSerializer.Serialize(
                        new[]
                    {
                        new ConditionBindingSettings
                        {
                            TypeId = typeof(ArtifactReferenceExistsCondition).FullName,
                        }
                    });

                    Assert.Equal(menuSettings.Conditions, conditions);
                }

                return(menu);
            }
Beispiel #17
0
        /// <summary>
        /// Processes the document
        /// </summary>
        /// <param name="document">The document to process.</param>
        public void ProcessSchema(XDocument document)
        {
            Guard.NotNull(() => document, document);

            this.IsModified = false;

            // Locate all <commandSettings> that have a 'typeId=' any of the old feature commands
            var commandSettings = document.Descendants(CommandSettingsElementName)
                                  .Where(cs => cs.Attribute(CommandSettingsTypeIdName) != null)
                                  .Where(cs => cs.Attribute(CommandSettingsTypeIdName).Value == ActivateCommandTypeName ||
                                         cs.Attribute(CommandSettingsTypeIdName).Value == InstantiateCommandTypeName ||
                                         cs.Attribute(CommandSettingsTypeIdName).Value == ActivateOrInstantiateCommandTypeName)
                                  .Distinct();

            if (commandSettings.Any())
            {
                tracer.Info(Resources.GuidanceCommandUpgradeProcessor_TraceDeserialize);

                // Enumerate each <commandSettings> element
                commandSettings.ForEach(cmdSettingsElement =>
                {
                    // Rename command TypeId
                    var typeId    = cmdSettingsElement.Attribute(CommandSettingsTypeIdName) != null ? cmdSettingsElement.Attribute(CommandSettingsTypeIdName).Value : string.Empty;
                    var newTypeId = string.Empty;
                    switch (typeId)
                    {
                    case ActivateCommandTypeName:
                        newTypeId = typeof(ActivateGuidanceWorkflowCommand).FullName;
                        break;

                    case InstantiateCommandTypeName:
                        newTypeId = typeof(InstantiateGuidanceWorkflowCommand).FullName;
                        break;

                    case ActivateOrInstantiateCommandTypeName:
                        newTypeId = typeof(ActivateOrInstantiateSharedGuidanceWorkflowCommand).FullName;
                        break;
                    }

                    if (!String.IsNullOrEmpty(newTypeId))
                    {
                        // Rename command typeId
                        cmdSettingsElement.Attribute(CommandSettingsTypeIdName).SetValue(newTypeId);
                        this.IsModified = true;

                        //Rename 'FeatureId' property to 'ExtensionId' property
                        // Note, not all these commands have properties
                        var cmdPropsElement = cmdSettingsElement.Descendants(CommandSettingsPropertiesElementName).FirstOrDefault();
                        if (cmdPropsElement != null)
                        {
                            var propertiesValue = cmdPropsElement.Value;
                            if (!string.IsNullOrEmpty(propertiesValue))
                            {
                                try
                                {
                                    var bindings = BindingSerializer.Deserialize <IEnumerable <IPropertyBindingSettings> >(propertiesValue).ToList();
                                    if (bindings != null && bindings.Any())
                                    {
                                        // Note, not all the commands had the 'FeatureId' property
                                        var featureIdProperty = bindings.FirstOrDefault(p => p.Name == FeatureIdPropertyName);
                                        if (featureIdProperty != null)
                                        {
                                            // Replace 'FeatureId' Property binding
                                            featureIdProperty.Name = Reflector <InstantiateGuidanceWorkflowCommand> .GetPropertyName(x => x.ExtensionId);

                                            // Write bindings back
                                            cmdPropsElement.SetValue(BindingSerializer.Serialize(bindings));
                                            this.IsModified = true;
                                        }
                                    }
                                }
                                catch (BindingSerializationException)
                                {
                                    // Ignore deserializaton exception
                                }
                            }
                        }
                    }
                });
            }
        }
Beispiel #18
0
 private void OnSaveRules(object sender, EventArgs args)
 {
     this.Properties = BindingSerializer.Serialize(this.propertySettings);
 }
        internal static IItemContainer UnfoldTemplate(ISolution solution, IUriReferenceService uriService, IServiceProvider serviceProvider, IProductElement owner, UnfoldVsTemplateSettings settings, bool fromWizard)
        {
            var eventScope = new StoreEventBufferingScope();

            try
            {
                Guard.NotNull(() => solution, solution);
                Guard.NotNull(() => owner, owner);
                Guard.NotNull(() => settings, settings);

                var pathHelper  = new UnfoldPathHelper(solution);
                var templateUri = new Uri(settings.TemplateUri);

                // Resolve the designtime template
                tracer.Verbose(
                    Resources.UnfoldVsTemplateCommand_TraceResolvingTemplateUri, owner, settings.TemplateUri.ToString());
                var template = uriService.TryResolveUri <ITemplate>(templateUri);
                if (template == null)
                {
                    throw new FileNotFoundException(
                              string.Format(CultureInfo.CurrentCulture,
                                            Resources.UnfoldVsTemplateCommand_ErrorTemplateNotFound, templateUri), settings.TemplateUri.ToString());
                }

                // Resolve the vstemplate
                tracer.Verbose(
                    Resources.UnfoldVsTemplateCommand_TraceResolvingVsTemplateUri, owner, templateUri);
                var vsTemplate = uriService.ResolveUri <IVsTemplate>(templateUri);

                // Get the resolved instance name for the unfolded item
                var unfoldResolver = new UnfoldParentResolver(solution, uriService, owner, vsTemplate);
                unfoldResolver.ResolveParent(settings.TargetPath, settings.TargetFileName);
                var instanceName = unfoldResolver.FileName;
                if (settings.SanitizeName)
                {
                    instanceName = DataFormats.MakePreferredSolutionItemName(instanceName);
                }

                // Ensure name is unique (on disk)
                var solutionItemName = pathHelper.GetUniqueName(instanceName, vsTemplate, unfoldResolver.ParentItem);

                //TODO: We need to close the existing solution (if any) if template is a ProjectGroup
                // if (vsTemplate.Type == VsTemplateType.ProjectGroup).
                // Otherwise this will fail the unfold

                // Unfold the template
                var generatedItem = template.Unfold(unfoldResolver.ResolveExtension(solutionItemName), unfoldResolver.ParentItem);
                eventScope.Dispose();

                // Perhaps the template unfolded multiple items and none was identifed as the primary
                // (such as in a multi-item item template, with no non-fixed named items)
                if (generatedItem != null)
                {
                    // Prompt user to update element instance name (on name collision) if he is synching names,
                    // it doesn't make sense to correlate them otherwise
                    if (settings.SyncName)
                    {
                        if (!instanceName.Equals(solutionItemName, StringComparison.OrdinalIgnoreCase))
                        {
                            if (serviceProvider != null)
                            {
                                var shellService = serviceProvider.GetService <IVsUIShell>();
                                if (shellService != null)
                                {
                                    var result = shellService.ShowPrompt(
                                        Resources.UnfoldVsTemplateCommand_PromptToSyncNameTitle,
                                        string.Format(CultureInfo.CurrentCulture,
                                                      Resources.UnfoldVsTemplateCommand_PromptToSyncName,
                                                      instanceName, solutionItemName));
                                    if (result)
                                    {
                                        owner.InstanceName = solutionItemName;
                                    }
                                }
                                else
                                {
                                    owner.InstanceName = solutionItemName;
                                }
                            }
                            else
                            {
                                owner.InstanceName = solutionItemName;
                            }
                        }
                    }

                    if (!fromWizard)
                    {
                        tracer.Info(
                            Resources.UnfoldVsTemplateCommand_TraceAddReference, owner);

                        SolutionArtifactLinkReference
                        .AddReference(owner, uriService.CreateUri(generatedItem))
                        .Tag = BindingSerializer.Serialize(new ReferenceTag
                        {
                            Tag            = settings.Tag ?? string.Empty,
                            SyncNames      = settings.SyncName,
                            TargetFileName = settings.TargetFileName
                        });
                    }
                }
                return(generatedItem);
            }
            catch (WizardBackoutException) //cancel the unfold if wizard backout
            {
                tracer.Info(
                    Resources.UnfoldVsTemplateCommand_TraceWizardCancelled);
                owner.Delete();
                eventScope.Dispose();
                return(null);
            }
            catch (COMException comEx)
            {
                tracer.Error(
                    comEx, Resources.UnfoldVsTemplateCommand_TraceCOMException, owner.InstanceName, settings.TemplateUri);
                owner.Delete();
                eventScope.Dispose();
                throw;
            }
            catch (OperationCanceledException)
            {
                // This exception can be throw explicitly by author code
                // that wishes to cancel execution, with a friendly user
                // message, so we can pass this on as-is.
                throw;
            }
            catch (Exception ex) //cancel the unfold if another unexpected exception happened
            {
                tracer.Info(
                    Resources.UnfoldVsTemplateCommand_TraceUnexpectedException, owner.InstanceName, settings.TemplateUri);
                owner.Delete();
                eventScope.Dispose();

                throw new OperationCanceledException(string.Format(
                                                         CultureInfo.CurrentCulture,
                                                         Resources.UnfoldVsTemplateCommand_UnexpectedException,
                                                         settings.TemplateUri, owner.InstanceName, ex.Message));
            }
        }
        /// <summary>
        /// Processes the document
        /// </summary>
        /// <param name="document">The document to process.</param>
        public void ProcessSchema(XDocument document)
        {
            Guard.NotNull(() => document, document);

            this.IsModified = false;

            // Locate all <commandSettings> that have a 'typeId="NuPattern.Library.Commands.AggregatorCommand"'
            var commandSettings = document.Descendants(CommandSettingsElementName)
                                  .Where(cs => cs.Attribute(CommandSettingsTypeIdName) != null && cs.Attribute(CommandSettingsTypeIdName).Value == typeof(AggregatorCommand).FullName)
                                  .Distinct();

            if (commandSettings.Any())
            {
                tracer.Info(Resources.AggregatorCommandUpgradeProcessor_TraceDeserialize);

                // Enumerate each <commandSettings> element
                commandSettings.ForEach(cmdSettingsElement =>
                {
                    var id = cmdSettingsElement.Attribute(CommandSettingsIdName) != null ? cmdSettingsElement.Attribute(CommandSettingsIdName).Value : string.Empty;
                    var cmdPropsElement = cmdSettingsElement.Descendants(CommandSettingsPropertiesElementName).FirstOrDefault();
                    if (cmdPropsElement != null)
                    {
                        // Ensure we have a value for <properties>
                        var propertiesValue = cmdPropsElement.Value;
                        if (!string.IsNullOrEmpty(propertiesValue))
                        {
                            try
                            {
                                // Determine if has a serialized 'string' value, as opposed to a 'Collection<CommmandReference>'
                                var bindings = BindingSerializer.Deserialize <IEnumerable <IPropertyBindingSettings> >(propertiesValue);
                                if (bindings != null && bindings.Any())
                                {
                                    var existingBinding = bindings.FirstOrDefault(b => b.Name == Reflector <AggregatorCommand> .GetPropertyName(x => x.CommandReferenceList));
                                    if (existingBinding != null)
                                    {
                                        // Ensure there is a value
                                        if (!String.IsNullOrEmpty(existingBinding.Value))
                                        {
                                            //Ensure value is previous GUID list format
                                            if (Regex.IsMatch(existingBinding.Value, DelimitedListGuidRegEx))
                                            {
                                                // Read the delimitied array of strings
                                                var referenceStrings = existingBinding.Value.Split(new[] { CommandReferenceDelimitier }, StringSplitOptions.RemoveEmptyEntries);
                                                if (referenceStrings.Any())
                                                {
                                                    tracer.Info(Resources.AggregatorCommandUpgradeProcessor_TraceDeserializeCommandSettings, id);

                                                    // Convert to command references
                                                    var references = new List <CommandReference>();
                                                    referenceStrings.ForEach(rs =>
                                                    {
                                                        Guid refId;
                                                        if (Guid.TryParse(rs, out refId))
                                                        {
                                                            references.Add(new CommandReference(null)
                                                            {
                                                                CommandId = refId,
                                                            });
                                                        }
                                                    });

                                                    // Update value of <properties> element
                                                    var newBinding = new PropertyBindingSettings
                                                    {
                                                        Name  = Reflector <AggregatorCommand> .GetPropertyName(x => x.CommandReferenceList),
                                                        Value = BindingSerializer.Serialize(new Collection <CommandReference>(references)),
                                                    };
                                                    cmdPropsElement.SetValue(BindingSerializer.Serialize(new IPropertyBindingSettings[] { newBinding }));
                                                    this.IsModified = true;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            catch (BindingSerializationException)
                            {
                                // Ignore deserializaton exception
                            }
                        }
                    }
                });
            }
        }
Beispiel #21
0
 private void SaveValidationRules()
 {
     this.RawValidationRules = BindingSerializer.Serialize(this.validationSettings);
 }
Beispiel #22
0
        /// <summary>
        /// Runs the configured template data against the element.
        /// </summary>
        public override void Execute()
        {
            //tracer.TraceData(TraceEventType.Verbose, Resources.GenerateProductCodeCommand_StartedEvent, this.CurrentElement);

            // Note: we are NOT doing this.ValidateObject() thing here as we are setting the base class
            // properties ourselves. This will be a problem if this is automatically validated by the runtime.
            if (this.PatternManager != null)
            {
                if (!this.PatternManager.IsOpen)
                {
                    throw new InvalidOperationException(Resources.GenerateProductCodeCommand_PatternManagerNotOpen);
                }

                this.ModelFile = this.PatternManager.StoreFile;

                tracer.Info(
                    Resources.GenerateProductCodeCommand_TraceModelFile, this.ModelFile);
            }

            this.ModelElement = this.CurrentElement as ModelElement;

            Guard.NotNull(() => this.Settings, this.Settings);

            IItemContainer existingArtifact       = null;
            var            originalTargetFilename = this.TargetFileName;

            // If there is an existing artifact that we can resolve, override the configured settings and
            // reuse that one instead.
            var existingArtifactLink = SolutionArtifactLinkReference
                                       .GetReferenceValues(this.CurrentElement, r => GetIdFromReferenceTag(r) == this.Settings.Id)
                                       .FirstOrDefault();

            if (existingArtifactLink != null)
            {
                // Try to locate the existing solution item
                existingArtifact = this.UriService.TryResolveUri <IItemContainer>(existingArtifactLink);
                if (existingArtifact != null)
                {
                    // If the item exists, then we'll override the configured paths to point
                    // to the located element.
                    this.TargetPath     = existingArtifact.Parent.GetLogicalPath();
                    this.TargetFileName = existingArtifact.Name;

                    tracer.Verbose(
                        Resources.GenerateProductCodeCommand_Trace_ExistingArtifactUsed, existingArtifact.GetLogicalPath());
                }
                else
                {
                    // Otherwise, we'll use the configured path and filename.
                    tracer.Info(Resources.GenerateProductCodeCommand_Trace_ExistingArtifactUriNotFound, existingArtifactLink);
                }
            }

            //Re-evaluate all properties of current element
            RefreshProvidedValues();

            // Generate the file according to current settings and porperty values
            base.Execute();

            //Restore targetfilename
            if (existingArtifactLink != null)
            {
                if (existingArtifact != null)
                {
                    this.TargetFileName = originalTargetFilename;
                }
            }

            // If an item was generated
            if (this.GeneratedItem != null)
            {
                tracer.Verbose(
                    Resources.GenerateProductCodeCommand_Trace_GeneratedArtifact, this.GeneratedItem.GetLogicalPath());

                // Add new artifact link
                if (existingArtifactLink == null)
                {
                    // Add the new link and set the tag to our settings, so that we know
                    // it's the link generated by this command instance.
                    var newLink = this.UriService.CreateUri(this.GeneratedItem);

                    SolutionArtifactLinkReference
                    .AddReference(this.CurrentElement, newLink)
                    .Tag = BindingSerializer.Serialize(new ReferenceTag
                    {
                        Tag            = this.Tag ?? string.Empty,
                        SyncNames      = this.SyncName,
                        TargetFileName = this.TargetFileName,
                        Id             = this.Settings.Id
                    });

                    tracer.Verbose(
                        Resources.GenerateProductCodeCommand_Trace_NewArtifactLinkAdded, newLink);
                }
                else
                {
                    // Update existing artifact link

                    // If existing artifact was not found (perhaps its now deleted), a new
                    // link will be generated for the newly added item, so we must update the existing reference.
                    if (existingArtifact == null)
                    {
                        var newLink = this.UriService.CreateUri(this.GeneratedItem);

                        var reference = this.CurrentElement.References.First(r => GetIdFromReferenceTag(r) == Settings.Id);
                        SolutionArtifactLinkReference.SetReference(reference, newLink);

                        tracer.Verbose(
                            Resources.GenerateProductCodeCommand_Trace_UpdatedExistingArtifactLink, newLink);
                    }
                    else
                    {
                        // Existing artifact found
                        if (this.SyncName)
                        {
                            // Must rename the file to the new filename, (paths remains the same)

                            // Recalculate the filename
                            var resolver = new PathResolver(this.ModelElement, this.UriService, this.TargetPath,
                                                            (!string.IsNullOrEmpty(this.TargetFileName)) ? this.TargetFileName : ((IProductElement)this.ModelElement).InstanceName);
                            resolver.Resolve();

                            var proposedItemName = resolver.FileName;
                            if (this.SanitizeName)
                            {
                                proposedItemName = SanitizeItemName(proposedItemName);
                            }

                            // Rename file if different name now (taking into account whether extension is specified in TargetFileName or not)
                            if (!proposedItemName.Equals(
                                    (string.IsNullOrEmpty(Path.GetExtension(proposedItemName)))
                                    ? Path.GetFileNameWithoutExtension(this.GeneratedItem.Name)
                                    : this.GeneratedItem.Name,
                                    StringComparison.OrdinalIgnoreCase))
                            {
                                tracer.Info(
                                    Resources.GenerateProductCodeCommand_TraceRenameSolutionItem, this.GeneratedItem.Name, proposedItemName);

                                var uiService   = (IVsUIShell)this.ServiceProvider.GetService(typeof(IVsUIShell));
                                var newItemName = this.GeneratedItem.Rename(proposedItemName, true, uiService);

                                tracer.Info(
                                    Resources.GenerateProductCodeCommand_TraceSolutionItemRenamed, this.GeneratedItem.Name, newItemName);
                            }
                        }
                    }
                }
            }
        }
Beispiel #23
0
 private void SaveValue()
 {
     this.rawValueSetter(BindingSerializer.Serialize(this.valueProviderSettings));
 }