public void LoadDuplicateReferencesThrow()
        {
            IAssetReferenceService service = (IAssetReferenceService)package.GetService(typeof(IAssetReferenceService), true);

            service.Add(new MockObjects.MockReference("AddService", "/Solution/Services"), true);
            service.Add(new MockObjects.MockReference("AddService", "/Solution/Services"), true);
        }
        /// <summary>
        /// Adds the template reference to the IAssetReferenceService
        /// </summary>
        public override void Execute()
        {
            DTE vs = GetService <DTE>(true);
            IAssetReferenceService referenceService = GetService <IAssetReferenceService>(true);
            object item = DteHelper.GetTarget(vs);

            if (item == null)
            {
                throw new InvalidOperationException("There is no valid target to reference the template.");
            }

            if (item is Project)
            {
                addedReference = new ProjectReference(recipeName, (Project)item);
            }
            else if (item is Solution)
            {
                addedReference = new SolutionReference(recipeName, (Solution)item);
            }
            else if (item is ProjectItem)
            {
                addedReference = new ProjectItemReference(recipeName, (ProjectItem)item);
            }
            else
            {
                throw new NotSupportedException("Current selection is unsupported.");
            }

            referenceService.Add(addedReference);

            MessageBox.Show("The new reference was successfully added.", "New Reference",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Пример #3
0
        public bool Test()
        {
            try
            {
                EnvDTE.DTE             dte = (EnvDTE.DTE)GetService(typeof(EnvDTE.DTE));
                IAssetReferenceService referenceService = (IAssetReferenceService)GetService(typeof(IAssetReferenceService));
                object item = DteHelper.GetTarget(dte);
                //MessageBox.Show("Coneccion exitosa.- a " + _Server.Information.Product.ToString(),  Fwk.GuidPk.Properties.Resources.ProductTitle);


                //templateFilename = new Uri(templateFilename).LocalPath;
                StringBuilder items = new StringBuilder();
                //VsBoundReference vsTarget = null;
                if (item is Project)
                {
                    foreach (ProjectItem i in ((Project)item).ProjectItems)
                    {
                        items.AppendLine(i.Name);
                    }
                    //vsTarget = new ProjectReference(templateFilename, (Project)item);
                }

                MessageBox.Show(items.ToString(), Fwk.GuidPk.Properties.Resources.ProductTitle);
            }
            catch (Exception ex)
            {
                MessageBox.Show(Fwk.CodeGenerator.HelperFunctions.GetAllMessageException(ex), Fwk.GuidPk.Properties.Resources.ProductTitle);
                return(false);
            }
            return(true);
        }
Пример #4
0
        /// <summary>
        /// Creates the unbound reference and registers
        /// the reference with the Recipe Framework
        /// </summary>
        public override void Execute()
        {
            ITypeResolutionService typeLoader = GetService <ITypeResolutionService>(true);
            Type assetType = typeLoader.GetType(this.referenceType, true);

            if (!typeof(IUnboundAssetReference).IsAssignableFrom(assetType))
            {
                throw new ArgumentException(String.Format(
                                                System.Globalization.CultureInfo.CurrentCulture,
                                                Properties.Resources.CreateUnboundReferenceAction_WrongType,
                                                assetType));
            }

            ConstructorInfo ctor = assetType.GetConstructor(new Type[] { typeof(string) });

            if (ctor == null)
            {
                throw new NotSupportedException(String.Format(
                                                    System.Globalization.CultureInfo.CurrentCulture,
                                                    Properties.Resources.CreateUnboundReferenceAction_UnsupportedConstructor,
                                                    assetType));
            }

            reference = (IAssetReference)ctor.Invoke(new object[] { this.assetName });
            if (reference is IAttributesConfigurable)
            {
                ((IAttributesConfigurable)reference).Configure(this.attributes);
            }
            IAssetReferenceService service = GetService <IAssetReferenceService>(true);

            service.Add(reference);
        }
Пример #5
0
 private void OnDeleteRecipe(object sender, EventArgs e)
 {
     if (this.lstRecipes.SelectedItems.Count != 1)
     {
         return;
     }
     if (MessageBox.Show(this, Configuration.Resources.PackageManager_ConfirmDeleteReference,
                         this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
     {
         try
         {
             ReferenceInfo          refinfo = (ReferenceInfo)lstRecipes.SelectedItems[0].Tag;
             IAssetReferenceService refsvc  = (IAssetReferenceService)
                                              ServiceHelper.GetService(refinfo.Reference, typeof(IAssetReferenceService));
             refsvc.Remove(refinfo.Reference);
             this.lstRecipes.Items.Remove(lstRecipes.SelectedItems[0]);
             if (this.lstRecipes.Items.Count != 0)
             {
                 this.lstRecipes.SelectedIndices.Clear();
                 this.lstRecipes.SelectedIndices.Add(0);
             }
             else
             {
                 this.txtDescription.Clear();
             }
         }
         catch (Exception ex)
         {
             ErrorHelper.Show((IUIService)GetService(typeof(IUIService)), ex);
         }
     }
 }
 /// <summary>
 /// Removes the previously added reference, if it was created
 /// </summary>
 public override void Undo()
 {
     if (addedReference != null)
     {
         IAssetReferenceService referenceService = GetService <IAssetReferenceService>(true);
         referenceService.Remove(addedReference);
     }
 }
Пример #7
0
        public override void Execute()
        {
            DTE vs = GetService <DTE>(true);
            IAssetReferenceService referenceService = GetService <IAssetReferenceService>(true);
            object item = DteHelper.GetTarget(vs);

            CreateFolderAndFiles(Project);
        }
Пример #8
0
 /// <summary>
 /// Removes the previously added reference, if it was created
 /// </summary>
 public override void Undo()
 {
     if (newReference != null)
     {
         IAssetReferenceService referenceService = (IAssetReferenceService)GetService(typeof(IAssetReferenceService));
         referenceService.Remove(newReference);
     }
 }
Пример #9
0
 protected override void OnSited()
 {
     base.OnSited();
     this.referenceService = (IAssetReferenceService)
                             GetService(typeof(IAssetReferenceService), true);
     ReBuildTaskEnumerator();
     RegisterChangeEvent(true);
     cookie = Register();
 }
Пример #10
0
        /// <summary>
        /// Removes the previously added reference
        /// </summary>
        public override void Undo()
        {
            IAssetReferenceService service = GetService <IAssetReferenceService>(true);

            if (reference != null)
            {
                service.Remove(reference);
                reference = null;
            }
        }
        /// <summary>
        /// <seealso cref="IAction.Undo"/>
        /// </summary>
        public override void Undo()
        {
            IAssetReferenceService referenceService = GetService <IAssetReferenceService>(true);

            foreach (IAssetReference asset in this.referencesAdded)
            {
                referenceService.Remove(asset);
            }
            referencesAdded.Clear();
        }
Пример #12
0
        /// <summary>
        /// Adds the template reference to the IAssetReferenceService
        /// </summary>
        public override void Execute()
        {
            EnvDTE.DTE             dte = (EnvDTE.DTE)GetService(typeof(EnvDTE.DTE));
            IAssetReferenceService referenceService = (IAssetReferenceService)GetService(typeof(IAssetReferenceService));
            object item = DteHelper.GetTarget(dte);



            if (item == null)
            {
                MessageBox.Show("There is no valid target to reference the template");
                return;
            }
            templateFilename = new Uri(templateFilename).LocalPath;

            VsBoundReference vsTarget = null;

            if (item is Project)
            {
                vsTarget = new ProjectReference(templateFilename, (Project)item);
            }
            else if (item is Solution)
            {
                vsTarget = new SolutionReference(templateFilename, (Solution)item);
            }
            else if (item is ProjectItem)
            {
                vsTarget = new ProjectItemReference(templateFilename, (ProjectItem)item);
            }
            else if (item is EnvDTE80.SolutionFolder)
            {
                vsTarget = new ProjectReference(templateFilename, ((EnvDTE80.SolutionFolder)item).Parent);
            }
            if (item == null || vsTarget == null)
            {
                MessageBox.Show(string.Format(
                                    CultureInfo.CurrentCulture,
                                    "Target {0} specified for reference to asset {1} doesn't exist.",
                                    "target", templateFilename));
                return;
            }
            if (!File.Exists(templateFilename) || !templateFilename.EndsWith(".vstemplate", StringComparison.InvariantCultureIgnoreCase))
            {
                MessageBox.Show(string.Format(
                                    CultureInfo.CurrentCulture,
                                    "The filename specified for the template \"{0}\" does not exist.",
                                    templateFilename));
                return;
            }
            newReference = new BoundTemplateReference(templateFilename, vsTarget);
            referenceService.Add(newReference);
            MessageBox.Show("The new reference was successfully added", "New Reference",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Пример #13
0
            public override void Execute()
            {
                IAssetReferenceService refsvc = (IAssetReferenceService)
                                                GetService(typeof(IAssetReferenceService));

                refsvc.Add(new MockObjects.MockReference("ValidateSolution", "/"));
                refsvc.Add(new MockObjects.MockReference("PublishServices", "/Services/Accounting"));
                refsvc.Add(new MyUnboundRecipeReference("AddXmlSerializationClass"));

                Flags[0] = true;
            }
Пример #14
0
        protected override void OnExec()
        {
            IAssetReferenceService referenceservice = ServiceProvider.GetService <IAssetReferenceService>(true);
            IAssetReference        reference        = referenceservice.GetReferenceFor(recipe.Name, GetTarget());

            if (reference == null)
            {
                throw new ArgumentNullException("reference");
            }
            reference.Execute();
        }
        public void IndexedByItem()
        {
            IAssetReferenceService service = (IAssetReferenceService)package.GetService(typeof(IAssetReferenceService), true);

            service.Add(new MockObjects.MockReference("AddService", "/Solution/Services"));
            service.Add(new MockObjects.MockReference("AddService", "/Solution/Services/Accounting"));
            service.Add(new MockObjects.MockReference("AddService", "/Solution/BusinessLayer"));
            service.Add(new MockObjects.MockReference("AddBusinessAction", "/Solution/BusinessLayer"));

            Assert.AreEqual(service.Find(typeof(IndexerBoundTarget), "/Solution/Services/Accounting").Length, 1);
            Assert.AreEqual(service.Find(typeof(IndexerBoundTarget), "/Solution/BusinessLayer").Length, 2);
        }
Пример #16
0
        protected override void OnSited()
        {
            base.OnSited();

            //Setup TaskList provider
            taskList = new RecipeTaskProvider(new Guid(guidancePackage.Configuration.Guid));
            Add(taskList);

            IAssetReferenceService referenceService = GetService <IAssetReferenceService>();

            referenceService.AddIndexer(typeof(IndexerBoundAssetParent), new IndexerBoundAssetParent());

            // Initialize all commands according to loaded configuration.
            InitializeCommands();
        }
Пример #17
0
        protected override void OnSited()
        {
            base.OnSited();
            IAssetReferenceService referenceService = (IAssetReferenceService)
                                                      this.GetService(typeof(IAssetReferenceService), true);

            foreach (IAssetReference reference in referenceService.GetAll())
            {
                if (reference is RecipeReference && reference is IBoundAssetReference)
                {
                    RecipeTaskItem recipeTaskItem = new RecipeTaskItem((RecipeReference)reference);
                    this.Add(recipeTaskItem, reference.Key);
                }
            }
            ((IVsEnumTaskItems)this).Reset();
        }
Пример #18
0
            public override void Execute()
            {
                if (OldReference == null)
                {
                    return;
                }
                IRecipeManagerService manager = (IRecipeManagerService)
                                                ServiceHelper.GetService(this, typeof(IRecipeManagerService));
                // Add the references to the target package.
                GuidancePackage        package          = manager.GetPackage(targetPackage);
                IAssetReferenceService referenceService = (IAssetReferenceService)
                                                          ServiceHelper.GetService(package, typeof(IAssetReferenceService), this);
                IPersistenceService persist = (IPersistenceService)
                                              ServiceHelper.GetService(this, typeof(IPersistenceService));

                try
                {
                    IDictionary state = persist.LoadState(package.Configuration.Name, OldReference);
                    if ((target != null) && !(target is DummyDTE.EmptyDteElement))
                    {
                        //We have to get the real object Project for case of Solution Folder
                        object realTarget = target;
                        if (target is SolutionFolder)
                        {
                            realTarget = ((SolutionFolder)target).Parent;
                        }

                        if (OldReference is VsBoundReference)
                        {
                            ((VsBoundReference)OldReference).SetTarget(realTarget);
                        }
                        else if (OldReference is BoundTemplateReference)
                        {
                            ((BoundTemplateReference)OldReference).BoundReference.SetTarget(realTarget);
                        }
                        referenceService.Add(OldReference, state);
                    }
                }
                catch (Exception ex)
                {
                    if (OldReference != null)
                    {
                        referenceService.Remove(OldReference);
                    }
                    ErrorHelper.Show(this.Site, ex);
                }
            }
Пример #19
0
        /// <summary>
        /// Adds the template reference to the IAssetReferenceService
        /// </summary>
        public override void Execute()
        {
            DTE vs = GetService <DTE>(true);
            IAssetReferenceService referenceService = GetService <IAssetReferenceService>(true);
            object item = DteHelper.GetTarget(vs);

            CreateFolderAndFiles(Project);



            if (item == null)
            {
                throw new InvalidOperationException("There is no valid target to create any DAC .");
            }

            if (item is EnvDTE.Project)
            {
                EnvDTE.Project p = (EnvDTE.Project)item;

                // p.ProjectItems.AddFromFile();
            }
            else if (item is Solution)
            {
                // addedReference = new SolutionReference(recipeName, (Solution)item);
            }
            else if (item is ProjectItem)
            {
                //  addedReference = new ProjectItemReference(recipeName, (ProjectItem)item);
            }
            else
            {
                throw new NotSupportedException("Current selection is unsupported.");
            }

            //referenceService.Add(addedReference);

            //MessageBox.Show("The new reference was successfully added.", "New Reference",
            //    MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Пример #20
0
        protected override void OnQueryStatus()
        {
            IAssetReferenceService referenceservice = ServiceProvider.GetService <IAssetReferenceService>(true);

            Visible = referenceservice.IsAssetEnabledFor(recipe.Name, GetTarget());
        }
Пример #21
0
        private void LoadReferences()
        {
            this.SuspendLayout();
            this.imgImages.Images.Clear();
            this.lstRecipes.Items.Clear();
            GuidancePackage[] Packages = base.RecipeManagerService.GetEnabledPackages();

            ArrayList images = new ArrayList();
            // Add the two default images.
            ToolboxBitmapAttribute boundattr = new ToolboxBitmapAttribute(typeof(IBoundAssetReference));
            Image boundimg = boundattr.GetImage(boundattr);

            this.imgImages.Images.Add(boundimg);
            // Add gray version
            this.imgImages.Images.Add(ConvertToGrayscale(boundimg));
            ToolboxBitmapAttribute unboundattr = new ToolboxBitmapAttribute(typeof(IUnboundAssetReference));
            Image unboundimg = unboundattr.GetImage(unboundattr);

            this.imgImages.Images.Add(unboundimg);
            // Add gray version
            this.imgImages.Images.Add(ConvertToGrayscale(unboundimg));

            Hashtable groups = new Hashtable();
            ArrayList items  = new ArrayList();

            // WORKAROUND: fixed for VSWhidbey "by design" bug #440390. Now we load items and groups
            // first, then sort everything manually, and finally add stuff to the control.
            // Commented lines should be documented when feature is fixed.
            foreach (GuidancePackage Package in Packages)
            {
                IAssetReferenceService refservice = (IAssetReferenceService)
                                                    Package.GetService(typeof(IAssetReferenceService), true);
                IConfigurationService configService =
                    (IConfigurationService)Package.GetService(typeof(IConfigurationService), true);

                foreach (IAssetReference reference in refservice.GetAll())
                {
                    ReferenceInfo info = new ReferenceInfo(reference);

                    #region Determine image

                    int imageindex = images.IndexOf(reference.GetType());
                    // Determine image to show.
                    if (imageindex == -1)
                    {
                        ToolboxBitmapAttribute bmp = (ToolboxBitmapAttribute)Attribute.GetCustomAttribute(
                            reference.GetType(), typeof(ToolboxBitmapAttribute), true);
                        if (bmp == null)
                        {
                            // Use default attributes.
                            if (reference is IBoundAssetReference)
                            {
                                imageindex = 0;
                            }
                            else
                            {
                                imageindex = 2;
                            }
                            if (!info.IsEnabled)
                            {
                                imageindex++;
                            }
                        }
                        else
                        {
                            imageindex = this.imgImages.Images.Count;
                            Image newimg = bmp.GetImage(reference);
                            if (info.IsEnabled)
                            {
                                this.imgImages.Images.Add(newimg);
                            }
                            else
                            {
                                // Add gray version.
                                this.imgImages.Images.Add(ConvertToGrayscale(newimg));
                            }
                            images.Add(reference.GetType());
                        }
                    }
                    else
                    {
                        // Account for the 4 built-in images.
                        imageindex = imageindex + 4;
                    }

                    #endregion Determine image

                    #region Determine group

                    // Bug: Should we fix this?
                    // We should get custom attributes instead of a single attr.
                    // The reference could override the category
                    //CategoryAttribute category = (CategoryAttribute)Attribute.GetCustomAttribute(
                    //    reference.GetType(), typeof(CategoryAttribute), true);
                    CategoryAttribute category = (CategoryAttribute)Attribute.GetCustomAttributes(
                        reference.GetType(), typeof(CategoryAttribute), true).First();
                    // ListViewGroup categorygroup = this.lstRecipes.Groups[category.Category];
                    ListViewGroup categorygroup = (ListViewGroup)groups[category.Category];
                    if (categorygroup == null)
                    {
                        //categorygroup = this.lstRecipes.Groups.Add(category.Category, category.Category);
                        categorygroup = new ListViewGroup(category.Category, category.Category);
                        groups.Add(category.Category, categorygroup);
                    }

                    #endregion Determine group

                    Config.Recipe recipe = null;
                    if (reference is RecipeReference)
                    {
                        recipe = configService.CurrentPackage[reference.AssetName];
                    }

                    string[]  subitems = new string[3];
                    string    errors   = string.Empty;
                    Exception ex       = null;
                    try
                    {
                        subitems[0] = reference.Caption;
                    }
                    catch (Exception e)
                    {
                        if (recipe != null)
                        {
                            subitems[0] = recipe.Caption;
                        }
                        ex     = e;
                        errors = "Caption";
                    }
                    try
                    {
                        subitems[1] = reference.AppliesTo;
                    }
                    catch (Exception e)
                    {
                        subitems[1] = Configuration.Resources.Reference_AppliesToThrew;
                        if (ex == null)
                        {
                            ex = e;
                        }
                        if (!string.IsNullOrEmpty(errors))
                        {
                            errors += ", ";
                        }
                        errors += "AppliesTo";
                    }
                    subitems[2] = Package.Configuration.Caption;
                    ListViewItem item = new ListViewItem(subitems, imageindex);
                    item.Tag   = info;
                    item.Group = categorygroup;
                    items.Add(item);
                    if (ex != null)
                    {
                        ErrorHelper.Show((IUIService)GetService(typeof(IUIService)), new RecipeExecutionException(reference.AssetName,
                                                                                                                  string.Format(CultureInfo.CurrentCulture,
                                                                                                                                Configuration.Resources.Reference_InvalidAttributes,
                                                                                                                                errors), ex));
                    }
                }
            }

            // Sort everything.
            ListViewGroup[] lvgroups = new ListViewGroup[groups.Count];
            groups.Values.CopyTo(lvgroups, 0);
            items.Sort(new ListViewItemSortComparer());
            Array.Sort(lvgroups, new GroupSortComparer());

            this.lstRecipes.Groups.AddRange(lvgroups);
            this.lstRecipes.Items.AddRange((ListViewItem[])items.ToArray(typeof(ListViewItem)));

            this.lstRecipes.Invalidate();
            this.ResumeLayout();

            if (this.lstRecipes.Items.Count > 0)
            {
                splitter.Panel1.Focus();
                splitter.Panel1.Select();
                ((ListViewItem)items[0]).Selected = true;
                this.lstRecipes.Focus();
                this.lstRecipes.Select();
            }
            else
            {
                this.txtDescription.Text = String.Empty;
            }
        }
Пример #22
0
        /// <summary>
        /// It creates a dynamic recipe in order to show a dialog that asks the user
        /// to introduce new targets for all dangling references
        /// </summary>
        private void PerformRestore()
        {
            if (referencesToFix.Count == 0)
            {
                return;
            }

            #region Asking to the user

            string msg;
            string details;
            BuildMessage(out msg, out details);

            if (ErrorHelper.Ask(Properties.Resources.ReferenceRestoreService_StartTitle, msg, details,
                                Properties.Resources.ReferenceRestoreService_ResolveButton,
                                Properties.Resources.ReferenceRestoreService_RemoveButton)
                == System.Windows.Forms.DialogResult.No)
            {
                IAssetReferenceService referenceService = null;
                GuidancePackage        lastPackage      = null;
                foreach (FixupReference lostReference in referencesToFix)
                {
                    if (lastPackage != lostReference.OwningPackage)
                    {
                        referenceService =
                            (IAssetReferenceService)ServiceHelper.GetService(lostReference.OwningPackage,
                                                                             typeof(IAssetReferenceService), this);
                    }
                    referenceService.Remove(lostReference.OldReference);
                }
                return;
            }

            #endregion

            // The pending FixupReferences we added to the list will be ordered
            // by the template they were in, so we can just build a wizard page
            // for each group of X of fields for fixup.
            int maxfields = 5;

            // Used to create configuration attributes
            XmlDocument xmlfactory = new XmlDocument();

            // Create a package dynamically.
            Config.GuidancePackage package = CreateDynamicPackage();

            Config.Recipe recipe;
            ArrayList     arguments;
            ArrayList     actions;
            CreateDynamicRecipe(package, out recipe, out arguments, out actions);

            Page      lastpage          = null;
            ArrayList pages             = new ArrayList();
            ArrayList fields            = new ArrayList(maxfields);
            Hashtable argumentNamesUsed = new Hashtable(7);

            int nPages = referencesToFix.Count / maxfields;
            if ((referencesToFix.Count % maxfields) != 0)
            {
                nPages++;
            }

            Hashtable referenceDictionary = CreateFixupPages(maxfields, xmlfactory,
                                                             arguments, actions, ref lastpage, pages, ref fields, nPages);

            lastpage.Fields = new Field[fields.Count];
            fields.CopyTo(lastpage.Fields, 0);

            recipe.Arguments = new Config.Argument[arguments.Count];
            arguments.CopyTo(recipe.Arguments, 0);
            if (recipe.Actions == null)
            {
                recipe.Actions = new Config.RecipeActions();
            }
            recipe.Actions.Action = new Config.Action[actions.Count];
            actions.CopyTo(recipe.Actions.Action, 0);

            Wizard wizard = new Wizard();
            wizard.SchemaVersion = "1.0";
            wizard.Pages         = new Page[pages.Count];
            pages.CopyTo(wizard.Pages, 0);

            // Get the wizard in XML form so that it's passed to the recipe execution.
            SerializeToAny(recipe, wizard);

            EnableAndExecute(package, referenceDictionary);
        }
Пример #23
0
        private ExecutionResult Execute(string recipe, IAssetReference reference, IDictionary arguments)
        {
            if (recipe == null)
            {
                throw new ArgumentNullException("recipe");
            }
            ThrowIfAlreadyExecutingRecipe();
            Config.Recipe config = ThrowIfRecipeNotConfigured(recipe);

            ReferenceService referenceService = null;

            try
            {
                string appliesTo = GetReferenceAppliesToOrErrorMessage(reference);
                this.TraceInformation(Properties.Resources.Recipe_StartingExecution, recipe,
                                      reference != null ? String.Format(Properties.Resources.Recipe_ReferenceApplied, appliesTo) : "");

                // This "parent" loader service is the one we created in OnSited that
                // wraps the one provided by the recipe manager itself, and adds resolution
                // relative to the package assembly location.
                ITypeResolutionService loader = GetService <ITypeResolutionService>(true);

                // Create the recipe from the configuration.
                currentRecipe    = new Recipe(config);
                currentReference = reference;

                // Setup the alias resolution "gateway" loader service.
                // This resolves aliases defined for the recipe only.
                // This service will go away together with the recipe.
                currentRecipe.AddService(typeof(ITypeResolutionService), new AliasResolutionService(
                                             config.TypeAliasesByName, loader));

                bool isPersisted;
                IPersistenceService persistenceService;
                arguments = LoadPersitedState(reference, arguments, out isPersisted, out persistenceService);

                // Construct the dictionary service. We don't pass the arguments at this
                // point as we want to go over the process of setting each in turn, so they are validated.
                DictionaryService dictionarysvc = new DictionaryService(null);
                AddService(typeof(IDictionaryService), dictionarysvc);
                // Expose the IComponentChangeService implementation too.
                AddService(typeof(IComponentChangeService), dictionarysvc);

                if (arguments != null && arguments.Count > 0)
                {
                    bool shouldUpdateState = InitializeDictionaryService(arguments, dictionarysvc);

                    // Persist changes if appropriate.
                    if (isPersisted && shouldUpdateState)
                    {
                        persistenceService.SaveState(Configuration.Name, reference, arguments);
                    }
                }

                // Construct the dictionary service, passing the persisted state (or null) as well
                // as the arguments configuration.

                // Site and execute the recipe.
                Add(currentRecipe);
                referenceService = new ReferenceService();
                currentRecipe.AddService(typeof(IReferenceService), referenceService);

                bool allowsuspend = (reference != null && reference is IBoundAssetReference) ||
                                    (arguments != null);
                EnsureInitializeMetadataForCurrentRecipe();
                ExecutionResult result = currentRecipe.Execute(allowsuspend);
                this.TraceInformation(Properties.Resources.Recipe_ExecutionResult, result);

                if (result == ExecutionResult.Finish)
                {
                    // If recipe is not recurrent and it's a bound reference, remove it.
                    if (!currentRecipe.Configuration.Recurrent && reference is IBoundAssetReference)
                    {
                        IAssetReferenceService refsvc = GetService <IAssetReferenceService>(true);
                        refsvc.Remove(reference);
                        // Remove the persisted state.
                        persistenceService.RemoveState(Configuration.Name, reference);
                    }
                    // Fire the AfterRecipeExecution event
                    // note this will happen only when the recipe is finished (not suspend nor cancelled)
                    if (AfterRecipeExecution != null)
                    {
                        this.AfterRecipeExecution(this, new RecipeEventArgs(config, isExecutingRecipeFromTemplate));
                    }
                }

                return(result);
            }
            finally
            {
                #region Cleanup

                if (referenceService != null)
                {
                    currentRecipe.RemoveService(typeof(IReferenceService));
                }

                // Remove recipe from container.
                Remove(currentRecipe);
                // Remove services we added.
                RemoveService(typeof(IDictionaryService));
                RemoveService(typeof(IComponentChangeService));
                // Dispose and clean current variables.
                if (currentRecipe != null)
                {
                    currentRecipe.Dispose();
                    currentRecipe = null;
                }
                currentReference = null;

                #endregion Cleanup
                // Write a separator on the trace.
                this.TraceInformation(new string('-', 150));
            }
        }
        public void LoadNonReferenceComponent()
        {
            IAssetReferenceService service = (IAssetReferenceService)package.GetService(typeof(IAssetReferenceService), true);

            ((ComponentModel.ContainerComponent)service).Add(new System.ComponentModel.Component());
        }
Пример #25
0
        internal Dictionary <string, IAssetReference> GetAvailableRecipes(GuidancePackage guidancePackage)
        {
#if DEBUG
            DateTime startTime = DateTime.Now;
            Debug.WriteLine(String.Format("GetAvailableRecipes - Start time {0}.", startTime.ToLongTimeString()));
#endif
            Dictionary <string, IAssetReference> availableRecipes = new Dictionary <string, IAssetReference>();

            IAssetReferenceService referenceService = (IAssetReferenceService)guidancePackage.GetService(typeof(IAssetReferenceService), true);

            IOutputWindowService outputWindow = guidancePackage.GetService <IOutputWindowService>();


            IPersistenceService persistenceService = guidancePackage.GetService <IPersistenceService>();
            IAssetReference[]   allReferences      = null;

            allReferences = persistenceService.LoadReferences(guidancePackage.Configuration.Name);
#if DEBUG
            Debug.WriteLine(String.Format("GetAvailableRecipes - Probing using {0} references.", allReferences.Length));
#endif

            List <IUnboundAssetReference> unboundAssetReferenceList;
            List <IAssetReference>        otherAssetList;
            GetAssetLists(allReferences, out unboundAssetReferenceList, out otherAssetList);
#if DEBUG
            Debug.WriteLine(String.Format("GetAvailableRecipes - Probing using {0} unbound references.", unboundAssetReferenceList.Count));
            Debug.WriteLine(String.Format("GetAvailableRecipes - Probing using {0} other references.", otherAssetList.Count));
#endif
            List <object> allPossibleTargets = GetAllSolutionExplorerItems();
#if DEBUG
            Debug.WriteLine(String.Format("GetAvailableRecipes - Probing against {0} targets.", allPossibleTargets.Count));
#endif


            List <IUnboundAssetReference> unboundAssetReferenceWithNoTargetList = new List <IUnboundAssetReference>();
            foreach (IUnboundAssetReference unboundAssetReference in unboundAssetReferenceList)
            {
                bool referenceHasValidTarget = false;

                foreach (object item in allPossibleTargets)
                {
                    try
                    {
                        if (unboundAssetReference.IsEnabledFor(item))
                        {
                            referenceHasValidTarget = true;
                            break;
                        }
                    }
                    catch (Exception resolveReferenceException)
                    {
                        // The reference is not valid for this item.
                        outputWindow.Display(string.Format(Resources.Navigator_ReferenceThrowException, unboundAssetReference.AssetName, resolveReferenceException.Message));
                    }
                }
                if (!referenceHasValidTarget)
                {
                    unboundAssetReferenceWithNoTargetList.Add(unboundAssetReference);
                }
            }

#if DEBUG
            Debug.WriteLine(String.Format("GetAvailableRecipes - Removing {0} unbound referenes with no valid targets", unboundAssetReferenceWithNoTargetList.Count));
#endif
            // remove those unbound asset references that don't have a valid target in the whole solution
            foreach (IUnboundAssetReference reference in unboundAssetReferenceWithNoTargetList)
            {
                unboundAssetReferenceList.Remove(reference);
            }

            // add the unbound asset references that have a valid target
            foreach (IAssetReference reference in unboundAssetReferenceList)
            {
                otherAssetList.Add(reference);
            }

            foreach (IAssetReference reference in otherAssetList)
            {
                if (!availableRecipes.ContainsKey(reference.AssetName))
                {
                    availableRecipes.Add(reference.AssetName, reference);
                }
            }
#if DEBUG
            DateTime endTime = DateTime.Now;
            Debug.WriteLine(String.Format("GetAvailableRecipes - End time {0}.", endTime.ToLongTimeString()));
            TimeSpan ts = endTime.Subtract(startTime);
            Debug.WriteLine(String.Format("GetAvailableRecipes - Executed in {0} ms.", ts.Milliseconds));
#endif
            return(availableRecipes);
        }
        /// <summary>
        /// <seealso cref="IAction.Execute"/>
        /// </summary>
        public override void Execute()
        {
            if (Template.ExtensionData.References == null)
            {
                return;
            }
            int length = 0;

            if (Template.ExtensionData.References.RecipeReference != null)
            {
                length = Template.ExtensionData.References.RecipeReference.Length;
            }
            if (Template.ExtensionData.References.TemplateReference != null)
            {
                length += Template.ExtensionData.References.TemplateReference.Length;
            }

            referencesAdded = new ArrayList(length);

            IAssetReferenceService referenceService = GetService <IAssetReferenceService>(true);
            StringBuilder          errorList        = new StringBuilder();

            if (this.Template.ExtensionData.References.RecipeReference != null)
            {
                foreach (Microsoft.Practices.RecipeFramework.VisualStudio.VsTemplate.AssetReference reference in Template.ExtensionData.References.RecipeReference)
                {
                    Hashtable hashInitialState;
                    try
                    {
                        hashInitialState = ReadReferenceState(reference.InitialState);
                    }
                    catch (Exception ex)
                    {
                        errorList.AppendFormat(
                            CultureInfo.CurrentCulture,
                            Properties.Resources.Templates_InitialStateError,
                            reference.Name,
                            DteHelper.ReplaceParameters(reference.Target, this.ReplacementDictionary),
                            ex);
                        // Don't add the offending reference.
                        continue;
                    }
                    VsBoundReference vsTarget = this.GetReferenceTarget(reference.Target, reference.Name);
                    if (vsTarget != null)
                    {
                        try
                        {
                            referenceService.Add(vsTarget, hashInitialState);
                            referencesAdded.Add(vsTarget);
                        }
                        catch (Exception ex)
                        {
                            errorList.AppendFormat(ex.Message).AppendLine();
                        }
                    }
                    else
                    {
                        errorList.AppendFormat(
                            CultureInfo.CurrentCulture,
                            Properties.Resources.Templates_CantFindTarget,
                            DteHelper.ReplaceParameters(reference.Target, this.ReplacementDictionary),
                            reference.Name).AppendLine();
                    }
                }
            }
            if (this.Item != null && this.Template.ExtensionData.References.TemplateReference != null)
            {
                throw new ArgumentException(String.Format(
                                                CultureInfo.CurrentCulture,
                                                Properties.Resources.Templates_ItemCantHaveTemplates,
                                                Path.GetFileName(this.Template.FileName)),
                                            "TemplateReference");
            }
            if (this.Template.ExtensionData.References.TemplateReference != null)
            {
                string basePath = this.Package.BasePath;
                foreach (VsTemplate.AssetReference reference in this.Template.ExtensionData.References.TemplateReference)
                {
                    Hashtable hashInitialState;
                    try
                    {
                        hashInitialState = ReadReferenceState(reference.InitialState);
                    }
                    catch (Exception ex)
                    {
                        errorList.AppendFormat(
                            CultureInfo.CurrentCulture,
                            Properties.Resources.Templates_InitialStateError,
                            reference.Name, reference.Target, ex);
                        continue;
                    }
                    string templateFileName = basePath + @"\Templates\" + reference.Name;
                    templateFileName = new CompatibleUri(templateFileName).LocalPath;
                    // Normalize path as it may contain double back slashes which usually shouldn't hurt but will break some of the checkings GAX does against registry keys
                    // this is necessary due to Uri.LocalPath behaving differently under Vista -- reported as VS bug #
                    //templateFileName = WinXpUriLocalPathBehavior(
                    //templateFileName = templateFileName.Replace(@"\\", @"\");
                    VsBoundReference vsTarget = this.GetReferenceTarget(reference.Target, templateFileName);
                    if (File.Exists(templateFileName) && templateFileName.EndsWith(".vstemplate", StringComparison.InvariantCultureIgnoreCase) && vsTarget != null)
                    {
                        BoundTemplateReference tmpref = new BoundTemplateReference(templateFileName, vsTarget);
                        referencesAdded.Add(tmpref);
                        referenceService.Add(tmpref, hashInitialState);
                    }
                    else if (vsTarget == null)
                    {
                        errorList.Append(String.Format(
                                             CultureInfo.CurrentCulture,
                                             Properties.Resources.Templates_CantFindTarget,
                                             DteHelper.ReplaceParameters(reference.Target, this.ReplacementDictionary),
                                             reference.Name));
                        errorList.Append(Environment.NewLine);
                    }
                    else
                    {
                        errorList.Append(String.Format(
                                             CultureInfo.CurrentCulture,
                                             Properties.Resources.Template_DoesntExist,
                                             reference.Name));
                        errorList.Append(Environment.NewLine);
                    }
                }
            }
            if (errorList.Length > 0)
            {
                // Enclose full list of errors in a simpler message for display in the dialog.
                throw new RecipeFrameworkException(string.Format(CultureInfo.CurrentCulture,
                                                                 Properties.Resources.Templates_ErrorsProcessingReferences,
                                                                 this.Template.Name),
                                                   new ArgumentException(errorList.ToString()));
            }
        }
Пример #27
0
        private void LoadInitialState()
        {
            if (this.template.ExtensionData.Recipe == null)
            {
                return;
            }
            DTE dte = (DTE)GetService(typeof(DTE));
            IAssetReferenceService referenceService = (IAssetReferenceService)
                                                      this.Package.GetService(typeof(IAssetReferenceService), false);

            if (referenceService != null)
            {
                IAssetReference templateAsset = null;
                try
                {
                    object target = DteHelper.GetTarget(dte);
                    templateAsset = referenceService.GetReferenceFor(this.Template.FileName, target);
                    if (templateAsset == null)
                    {
                        if (this.Template.Kind == TemplateKind.Project && target is Project)                         // If the template is been unfolded, then check the parent folder
                        {
                            Project parentProject = (target as Project).ParentProjectItem.ContainingProject;
                            if (parentProject != null)                             // Parent folder exist, check the reference to the template
                            {
                                templateAsset = referenceService.GetReferenceFor(this.Template.FileName, parentProject);
                            }
                            else                             // The parent folder is the solution root, check the reference in the solutioin root
                            {
                                templateAsset = referenceService.GetReferenceFor(this.Template.FileName, dte.Solution);
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    templateAsset = null;
                }
                if (templateAsset != null)
                {
                    IPersistenceService persistenceService = (IPersistenceService)this.Package.GetService(typeof(IPersistenceService), false);
                    if (persistenceService != null)
                    {
                        IDictionary hashStored = persistenceService.LoadState(this.Template.PackageName, templateAsset);
                        if (hashStored != null)
                        {
                            ArrayList toremove = new ArrayList(hashStored.Count);
                            foreach (DictionaryEntry keyValuePair in hashStored)
                            {
                                if (this.templateDictionary.GetValue(keyValuePair.Key) == null)
                                {
                                    try
                                    {
                                        this.templateDictionary.SetValue(keyValuePair.Key, keyValuePair.Value);
                                    }
                                    catch
                                    {
                                        string appliesTo;
                                        try
                                        {
                                            appliesTo = templateAsset.AppliesTo;
                                        }
                                        catch (Exception e)
                                        {
                                            Trace.TraceWarning(e.Message);
                                            appliesTo = Properties.Resources.Reference_AppliesToThrew;
                                        }
                                        // Invalid initial state should just be ignored.
                                        Trace.TraceWarning(Properties.Resources.Template_IgnoreKeyInitialState, keyValuePair.Key, templateAsset.AppliesTo);
                                        toremove.Add(keyValuePair.Key);
                                    }
                                }
                            }
                            foreach (object key in toremove)
                            {
                                hashStored.Remove(key);
                            }
                            if (toremove.Count != 0)
                            {
                                // Save the updated one without the offending values.
                                persistenceService.SaveState(this.template.PackageName, templateAsset, hashStored);
                            }
                        }
                    }
                }
            }
        }