Пример #1
0
 public ActionPackageMetric(MetricsContext context, PackageAction packageAction, string projectPath)
 {
     PackageName      = packageAction.Name;
     PackageVersion   = packageAction.Version;
     SolutionPathHash = context.SolutionPathHash;
     ProjectGuid      = context.ProjectGuidMap.GetValueOrDefault(projectPath, "N/A");
 }
Пример #2
0
        public string CreateWhereAction(PackageAction action, int?PackageID = 1)
        {
            var sqlWhere = string.Empty;

            if (action == PackageAction.All)
            {
                sqlWhere = "( IsDelete = 0 ) ";
            }
            else if (action == PackageAction.MaxProduct)
            {
                //comprowflag มาจาก b2bcompany.rowflag
                sqlWhere = "( IsDelete = 0 AND OptionCode = 'maxProduct' )";
            }
            else if (action == PackageAction.MaxHot)
            {
                sqlWhere = "( IsDelete = 0 AND OptionCode = 'maxHotProduct' ) ";
            }
            else if (action == PackageAction.MaxFeat)
            {
                sqlWhere = "( IsDelete = 0 AND OptionCode = 'maxFeatProduct' ) ";
            }

            if (PackageID > 0)
            {
                sqlWhere += "AND (PackageID = " + PackageID + ")";
            }

            return(sqlWhere);
        }
Пример #3
0
        /// <summary>
        /// Adds the Formulate dashboard to the Formulate section.
        /// </summary>
        private void AddDashboard()
        {
            // Queue dashboard transformation.
            QueueInstallAction(() =>
            {
                var exists = DashboardExists();
                if (!exists)
                {
                    // Logging.
                    LogHelper.Info <ApplicationStartedHandler>("Installing Formulate dashboard.");


                    // Variables.
                    var doc       = new XmlDocument();
                    var actionXml = Resources.TransformDashboard;
                    doc.LoadXml(actionXml);


                    // Add dashboard.
                    PackageAction.RunPackageAction("Formulate",
                                                   "Formulate.TransformXmlFile", doc.FirstChild);

                    // Logging.
                    LogHelper.Info <ApplicationStartedHandler>("Done installing Formulate dashboard.");
                }
            });
        }
Пример #4
0
        /// <summary>
        /// Adds the Formulate section to Umbraco.
        /// </summary>
        /// <param name="applicationContext">
        /// The current application context.
        /// </param>
        private void AddSection(ApplicationContext applicationContext)
        {
            // Queue section change.
            QueueInstallAction(() =>
            {
                var service         = applicationContext.Services.SectionService;
                var existingSection = service.GetByAlias("formulate");
                if (existingSection == null)
                {
                    // Logging.
                    LogHelper.Info <ApplicationStartedHandler>("Installing Formulate section in applications.config.");


                    // Variables.
                    var doc       = new XmlDocument();
                    var actionXml = Resources.TransformApplications;
                    doc.LoadXml(actionXml);


                    // Add to applications.
                    PackageAction.RunPackageAction("Formulate",
                                                   "Formulate.TransformXmlFile", doc.FirstChild);


                    // Logging.
                    LogHelper.Info <ApplicationStartedHandler>("Done installing Formulate section in applications.config.");
                }
            });
        }
        /// <summary>
        /// Transforms the web.config to add the Formulate
        /// configuration group.
        /// </summary>
        private void AddConfigurationGroup()
        {
            // Queue web.config change to add Formulate configuration.
            QueueInstallAction(() =>
            {
                // Does the section group already exist?
                var config    = WebConfigurationManager.OpenWebConfiguration("~");
                var groupName = "formulateConfiguration";
                var group     = config.GetSectionGroup(groupName);
                var exists    = group != null;


                // Only add the group if it doesn't exist.
                if (!exists)
                {
                    // Logging.
                    LogHelper.Info <ApplicationStartedHandler>("Adding Formulate config to the web.config.");


                    // Variables.
                    var doc       = new XmlDocument();
                    var actionXml = Resources.TransformWebConfig;
                    doc.LoadXml(actionXml);


                    // Add configuration group.
                    PackageAction.RunPackageAction("Formulate",
                                                   "Formulate.TransformXmlFile", doc.FirstChild);


                    // Logging.
                    LogHelper.Info <ApplicationStartedHandler>("Done adding Formulate config to the web.config.");
                }
            });
        }
