Example #1
0
        private static void ImportWorkItemTypes(ILogger logger, ApplicationTask task, bool setTaskProgress, ref int step, ImportOptions options, WorkItemStore store, Dictionary <TeamProjectInfo, List <WorkItemTypeDefinition> > teamProjectsWithWorkItemTypes)
        {
            var importValidationFailed            = false;
            ImportEventHandler importEventHandler = (sender, e) =>
            {
                if (e.Severity == ImportSeverity.Error)
                {
                    importValidationFailed = true;
                    var message = e.Message;
                    var schemaValidationException = e.Exception as XmlSchemaValidationException;
                    if (schemaValidationException != null)
                    {
                        message = string.Format("XML validation error at row {0}, column {1}: {2}", schemaValidationException.LineNumber, schemaValidationException.LinePosition, message);
                    }
                    task.SetError(message);
                }
                else if (e.Severity == ImportSeverity.Warning)
                {
                    task.SetWarning(e.Message);
                }
            };

            // Validate.
            if (!task.IsCanceled)
            {
                WorkItemType.ValidationEventHandler += importEventHandler;
                try
                {
                    foreach (var teamProjectWithWorkItemTypes in teamProjectsWithWorkItemTypes)
                    {
                        var teamProject = teamProjectWithWorkItemTypes.Key;
                        var project     = store.Projects[teamProject.Name];
                        foreach (var workItemTypeFile in teamProjectWithWorkItemTypes.Value)
                        {
                            task.Status = string.Format("Validating {0} for Team Project \"{1}\"", workItemTypeFile.DisplayName, teamProject.Name);
                            try
                            {
                                WorkItemType.Validate(project, workItemTypeFile.XmlDefinition.OuterXml);
                            }
                            catch (Exception exc)
                            {
                                var message = string.Format("An error occurred while validating {0} for Team Project \"{1}\"", workItemTypeFile.DisplayName, teamProject.Name);
                                logger.Log(message, exc);
                                task.SetError(message, exc);
                            }
                            if (task.IsCanceled)
                            {
                                break;
                            }
                        }
                        if (task.IsCanceled)
                        {
                            task.Status = "Canceled";
                            break;
                        }
                    }
                }
                finally
                {
                    WorkItemType.ValidationEventHandler -= importEventHandler;
                }
            }

            // Import.
            if (!task.IsCanceled && !importValidationFailed)
            {
                foreach (var teamProjectWithWorkItemTypes in teamProjectsWithWorkItemTypes)
                {
                    var teamProject = teamProjectWithWorkItemTypes.Key;
                    var project     = store.Projects[teamProject.Name];
                    project.WorkItemTypes.ImportEventHandler += importEventHandler;
                    try
                    {
                        foreach (var workItemTypeFile in teamProjectWithWorkItemTypes.Value)
                        {
                            if (options.HasFlag(ImportOptions.Simulate))
                            {
                                var status = string.Format("Simulating import of {0} in Team Project \"{1}\"", workItemTypeFile.DisplayName, teamProject.Name);
                                if (setTaskProgress)
                                {
                                    task.SetProgress(step++, status);
                                }
                                else
                                {
                                    task.Status = status;
                                }
                            }
                            else
                            {
                                var status = string.Format("Importing {0} in Team Project \"{1}\"", workItemTypeFile.DisplayName, teamProject.Name);
                                if (setTaskProgress)
                                {
                                    task.SetProgress(step++, status);
                                }
                                else
                                {
                                    task.Status = status;
                                }
                                try
                                {
                                    project.WorkItemTypes.Import(workItemTypeFile.XmlDefinition.DocumentElement);
                                }
                                catch (Exception exc)
                                {
                                    var message = string.Format("An error occurred while importing {0} in Team Project \"{1}\"", workItemTypeFile.DisplayName, teamProject.Name);
                                    logger.Log(message, exc);
                                    task.SetError(message, exc);
                                }
                            }
                            if (task.IsCanceled)
                            {
                                break;
                            }
                        }
                    }
                    finally
                    {
                        project.WorkItemTypes.ImportEventHandler -= importEventHandler;
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
            }
        }
Example #2
0
        public static void Import(ILogger logger, ApplicationTask task, bool setTaskProgress, WorkItemStore store, Dictionary <TeamProjectInfo, List <WorkItemConfigurationItem> > teamProjectsWithConfigurationItems, ImportOptions options)
        {
            // Replace any macros.
            if (!task.IsCanceled)
            {
                foreach (var teamProject in teamProjectsWithConfigurationItems.Keys.ToArray())
                {
                    var transformedList = new List <WorkItemConfigurationItem>();
                    foreach (var workItemConfigurationItem in teamProjectsWithConfigurationItems[teamProject])
                    {
                        // Clone the item so that any callers aren't affected by a changed XML definitions.
                        var clone = workItemConfigurationItem.Clone();
                        ReplaceTeamProjectMacros(clone.XmlDefinition, teamProject);
                        transformedList.Add(clone);
                    }
                    teamProjectsWithConfigurationItems[teamProject] = transformedList;
                }
            }

            // Save a temporary copy for troubleshooting if requested.
            if (!task.IsCanceled && options.HasFlag(ImportOptions.SaveCopy))
            {
                foreach (var teamProjectWithConfigurationItems in teamProjectsWithConfigurationItems)
                {
                    var teamProject = teamProjectWithConfigurationItems.Key;
                    foreach (var workItemConfigurationItem in teamProjectWithConfigurationItems.Value)
                    {
                        var directoryName = Path.Combine(Path.GetTempPath(), Constants.ApplicationName, teamProject.Name);
                        Directory.CreateDirectory(directoryName);
                        var fileName = Path.Combine(directoryName, workItemConfigurationItem.Name + ".xml");
                        using (var writer = XmlWriter.Create(fileName, new XmlWriterSettings {
                            Indent = true
                        }))
                        {
                            workItemConfigurationItem.XmlDefinition.WriteTo(writer);
                        }
                        var message = "{0} for Team Project \"{1}\" was saved to \"{2}\"".FormatCurrent(workItemConfigurationItem.DisplayName, teamProject.Name, fileName);
                        logger.Log(message, TraceEventType.Verbose);
                        task.Status = message;
                    }
                }
            }

            var step = 0;

            foreach (var teamProjectWithConfigurationItems in teamProjectsWithConfigurationItems)
            {
                var teamProject        = teamProjectWithConfigurationItems.Key;
                var configurationItems = teamProjectWithConfigurationItems.Value;
                var project            = store.Projects[teamProjectWithConfigurationItems.Key.Name];

                // First apply all work item types in batch.
                var workItemTypes = configurationItems.Where(t => t.Type == WorkItemConfigurationItemType.WorkItemType).Cast <WorkItemTypeDefinition>().ToList();
                if (workItemTypes.Any())
                {
                    var teamProjectsWithWorkItemTypes = new Dictionary <TeamProjectInfo, List <WorkItemTypeDefinition> >()
                    {
                        { teamProject, workItemTypes }
                    };
                    ImportWorkItemTypes(logger, task, setTaskProgress, ref step, options, store, teamProjectsWithWorkItemTypes);
                }

                // Then apply the other configuration items.
                foreach (var configurationItem in configurationItems.Where(w => w.Type != WorkItemConfigurationItemType.WorkItemType))
                {
                    if (options.HasFlag(ImportOptions.Simulate))
                    {
                        var status = "Simulating import of {0} in Team Project \"{1}\"".FormatCurrent(configurationItem.DisplayName, teamProject.Name);
                        if (setTaskProgress)
                        {
                            task.SetProgress(step++, status);
                        }
                        else
                        {
                            task.Status = status;
                        }
                    }
                    else
                    {
                        var status = "Importing {0} in Team Project \"{1}\"".FormatCurrent(configurationItem.DisplayName, teamProject.Name);
                        if (setTaskProgress)
                        {
                            task.SetProgress(step++, status);
                        }
                        else
                        {
                            task.Status = status;
                        }
                        try
                        {
                            switch (configurationItem.Type)
                            {
                            case WorkItemConfigurationItemType.Categories:
                                SetCategories(project, configurationItem);
                                break;

                            case WorkItemConfigurationItemType.CommonConfiguration:
                                SetCommonConfiguration(project, configurationItem);
                                break;

                            case WorkItemConfigurationItemType.AgileConfiguration:
                                SetAgileConfiguration(project, configurationItem);
                                break;

                            case WorkItemConfigurationItemType.ProcessConfiguration:
                                SetProcessConfiguration(project, configurationItem);
                                break;

                            default:
                                throw new ArgumentException("The Work Item Configuration Item Type is unknown: " + configurationItem.Type.ToString());
                            }
                        }
                        catch (Exception exc)
                        {
                            var message = string.Format(CultureInfo.CurrentCulture, "An error occurred while importing {0} in Team Project \"{1}\"", configurationItem.DisplayName, teamProjectWithConfigurationItems.Key.Name);
                            logger.Log(message, exc);
                            task.SetError(message, exc);
                        }
                    }
                }
                if (task.IsCanceled)
                {
                    task.Status = "Canceled";
                    break;
                }
            }
        }
Example #3
0
        protected override IEnumerable <LessNode> EvaluateCore(EvaluationContext context)
        {
            string EvaluateFilePath(Expression expr)
            {
                if (expr is LessString str)
                {
                    return(str.GetUnquotedValue());
                }

                if (expr is Url url)
                {
                    return(EvaluateFilePath(url.Content));
                }

                return(expr.ToString());
            }

            // Import resolution takes care of relative paths regardless of the
            // rewrite setting, so while evaluating the import URL, we turn the
            // rewrite setting off.
            bool rewrite = context.RewriteRelativeUrls;

            context.RewriteRelativeUrls = false;
            var evaluatedUrl = Url.EvaluateSingle <Expression>(context);

            context.RewriteRelativeUrls = rewrite;

            var filePath = EvaluateFilePath(evaluatedUrl);

            bool isExplicitCssImport = options.HasFlag(ImportOptions.Css);

            if (isExplicitCssImport || !filePath.IsLocalFilePath())
            {
                return(new[] { this });
            }

            var extension = Path.GetExtension(filePath);

            bool isCssFile            = extension == ".css";
            bool isExplicitLessImport = options.HasFlag(ImportOptions.Less);
            bool isInlineImport       = options.HasFlag(ImportOptions.Inline);

            if (isCssFile && !isExplicitLessImport && !isInlineImport)
            {
                return(new[] {
                    new ImportStatement(
                        evaluatedUrl,
                        options,
                        mediaQueries.Select(mq => mq.EvaluateSingle <MediaQuery>(context))),
                });
            }

            var actualImportPath = string.IsNullOrEmpty(extension)
                                ? Path.ChangeExtension(filePath, "less")
                                : filePath;


            var importResults = GetImportResults(options.HasFlag(ImportOptions.Optional));

            if (importResults == null)
            {
                return(Enumerable.Empty <LessNode>());
            }

            if (mediaQueries.Any())
            {
                return(new[] { new MediaBlock(mediaQueries, new RuleBlock(importResults)).EvaluateSingle <MediaBlock>(context) });
            }

            return(importResults);

            IEnumerable <Statement> GetImportResults(bool optional)
            {
                if (context.SeenImport(actualImportPath))
                {
                    return(Enumerable.Empty <Statement>());
                }

                if (!options.HasFlag(ImportOptions.Reference))
                {
                    context.NoteImport(actualImportPath);
                }

                using (context.EnterImportScope(actualImportPath)) {
                    try {
                        if (isCssFile && isInlineImport)
                        {
                            return(new Statement[] { new InlineCssImportStatement(context.GetFileContent()) });
                        }


                        return(context
                               .ParseCurrentStylesheet(isReference: options.HasFlag(ImportOptions.Reference))
                               .Evaluate(context)
                               .OfType <Statement>()
                               .ToList());
                    } catch (IOException ex) {
                        if (optional)
                        {
                            return(null);
                        }

                        throw new EvaluationException($"Failed to import {filePath}", ex);
                    }
                }
            }
        }
Example #4
0
        internal void TryApplyOnlineChangeSettings(LogicProject zenonLogicProject, ImportOptions options = ImportOptions.Default)
        {
            if (!options.HasFlag(ImportOptions.ApplyOnlineSettings))
            {
                return;
            }

            var optionTuples = zenonLogicProject.Settings.OnlineChangeSettings.OptionTuples ?? Enumerable.Empty <LogicOptionTuple>();

            const uint callback            = 0x400;
            IntPtr     hwnd                = Process.GetCurrentProcess().MainWindowHandle;
            string     clientName          = System.Reflection.Assembly.GetEntryAssembly().GetName().Name;
            string     hotSizeBuffer       = string.Empty;
            bool       enableHot           = false;
            bool       hasHotOptionDefined = false;

            using (K5SrvWrapper srv = K5SrvWrapper.TryConnect(hwnd, callback, zenonLogicProject.Path, clientName, K5SrvConstants.K5DbSelfNotif))
            {
                while (!srv.IsReady)
                {
                    Thread.Sleep(100);
                }

                foreach (var optionTuple in optionTuples)
                {
                    if (!string.IsNullOrWhiteSpace(optionTuple.Name) && !string.IsNullOrWhiteSpace(optionTuple.Value))
                    {
                        if (optionTuple.Name.StartsWith("size_"))
                        {
                            hotSizeBuffer = hotSizeBuffer + optionTuple.Name.Replace("size_", "") + "=" + optionTuple.Value + ",";
                        }

                        else if (optionTuple.Name.Equals("enable"))
                        {
                            hasHotOptionDefined = true;
                            if (int.TryParse(optionTuple.Value, out var i))
                            {
                                enableHot = i > 0;
                            }
                            else if (bool.TryParse(optionTuple.Value, out var b))
                            {
                                enableHot = b;
                            }
                            else if (optionTuple.Value.Equals("ON", StringComparison.OrdinalIgnoreCase))
                            {
                                enableHot = true;
                            }
                            else if (optionTuple.Value.Equals("OFF", StringComparison.OrdinalIgnoreCase))
                            {
                                enableHot = false;
                            }
                        }
                    }
                }

                if (hasHotOptionDefined)
                {
                    srv.SetHot(enableHot);
                }

                if (hotSizeBuffer.Length > 0)
                {
                    srv.SetHotSizing(hotSizeBuffer);
                }
            }
        }
Example #5
0
        public void Import(ImportOptions options, string scheduleFile = null)
        {
            try
            {
                switch (DataFormat)
                {
                case "json":
                    if (options.HasFlag(ImportOptions.AllSchedules))
                    {
                        Schedule[] newSch = null;
                        using (var stream = File.Open(SchedulesFile, FileMode.Open, FileAccess.Read))
                            using (var reader = new StreamReader(stream))
                                newSch = JsonConvert.DeserializeObject <Schedule[]>(reader.ReadToEnd());
                        if (newSch == null)
                        {
                            return;
                        }
                        Schedules.Clear();
                        foreach (var sch in newSch)
                        {
                            Schedules.Add(sch);
                        }
                    }
                    if (options.HasFlag(ImportOptions.MapData))
                    {
                        Map[] newMaps = null;
                        using (var stream = File.Open(MapDataFile, FileMode.Open, FileAccess.Read))
                            using (var reader = new StreamReader(stream))
                                newMaps = JsonConvert.DeserializeObject <Map[]>(reader.ReadToEnd());
                        if (newMaps == null)
                        {
                            return;
                        }
                        MapData.Clear();
                        foreach (var map in newMaps)
                        {
                            MapData.Add(map);
                        }
                    }
                    if (options.HasFlag(ImportOptions.Questions))
                    {
                        Question[] newQueries = null;
                        using (var stream = File.Open(QuestionsFile, FileMode.Open, FileAccess.Read))
                            using (var reader = new StreamReader(stream))
                                newQueries = JsonConvert.DeserializeObject <Question[]>(reader.ReadToEnd());
                        if (newQueries == null)
                        {
                            return;
                        }
                        Questions.Clear();
                        foreach (var query in newQueries)
                        {
                            Questions.Add(query);
                        }
                    }
                    if (options.HasFlag(ImportOptions.Activities))
                    {
                        Activity[] newAct = null;
                        using (var stream = File.Open(ActivitiesFile, FileMode.Open, FileAccess.Read))
                            using (var reader = new StreamReader(stream))
                                newAct = JsonConvert.DeserializeObject <Activity[]>(reader.ReadToEnd());
                        if (newAct == null)
                        {
                            return;
                        }
                        Activities.Clear();
                        foreach (var act in newAct)
                        {
                            Activities.Add(act);
                        }
                    }
                    break;

                case "csv":
                    if (options.HasFlag(ImportOptions.AllSchedules))
                    {
                        var newSch = Schedule.FromCsvMulti(DataDirectory, true);
                        Schedules.Clear();
                        foreach (var sch in newSch)
                        {
                            Schedules.Add(sch);
                        }
                    }
                    if (options == ImportOptions.SingleSchedule)
                    {
                        Schedules.Add(Schedule.FromCsv(scheduleFile));
                    }
                    if (options.HasFlag(ImportOptions.MapData))
                    {
                        var newMaps = Map.FromCsvMulti(MapDataFile, true);
                        MapData.Clear();
                        foreach (var map in newMaps)
                        {
                            MapData.Add(map);
                        }
                    }
                    if (options.HasFlag(ImportOptions.Questions))
                    {
                        var newQueries = Question.FromCsvMulti(QuestionsFile, true);
                        Questions.Clear();
                        foreach (var query in newQueries)
                        {
                            Questions.Add(query);
                        }
                    }
                    if (options.HasFlag(ImportOptions.Activities))
                    {
                        var newActs = Activity.FromCsvMulti(ActivitiesFile, true);
                        Activities.Clear();
                        foreach (var act in newActs)
                        {
                            Activities.Add(act);
                        }
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
        }