Пример #6
0
        /// <summary>
        /// Permits all users to access Formulate if configured in the web.config.
        /// </summary>
        private void PermitAccess()
        {
            // Variables.
            var key    = SettingConstants.EnsureUsersCanAccess;
            var ensure = ConfigurationManager.AppSettings[key];


            // Should all users be given access to Formulate?
            if (string.IsNullOrWhiteSpace(ensure))
            {
                return;
            }


            // Variables.
            var doc       = new XmlDocument();
            var actionXml = Resources.GrantAllUsersPermissionToSection;

            doc.LoadXml(actionXml);


            // Grant access permission.
            PackageAction.RunPackageAction("Formulate",
                                           "Formulate.GrantPermissionToSection", doc.FirstChild);
        }
Пример #7
0
        public object PermitAccessToFormulate()
        {
            try
            {
                // Variables.
                var doc       = new XmlDocument();
                var actionXml = Resources.GrantPermissionToSection;
                doc.LoadXml(actionXml);


                // Grant access permission.
                PackageAction.RunPackageAction("Formulate",
                                               "Formulate.GrantPermissionToSection", doc.FirstChild);


                // Indicate success.
                return(new
                {
                    Success = true
                });
            }
            catch (Exception ex)
            {
                // Error (log and indicate failure).
                var message = "An error occurred while attempting to set permissions.";
                LogHelper.Error <SetupController>(message, ex);
                return(new
                {
                    Success = false,
                    Reason = message
                });
            }
        }
        public bool Undo(string packageName, XmlNode xmlData)
        {
            bool result = true;

            // build XML string for all the installable components
            var sb = new StringBuilder("<Actions>");

            // loop through each of the appSettings keys
            foreach (var appKey in Settings.AppKeys)
            {
                sb.AppendFormat("<Action runat=\"install\" undo=\"true\" alias=\"HttpsRedirect_AddAppConfigKey\" key=\"{0}\" value=\"false\" />", appKey.Key);
            }

            // remove the dashboard control (if exists)
            sb.Append("<Action runat=\"install\" undo=\"true\" alias=\"addDashboardSection\" dashboardAlias=\"HttpsRedirectInstaller\" />");

            // append the closing tag
            sb.Append("</Actions>");

            // load the XML string into an XML document
            var actionsXml = new XmlDocument();

            actionsXml.LoadXml(sb.ToString());

            // loop through each of the installable components
            foreach (XmlNode node in actionsXml.DocumentElement.SelectNodes("//Action"))
            {
                // uninstall the components
                PackageAction.UndoPackageAction("HttpsRedirect", node.Attributes["alias"].Value, node);
            }

            return(result);
        }
Пример #9
0
 private static void SimulateProgressUpdate(PackageAction action)
 {
     for (var i = 0; i < 100; i += ProgressStep)
     {
         action.Progress += ProgressStep;
         Task.Delay(MillisecondsDelay).Wait();
     }
 }
Пример #10
0
        private string GetButtonText(PackageAction action, bool inProgress = false, SemVersion version = null)
        {
            var actionText = inProgress ? PackageActionInProgressVerbs[(int)action] : PackageActionVerbs[(int)action];

            return(version == null?
                   string.Format("{0}", actionText) :
                       string.Format("{0} {1}", actionText, version));
        }
Пример #11
0
        private void _addLanguageKey()
        {
            var xd = new XmlDocument();

            xd.LoadXml(@"<Action runat='install' undo='true' alias='AddLanguageFileKey' language='en' position='beginning' area='sections' key='UmbracoBookshelf' value='Umbraco Bookshelf' />");

            LogHelper.Info <PackageActions>("Running Bookshelf language action.");
            PackageAction.RunPackageAction("UmbracoBookshelf", "AddLanguageFileKey", xd.FirstChild);
        }
Пример #12
0
            internal IEnumerable <IPackage> GetPackages(PackageAction action)
            {
                Dictionary <IPackage, PackageOperation> dictionary = GetPackageLookup(action);

                if (dictionary != null)
                {
                    return(dictionary.Keys);
                }
                return(Enumerable.Empty <IPackage>());
            }
Пример #13
0
        public static Task <bool> IsValidAction(this PackageKey package, PackageAction action)
        {
            switch (action.Action)
            {
            case 0:
                return(IsInstallable(package));

            default:
                return(IsUninstallable(package));
            }
        }
Пример #14
0
            internal void RemoveOperation(IPackage package, PackageAction action)
            {
                PackageOperation operation;
                Dictionary <IPackage, PackageOperation> packageLookup = this.GetPackageLookup(action, false);

                if ((packageLookup != null) && packageLookup.TryGetValue(package, out operation))
                {
                    packageLookup.Remove(package);
                    this._operations.Remove(operation);
                }
            }
Пример #15
0
            private Dictionary <IPackage, PackageOperation> GetPackageLookup(PackageAction action, bool createIfNotExists = false)
            {
                Dictionary <IPackage, PackageOperation> dictionary;

                if (!this._operationLookup.TryGetValue(action, out dictionary) & createIfNotExists)
                {
                    dictionary = new Dictionary <IPackage, PackageOperation>((IEqualityComparer <IPackage>)PackageEqualityComparer.IdAndVersion);
                    this._operationLookup.Add(action, dictionary);
                }
                return(dictionary);
            }
Пример #16
0
            internal void RemoveOperation(IPackage package, PackageAction action)
            {
                Dictionary <IPackage, PackageOperation> dictionary = GetPackageLookup(action);
                PackageOperation operation;

                if (dictionary != null && dictionary.TryGetValue(package, out operation))
                {
                    dictionary.Remove(package);
                    _operations.Remove(operation);
                }
            }
        public void BeginProcessing(IEnumerable <string> batch, PackageAction action)
        {
            // JS projects does not handle TFS operations automatically when calling DTE APIs.
            // We do it manually here. Note the TfsFileSystem implements IBatchProcessor.
            var processor = BaseFileSystem as IBatchProcessor <string>;

            if (processor != null)
            {
                processor.BeginProcessing(batch, action);
            }
        }
Пример #18
0
            private Dictionary <IPackage, PackageOperation> GetPackageLookup(PackageAction action, bool createIfNotExists = false)
            {
                Dictionary <IPackage, PackageOperation> packages;

                if (!_operationLookup.TryGetValue(action, out packages) && createIfNotExists)
                {
                    packages = new Dictionary <IPackage, PackageOperation>(PackageEqualityComparer.IdAndVersion);
                    _operationLookup.Add(action, packages);
                }
                return(packages);
            }
Пример #19
0
        public void ExecuteProcess(DeploymentSet dacPacInfo, PackageAction action)
        {
            switch (action)
            {
            case PackageAction.Report:
                _reportOutputFile = Path.Combine(CreateSessionFolder(_reportFolder, "Reports"), Settings.Default.PrePublishReportFilename);
                _args             = string.Format("/SourceFile:\"{0}\" /Profile:\"{1}\" /Action:DeployReport /OutputPath:\"{2}\"", dacPacInfo.DacPacFilePath, dacPacInfo.PublishProfileFilePath, _reportOutputFile);
                break;

            case PackageAction.DriftReport:
                _driftReportOutputFile = Path.Combine(CreateSessionFolder(_reportFolder, "Reports"), Settings.Default.DriftReportFilename);
                //_args = string.Format("/TargetServerName:\"{0}\" /TargetDatabaseName:\"{1}\" /Action:DriftReport /OutputPath:\"{2}\"", "V-DEV-WEB-008\\DATA", "SSDTProject", _driftReportOutputFile);
                _args = string.Format("/TargetConnectionString:\"{0}\" /Action:DriftReport /OutputPath:\"{1}\"", dacPacInfo.TargetConnectionString, _driftReportOutputFile);
                break;

            case PackageAction.Publish:
                _args = string.Format("/SourceFile:\"{0}\" /Profile:\"{1}\" /Action:Publish", dacPacInfo.DacPacFilePath, dacPacInfo.PublishProfileFilePath);
                break;

            case PackageAction.Script:
                _scriptOutputFile = Path.Combine(CreateSessionFolder(_reportFolder, "Reports"), Settings.Default.ScriptFilename);
                _args             = string.Format("/SourceFile:\"{0}\" /Profile:\"{1}\" /OutputPath:\"{2}\" /Action:Script", dacPacInfo.DacPacFilePath, dacPacInfo.PublishProfileFilePath, _scriptOutputFile);
                break;

            default:
                _args = string.Empty;
                break;
            }

            using (var proc = new System.Diagnostics.Process())
            {
                proc.StartInfo.FileName               = Settings.Default.SqlPackageExeLocation;
                proc.StartInfo.Arguments              = _args;
                proc.StartInfo.UseShellExecute        = false;
                proc.EnableRaisingEvents              = true;
                proc.StartInfo.WindowStyle            = ProcessWindowStyle.Normal;
                proc.StartInfo.CreateNoWindow         = true;
                proc.StartInfo.RedirectStandardInput  = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError  = true;
                proc.EnableRaisingEvents              = true;
                proc.OutputDataReceived              += ProcOutputDataReceived;
                proc.ErrorDataReceived += ProcOutputDataReceived;
                proc.Start();
                proc.BeginOutputReadLine();
                proc.BeginErrorReadLine();
                proc.WaitForExit();
            }

            Logging.Logger.Log.Info(string.Format("Command Line Arguments:{0}{1}{0}", Environment.NewLine, _args));

            Reporting(action);
        }
        private static IEnumerable <PackageAction> GetPackageActions(XElement actionsElement, string packageName)
        {
            if (actionsElement == null)
            {
                return(new PackageAction[0]);
            }

            if (string.Equals(Constants.Packaging.ActionsNodeName, actionsElement.Name.LocalName) == false)
            {
                throw new ArgumentException("Must be \"" + Constants.Packaging.ActionsNodeName + "\" as root",
                                            "actionsElement");
            }

            return(actionsElement.Elements(Constants.Packaging.ActionNodeName)
                   .Select(elemet =>
            {
                XAttribute aliasAttr = elemet.Attribute(Constants.Packaging.AliasNodeNameCapital);
                if (aliasAttr == null)
                {
                    throw new ArgumentException(
                        "missing \"" + Constants.Packaging.AliasNodeNameCapital + "\" atribute in alias element",
                        "actionsElement");
                }

                var packageAction = new PackageAction
                {
                    XmlData = elemet,
                    Alias = aliasAttr.Value,
                    PackageName = packageName,
                };


                XAttribute attr = elemet.Attribute(Constants.Packaging.RunatNodeAttribute);

                ActionRunAt runAt;
                if (attr != null && Enum.TryParse(attr.Value, true, out runAt))
                {
                    packageAction.RunAt = runAt;
                }

                attr = elemet.Attribute(Constants.Packaging.UndoNodeAttribute);

                bool undo;
                if (attr != null && bool.TryParse(attr.Value, out undo))
                {
                    packageAction.Undo = undo;
                }


                return packageAction;
            }).ToArray());
        }
        protected void btnActivate_Click(object sender, EventArgs e)
        {
            var failures  = new List <string>();
            var successes = new List <string>();
            var settings  = new Dictionary <string, string>();
            var xml       = new XmlDocument();

            // adds the appSettings keys for doctypes, templates, pageIds
            settings.Add(Settings.AppKey_DocTypes, GetStringFromCheckboxList(this.cblDocTypes));
            settings.Add(Settings.AppKey_Templates, GetStringFromCheckboxList(this.cblTemplates));
            settings.Add(Settings.AppKey_PageIds, this.txtPageIds.Text.Trim());
            settings.Add(Settings.AppKey_Properties, this.txtProperties.Text.Trim());
            settings.Add(Settings.AppKey_StripPort, this.chkStripPort.Checked.ToString());
            settings.Add(Settings.AppKey_UseTemporaryRedirects, this.chkUseTemporaryRedirects.Checked.ToString());
            settings.Add(Settings.AppKey_XForwardedProto, this.chkXForwardedProto.Checked.ToString());

            foreach (var setting in settings)
            {
                var title = Settings.AppKeys[setting.Key];
                xml.LoadXml(string.Format("<Action runat=\"install\" undo=\"true\" alias=\"HttpsRedirect_AddAppConfigKey\" key=\"{0}\" value=\"{1}\" />", setting.Key, setting.Value));
                PackageAction.RunPackageAction(title, "HttpsRedirect_AddAppConfigKey", xml.FirstChild);
                successes.Add(title);
            }

            if (this.cbDashboardControl.Checked)
            {
                var title = "Dashboard control";
                xml.LoadXml("<Action runat=\"install\" undo=\"true\" alias=\"addDashboardSection\" dashboardAlias=\"HttpsRedirectInstaller\"><section><areas><area>developer</area></areas><tab caption=\"HttpsRedirect: Settings\"><control>/umbraco/plugins/HttpsRedirect/HttpsRedirectInstaller.ascx</control></tab></section></Action>");
                PackageAction.RunPackageAction(title, "addDashboardSection", xml.FirstChild);
                successes.Add(title);
            }

            // set the feedback controls to hidden
            this.Failure.Visible = this.Success.Visible = false;

            // display failure messages
            if (failures.Count > 0)
            {
                this.Failure.type    = Feedback.feedbacktype.error;
                this.Failure.Text    = "There were errors with the following settings:<br />" + string.Join("<br />", failures.ToArray());
                this.Failure.Visible = true;
            }

            // display success messages
            if (successes.Count > 0)
            {
                this.Success.type    = Feedback.feedbacktype.success;
                this.Success.Text    = "Successfully installed the following settings: " + string.Join(", ", successes.ToArray());
                this.Success.Visible = true;
            }
        }
        FakeInstallPackageAction AddInstallActionWithMSBuildTargetsFile(
            string packageId            = "Test",
            PackageAction packageAction = PackageAction.Install)
        {
            FakeInstallPackageAction action = AddInstallAction();
            var package = new FakePackage(packageId);

            package.AddFile(@"build\net40\" + packageId + ".targets");
            var operations = new List <PackageOperation> ();

            operations.Add(new PackageOperation(package, packageAction));
            action.Operations = operations;
            action.Package    = package;
            return(action);
        }
        /// <summary>
        /// Transforms the web.config to add the Formulate configuration group.
        /// </summary>
        private void AddConfigurationGroup()
        {
            // Queue web.config change to add Formulate configuration.
            QueueInstallAction(() =>
            {
                // Does the section group already exist and contain all the expected sections?
                var config           = WebConfigurationManager.OpenWebConfiguration("~");
                var groupName        = "formulateConfiguration";
                var group            = config.GetSectionGroup(groupName);
                var exists           = group != null;
                var sectionKeys      = (group?.Sections?.Keys?.Cast <string>()?.ToArray()).MakeSafe();
                var sectionsSet      = new HashSet <string>(sectionKeys);
                var expectedSections = new[]
                {
                    "buttons",
                    "emailWhitelist",
                    "email",
                    "fieldCategories",
                    "persistence",
                    "submissions",
                    "templates"
                };
                var containsAllSections = expectedSections.All(x => sectionsSet.Contains(x));


                // Only add the group if it doesn't exist or doesn't contain all the expected sections.
                if (!exists || !containsAllSections)
                {
                    // Logging.
                    LogHelper.Info <ApplicationStartedHandler>("Adding Formulate config to the web.config.");


                    // Variables.
                    var doc       = new XmlDocument();
                    var actionXml = Resources.TransformWebConfig;
                    doc.LoadXml(actionXml);


                    // Add configuration group.
                    PackageAction.RunPackageAction("Formulate",
                                                   "Formulate.TransformXmlFile", doc.FirstChild);


                    // Logging.
                    LogHelper.Info <ApplicationStartedHandler>("Done adding Formulate config to the web.config.");
                }
            });
        }
Пример #24
0
 /// <summary>
 /// Installs the action.
 /// </summary>
 /// <param name="packageAlias">The package alias.</param>
 /// <param name="node">The node.</param>
 /// <param name="result">The result.</param>
 private static void InstallAction(string packageAlias, XmlNode node, List <PackageActionResult> result)
 {
     try
     {
         PackageAction.RunPackageAction("Packageactiontester", packageAlias, node);
         result.Add(new PackageActionResult {
             Alias = packageAlias, Result = "Installed"
         });
     }
     catch (Exception ex)
     {
         result.Add(new PackageActionResult {
             Alias = packageAlias, Result = string.Format("Error installing: {0}", ex)
         });
     }
 }
Пример #25
0
        private void _addDashboard()
        {
            var xd = new XmlDocument();

            xd.LoadXml(@"<Action runat='install' alias='addDashboardSection' dashboardAlias='UmbracoBookshelfSection'>
	                            <section alias='UmbracoBookshelfSection'>
		                            <areas>
		                                <area>UmbracoBookshelf</area>
		                            </areas>
		                            <tab caption='Library'>
		                                <control>/app_plugins/umbracobookshelf/backoffice/dashboards/library.html</control>
		                            </tab>
	                            </section>
	                        </Action>"    );

            LogHelper.Info <PackageActions>("Running Bookshelf dashboard action.");
            PackageAction.RunPackageAction("UmbracoBookshelf", "addDashboardSection", xd.FirstChild);
        }
Пример #26
0
        public void BeginProcessing(IEnumerable <string> batch, PackageAction action)
        {
            if (batch == null)
            {
                throw new ArgumentNullException("batch");
            }

            if (action == PackageAction.Install)
            {
                if (!batch.Any())
                {
                    // Short-circuit if nothing specified
                    return;
                }

                var batchSet     = new HashSet <string>(batch.Select(GetFullPath), StringComparer.OrdinalIgnoreCase);
                var batchFolders = batchSet.Select(Path.GetDirectoryName)
                                   .Distinct()
                                   .ToArray();

                // Prior to installing, we'll look at the directories and make sure none of them have any pending deletes.
                var pendingDeletes = Workspace.GetPendingChanges(Root, RecursionType.Full)
                                     .Where(c => c.IsDelete);

                // Find pending deletes that are in the same path as any of the folders we are going to be adding.
                var pendingDeletesToUndo = pendingDeletes.Where(delete => batchFolders.Any(f => PathUtility.IsSubdirectory(delete.LocalItem, f)))
                                           .ToArray();

                // Undo deletes.
                Workspace.Undo(pendingDeletesToUndo);

                // Expand the directory deletes into individual file deletes. Include all the files we want to add but exclude any directories that may be in the path of the file.
                var childrenToPendDelete = (from folder in pendingDeletesToUndo
                                            from childItem in Workspace.GetItemsRecursive(folder.LocalItem)
                                            where batchSet.Contains(childItem) || !batchFolders.Any(f => PathUtility.IsSubdirectory(childItem, f))
                                            select childItem).ToArray();
                Workspace.PendDelete(childrenToPendDelete, RecursionType.None);
            }
        }
Пример #27
0
        public void BeginProcessing(IEnumerable <string> batch, PackageAction action)
        {
            var files = batch.OrderBy(path => path)
                        .ToList();

            foreach (var path1 in files)
            {
                foreach (var path2 in files)
                {
                    if (path1.Equals(path2, StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    if (path1.StartsWith(path2, StringComparison.OrdinalIgnoreCase) &&
                        IsSourceFile(path1))
                    {
                        _excludedCodeFiles.Add(path1);
                    }
                }
            }
        }
Пример #28
0
        private void Reporting(PackageAction action)
        {
            if (action == PackageAction.Report)
            {
                if (!File.Exists(_reportOutputFile))
                {
                    return;
                }

                // Deserialize the Xml to the screen if a report file exists...
                Progress(this, new ProcessEventArgs(XDocument.Load(_reportOutputFile).ToString(), _args));
            }

            if (action == PackageAction.DriftReport)
            {
                if (!File.Exists(_driftReportOutputFile))
                {
                    return;
                }

                // Deserialize the Xml to the screen if a report file exists...
                Progress(this, new ProcessEventArgs(XDocument.Load(_driftReportOutputFile).ToString(), _args));
            }
        }
Пример #29
0
		public FakePackageOperation(FakePackage package, PackageAction action)
			: base(package, action)
		{
			this.FakePackage = package;
		}
Пример #30
0
        private string GetButtonText(PackageAction action, bool inProgress = false, SemVersion?version = null)
        {
            var actionText = inProgress ? ApplicationUtil.instance.GetTranslationForText(k_PackageActionInProgressVerbs[(int)action]) : ApplicationUtil.instance.GetTranslationForText(k_PackageActionVerbs[(int)action]);

            return(version == null ? actionText : $"{actionText} {version}");
        }
 PackageOperation CreatePackageOperation(string id, string version, PackageAction action)
 {
     IPackage package = CreatePackage(id, version);
     return new PackageOperation(package, action);
 }
Пример #32
0
        private string GetButtonText(PackageAction action, bool inProgress = false, SemVersion version = null)
        {
            var actionText = inProgress ? k_PackageActionInProgressVerbs[(int)action] : k_PackageActionVerbs[(int)action];

            return(version == null ? $"{actionText}" : $"{actionText} {version}");
        }
Пример #33
0
        private void Fetch(PackageAction action)
        {
            lock (_fetchLock)
            {
                var package = (Package)action.Package;

                if (package.Flags.Any(n => n == "fetched"))
                {
                    action.Progress = 100;
                    action.Status = "fetched";
                    return;
                }

                action.Status = "fetching";
                SimulateProgressUpdate(action);
                action.Status = "fetched";
                package.AddFlags("fetched");
            }
        }
Пример #34
0
 public PackageOperation(IPackage package, PackageAction action)
 {
     Package = package;
     Action = action;
 }
Пример #35
0
 public PackageOperation(IPackage package, PackageAction action)
 {
     Package = package;
     Action = action;
     Target = PackageOperationTarget.Project;
 }
		FakeInstallPackageAction AddInstallActionWithMSBuildTargetsFile (
			string packageId = "Test",
			PackageAction packageAction = PackageAction.Install)
		{
			FakeInstallPackageAction action = AddInstallAction ();
			var package = new FakePackage (packageId);
			package.AddFile (@"build\net40\" + packageId + ".targets");
			var operations = new List<PackageOperation> ();
			operations.Add (new PackageOperation (package, packageAction));
			action.Operations = operations;
			action.Package = package;
			return action;
		}
Пример #37
0
        // Package queue methods
        /// <summary>
        /// Add a package to the package queue.
        /// </summary>
        /// <param name="package">The package to add to the queue.</param>
        /// <param name="action">How to handle the package (e.g. installing or uninstalling?)</param>
        /// <param name="forceReappend">Force reappending package if it's already appended to be handled in the same way.</param>
        public void QueuePackage(Package package, PackageAction action = PackageAction.Install, bool forceReappend = false)
        {
            if (_pendingPackages.Any(p => p.Item2 == package && p.Item1 == action))
                if(forceReappend)
                    DequeuePackage(package);
                else
                    throw new InvalidOperationException("Package already appended with same action type. Dequeue the package before reappending or set forceReappend parameter to true.");

            _pendingPackages.Add(new Tuple<PackageAction, Package>(action, package));
        }
Пример #38
0
 internal RequestAction(XPathNavigator nav)
 {
     Type = nav.SelectSingleNode ("@type").Value;
     Source = new PackageAction (nav.SelectSingleNode ("source"));
     Target = new PackageAction (nav.SelectSingleNode ("target"));
 }
Пример #39
0
        private void Reinstall(PackageAction action)
        {
            var package = (Package)action.Package;

            if (ShouldFetch(package))
            {
                action.AddAction(new PackageAction(package, "fetch"));
            }
            action.AddAction(new PackageAction(package, "uninstall"));
            action.AddAction(new PackageAction(package, "install"));

            CreateTask(action.Actions).RunSynchronously();
        }
Пример #40
0
        private void Update(PackageAction action)
        {
            var package = (Package)action.Package;

            if (package.Flags.All(n => n != "installed"))
            {
                action.Progress = 100;
                action.Status = "failed";
                return;
            }

            var latest =
                _packages.SingleOrDefault(
                    n => n.Id == package.Id && n.Flags.All(m => m != "installed") && n.Flags.Any(m => m == "latest"));

            if (latest == null)
            {
                action.Progress = 100;
                action.Status = "failed";
                return;
            }

            if (ShouldFetch(latest))
            {
                action.AddAction(new PackageAction(latest, "fetch"));
            }
            if (ShouldInstall(latest))
            {
                action.AddAction(new PackageAction(latest, "install"));
            }

            if (!action.Actions.Any())
            {
                action.Progress = 100;
                action.Status = "failed";
                return;
            }

            action.IsIndeterminate = true;
            action.Status = "updating";

            CreateTask(action.Actions).RunSynchronously();

            action.Progress = 100;
            action.Status = "updated";
            package.RemoveFlags("updatable");
        }
Пример #41
0
        private void Uninstall(PackageAction action)
        {
            lock (_installLock)
            {
                var package = (Package) action.Package;

                if (package.Flags.All(n => n != "installed"))
                {
                    action.Progress = 100;
                    action.Status = "failed";
                    return;
                }

                action.Status = "uninstalling";
                SimulateProgressUpdate(action);
                action.Status = "uninstalled";
                package.RemoveFlags("installed");
            }
        }
Пример #42
0
 internal void RemoveOperation(IPackage package, PackageAction action)
 {
     Dictionary<IPackage, PackageOperation> dictionary = GetPackageLookup(action);
     PackageOperation operation;
     if (dictionary != null && dictionary.TryGetValue(package, out operation))
     {
         dictionary.Remove(package);
         _operations.Remove(operation);
     }
 }
Пример #43
0
 private Dictionary<IPackage, PackageOperation> GetPackageLookup(PackageAction action, bool createIfNotExists = false)
 {
     Dictionary<IPackage, PackageOperation> packages;
     if (!_operationLookup.TryGetValue(action, out packages) && createIfNotExists)
     {
         packages = new Dictionary<IPackage, PackageOperation>(PackageEqualityComparer.IdAndVersion);
         _operationLookup.Add(action, packages);
     }
     return packages;
 }
Пример #44
0
        private void Lock(PackageAction action)
        {
            var package = (Package)action.Package;

            action.Status = "locking";
            action.Progress = 100;
            action.Status = "locked";
            package.AddFlags("locked");
        }
Пример #45
0
        private void Unlock(PackageAction action)
        {
            var package = (Package)action.Package;

            action.Status = "unlocking";
            action.Progress = 100;
            action.Status = "unlocked";
            package.RemoveFlags("locked");
        }
Пример #46
0
            internal bool Contains(IPackage package, PackageAction action)
            {
                Dictionary <IPackage, PackageOperation> dictionary = GetPackageLookup(action);

                return(dictionary != null && dictionary.ContainsKey(package));
            }
Пример #47
0
        private void Install(PackageAction action)
        {
            lock (_installLock)
            {
                var package = (Package) action.Package;

                if (ShouldFetch(package))
                {
                    action.AddAction(new PackageAction(package, "fetch"));
                    CreateTask(action.Actions).RunSynchronously();
                }

                action.Status = "installing";
                SimulateProgressUpdate(action);
                action.Status = "installed";
                package.AddFlags("installed");
            }
        }
Пример #48
0
        private static List<string> ProcessPackage(string packageFilePath, string targetDirectoryPath, PackageAction action)
        {
            var files = new List<string>();

            using (var packageStream = File.Open(packageFilePath, FileMode.Open))
            using (var package = new ZipArchive(packageStream, ZipArchiveMode.Read))
            {
                foreach (var entry in package.Entries.Where(e => !string.IsNullOrEmpty(e.Name)))
                {
                    var filePath = Path.Combine(targetDirectoryPath, entry.FullName);
                    files.Add(filePath);

                    switch (action)
                    {
                        case PackageAction.Install:
                            EnsureDirectoryExists(filePath);
                            using (var entryStream = entry.Open())
                            using (var fileStream = File.Create(filePath))
                            {
                                entryStream.CopyTo(fileStream);
                            }
                            File.SetLastWriteTime(filePath, entry.LastWriteTime.LocalDateTime);
                            break;
                    }
                }
            }

            return files;
        }
Пример #49
0
 internal IEnumerable<IPackage> GetPackages(PackageAction action)
 {
     Dictionary<IPackage, PackageOperation> dictionary = GetPackageLookup(action);
     if (dictionary != null)
     {
         return dictionary.Keys;
     }
     return Enumerable.Empty<IPackage>();
 }
Пример #50
0
 internal bool Contains(IPackage package, PackageAction action)
 {
     Dictionary<IPackage, PackageOperation> dictionary = GetPackageLookup(action);
     return dictionary != null && dictionary.ContainsKey(package);
 }
Пример #51
0
 private static PackageAction ReverseAction(PackageAction packageAction)
 {
     return packageAction == PackageAction.Install ?
         PackageAction.Uninstall :
         PackageAction.Install;
 }
Пример #52
0
 private void AssertOperation(string expectedId, string expectedVersion, PackageAction expectedAction, PackageOperation operation)
 {
     Assert.Equal(expectedAction, operation.Action);
     Assert.Equal(expectedId, operation.Package.Id);
     Assert.Equal(new SemanticVersion(expectedVersion), operation.Package.Version);
 }
Пример #53
0
        private void Uninstall(PackageAction action)
        {
            lock (_riLock)
            {
                var package = (Package)action.Package;

                if (package.Flags.All(n => n != "installed"))
                {
                    action.Progress = 100;
                    action.Status = "failed";
                    return;
                }

                action.Status = "uninstalling";
                IList err;
                dynamic res = _ri.Invoke("Uninstall-Package $input -Force", new[] { package.Name }, out err);
                action.Status = "uninstalled";
                action.Progress = 100;
                foreach (var pkg in res)
                {
                    var ex = _packages.FirstOrDefault(n => n.Name == pkg.Name && n.Version == pkg.Version);
                    if (ex != null && pkg.Status != "Installed")
                    {
                        ex.RemoveFlags("installed");
                    }
                }
            }
        }