Exemple #1
0
        bool SaveTo(XmlNode formatNode)
        {
            var doc = new XmlDocument();

            try
            {
                doc.LoadXml(StringUtils.NormalizeLinebreakes(dialog.CodeTextBoxValue.Trim()));
            }
            catch (Exception e)
            {
                alerts.ShowPopup("Error", e.Message, AlertFlags.WarningIcon);
                return(false);
            }
            var nsMgr = XmlFormat.UserDefinedFormatFactory.NamespaceManager;

            if (doc.SelectSingleNode("xsl:stylesheet", nsMgr) == null)
            {
                alerts.ShowPopup("Error", "The transformation must have xsl:stylesheet on top level", AlertFlags.WarningIcon);
                return(false);
            }
            if (doc.SelectSingleNode("xsl:stylesheet/xsl:output[@method='xml']", nsMgr) == null)
            {
                alerts.ShowPopup("Error", "The transformation must output xml. Add <xsl:output method=\"xml\"/>", AlertFlags.WarningIcon);
                return(false);
            }

            formatNode.SelectNodes("xml/xsl:stylesheet", nsMgr)
            .OfType <XmlNode>().ToList().ForEach(n => n.ParentNode.RemoveChild(n));

            formatNode.SelectSingleNode("xml")?.AppendChild(
                formatNode.OwnerDocument.ImportNode(doc.DocumentElement, true));

            return(true);
        }
Exemple #2
0
        bool IPresenter.Open(IUserDefinedSearch search)
        {
            IFiltersList tempList  = search.Filters.Clone();
            bool         confirmed = false;

            using (dialogView = view.CreateDialog(this))
                using (var filtersManagerPresenter = filtersManagerFactory(tempList, dialogView))
                {
                    dialogView.SetData(new DialogData()
                    {
                        Name = search.Name
                    });
                    confirm = () =>
                    {
                        string name = dialogView.GetData().Name;
                        if (string.IsNullOrWhiteSpace(name))
                        {
                            alerts.ShowPopup(
                                alertsCaption,
                                "Bad filter name.",
                                AlertFlags.Ok
                                );
                            return(false);
                        }
                        if (name != search.Name && userDefinedSearches.ContainsItem(name))
                        {
                            alerts.ShowPopup(
                                alertsCaption,
                                string.Format("Name '{0}' is already used by another filter. Enter another name.", name),
                                AlertFlags.Ok
                                );
                            return(false);
                        }
                        if (tempList.Items.Count == 0)
                        {
                            alerts.ShowPopup(
                                alertsCaption,
                                "Can not save: filter must have at least one rule.",
                                AlertFlags.Ok
                                );
                            return(false);
                        }
                        confirmed = true;
                        return(confirmed);
                    };
                    dialogView.OpenModal();
                    confirm = null;
                    if (confirmed)
                    {
                        search.Name    = dialogView.GetData().Name;
                        search.Filters = tempList;
                    }
                    else
                    {
                        tempList.Dispose();
                    }
                }
            dialogView = null;
            return(confirmed);
        }
Exemple #3
0
        void IViewEvents.OnStateDetailsLinkClicked()
        {
            string msg = stateDetailsErrorMessage;

            if (!string.IsNullOrEmpty(msg))
            {
                alerts.ShowPopup("Error details", msg, AlertFlags.Ok | AlertFlags.WarningIcon);
            }
        }
Exemple #4
0
        void HandleProcessorError(BadUserCodeException exception, bool alwaysFallToAdvancedMode)
        {
            if (!alwaysFallToAdvancedMode && exception.BadField != null)
            {
                Field field = Get(exception.BadField.FieldName);
                if (field != null)
                {
                    dialog.FieldsListBoxSelection = fieldsListBoxItems.IndexOf(field);
                    dialog.ModifyCodeTextBoxSelection(exception.BadField.ErrorPosition, 1);

                    alerts.ShowPopup("Error", exception.ErrorMessage, AlertFlags.Ok | AlertFlags.WarningIcon);
                    return;
                }
            }

            if (alerts.ShowPopup(
                    "Error",
                    "LogJoint tried to combine your code into a class that would create LogJoin messages out of the regex captures. " +
                    "The combined code can not be compiled and the errors are outside your code. " +
                    "Although most likely the errors are caused by mistakes in the code you provided. " +
                    "It is recommended to doublecheck fields code.\n\n" +
                    "Error message: " + exception.ErrorMessage + "\n\n" +
                    "LogJoint can save combined code and detailed error messages into a file so you could analize them. " +
                    "Do you want to save this file?",
                    AlertFlags.YesNoCancel | AlertFlags.WarningIcon) == AlertFlags.Yes)
            {
                string fileName;
                if ((fileName = fileDialogs.SaveFileDialog(new SaveFileDialogParams()
                {
                    SuggestedFileName = "code.cs",
                })) != null)
                {
                    try
                    {
                        using (TextWriter fs = new StreamWriter(fileName, false, Encoding.UTF8))
                        {
                            fs.WriteLine(exception.FullCode);
                            fs.WriteLine();
                            fs.WriteLine("Compilation errors:");
                            fs.Write(exception.AllErrors);
                        }
                    }
                    catch (Exception e)
                    {
                        alerts.ShowPopup("Error", "Failed to save file. " + e.Message,
                                         AlertFlags.WarningIcon | AlertFlags.Ok);
                    }
                }
            }
        }
        public static bool?TestParsing(
            string sampleLog,
            IAlertPopup alerts,
            ITempFilesManager tempFilesManager,
            IObjectFactory objectsFactory,
            XmlNode formatRoot,
            string formatSpecificNodeName
            )
        {
            if (sampleLog == "")
            {
                alerts.ShowPopup("", "Provide sample log first", AlertFlags.Ok | AlertFlags.WarningIcon);
                return(null);
            }

            string tmpLog = tempFilesManager.GenerateNewName();

            try
            {
                XDocument clonedFormatXmlDocument = XDocument.Parse(formatRoot.OuterXml);

                UserDefinedFactoryParams createParams;
                createParams.Entry              = null;
                createParams.RootNode           = clonedFormatXmlDocument.Element("format");
                createParams.FormatSpecificNode = createParams.RootNode.Element(formatSpecificNodeName);
                createParams.FactoryRegistry    = null;
                createParams.TempFilesManager   = tempFilesManager;

                // Temporary sample file is always written in Unicode wo BOM: we don't test encoding detection,
                // we test regexps correctness.
                using (var w = new StreamWriter(tmpLog, false, new UnicodeEncoding(false, false)))
                    w.Write(sampleLog);
                ChangeEncodingToUnicode(createParams);

                var cp = ConnectionParamsUtils.CreateFileBasedConnectionParamsFromFileName(tmpLog);

                ILogProviderFactory f;
                if (formatSpecificNodeName == "regular-grammar")
                {
                    f = new RegularGrammar.UserDefinedFormatFactory(createParams);
                }
                else if (formatSpecificNodeName == "xml")
                {
                    f = new XmlFormat.UserDefinedFormatFactory(createParams);
                }
                else
                {
                    return(null);
                }
                using (f as IDisposable)
                    using (var interaction = objectsFactory.CreateTestDialog())
                    {
                        return(interaction.ShowDialog(f, cp));
                    }
            }
            finally
            {
                File.Delete(tmpLog);
            }
        }
Exemple #6
0
        async void IPresenter.StartInteraction()
        {
            string filename = fileDialogs.SaveFileDialog(new SaveFileDialogParams()
            {
                SuggestedFileName = "joint-log.log"
            });

            if (filename == null)
            {
                return;
            }
            try
            {
                using (var status = statusReport.CreateNewStatusReport())
                    using (var progress = progressFactory.CreateProgressAggregator())
                        using (var manualCancellation = new CancellationTokenSource())
                            using (var cancellation = CancellationTokenSource.CreateLinkedTokenSource(manualCancellation.Token, shutdown.ShutdownToken))
                            {
                                status.SetCancellationHandler(() => manualCancellation.Cancel());
                                Action <int> setStatusText = percentCompleted =>
                                                             status.ShowStatusText(string.Format("Saving joint log {0}%", percentCompleted), autoHide: false);
                                setStatusText(0);
                                progress.ProgressChanged += (s, e) => setStatusText(e.ProgressPercentage);
                                await LogSourceExtensions.SaveJoinedLog(logSources, cancellation.Token, progress, filename);
                            }
            }
            catch (Exception e)
            {
                alerts.ShowPopup("Failed to save joint log", e.Message,
                                 AlertFlags.Ok | AlertFlags.WarningIcon);
            }
        }
Exemple #7
0
        void IViewEvents.OnLoadSampleButtonClicked()
        {
            var fileName = fileDialogs.OpenFileDialog(new OpenFileDialogParams()
            {
                CanChooseFiles = true
            })?.FirstOrDefault();

            if (fileName == null)
            {
                return;
            }
            try
            {
                using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    using (StreamReader r = new StreamReader(fs, Encoding.ASCII, true))
                    {
                        char[] buf    = new char[1024 * 4];
                        var    sample = new string(buf, 0, r.Read(buf, 0, buf.Length));
                        view.SampleLogTextBoxValue = sample;
                    }
            }
            catch (Exception ex)
            {
                alerts.ShowPopup("Error", "Failed to read the file: " + ex.Message, AlertFlags.Ok | AlertFlags.WarningIcon);
            }
        }
        void IViewEvents.OnUploadButtonClicked()
        {
            var nonNetworkSource = logSourcesManager.Items.FirstOrDefault(s =>
                                                                          !preprocessingsManager.ConnectionRequiresDownloadPreprocessing(s.Provider.ConnectionParams));

            if (nonNetworkSource != null && alertPopup.ShowPopup(
                    "Warning",
                    string.Format(
                        "Log source '{0}' does not seem to be taken from a network location. It may be unavailable for those who you want to share your workspace with.\nContinue unloading?",
                        nonNetworkSource.GetShortDisplayNameWithAnnotation()
                        ),
                    AlertFlags.YesNoCancel | AlertFlags.WarningIcon) != AlertFlags.Yes)
            {
                return;
            }
            workspacesManager.SaveWorkspace(view.GetWorkspaceNameEditValue(), view.GetWorkspaceAnnotationEditValue());
        }
        void IDialogViewEvents.OnDeleteClicked()
        {
            var selected = GetSelection().ToArray();

            if (selected.Length == 0)
            {
                return;
            }
            if (alerts.ShowPopup(
                    "Deletion",
                    string.Format("Do you want to delete selected {0} item(s)?", selected.Length),
                    AlertFlags.YesNoCancel) != AlertFlags.Yes)
            {
                return;
            }
            foreach (var search in selected)
            {
                userDefinedSearches.Delete(search);
            }
        }
        bool IPresenter.ValidateInput()
        {
            string msg = ValidateInputInternal();

            if (msg == null)
            {
                return(true);
            }
            alerts.ShowPopup("Validation", msg, AlertFlags.Ok | AlertFlags.WarningIcon);
            return(false);
        }
        public static void Init(
            Dialog.IPresenter optionsDialogPresenter,
            Plugins.IPageAvailability pluginsPageAvailability,
            Persistence.IStorageManager storageManager,
            MainForm.IPresenter mainFormPresenter,
            IAlertPopup popup
            )
        {
            async void handler(object s, EventArgs e)
            {
                mainFormPresenter.Loaded -= handler;
                if (pluginsPageAvailability.IsAvailable)
                {
                    bool showOffer    = false;
                    var  storageEntry = storageManager.GetEntry("PluginsInstallationOffer");
                    using (var section = storageEntry.OpenXMLSection("state", Persistence.StorageSectionOpenFlag.ReadWrite))
                    {
                        if (section.Data.Root == null)
                        {
                            showOffer = true;
                            section.Data.Add(new XElement("root"));
                        }
                    }
                    if (showOffer)
                    {
                        await Task.Delay(1000);

                        string pluginsLocation = "LogJoint options dialog";
                        if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                        {
                            pluginsLocation = "menu LogJoint -> Preferences... -> Plug-ins";
                        }
                        else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                        {
                            pluginsLocation = "Options... -> Configuration... -> Plug-ins";
                        }
                        if (popup.ShowPopup(
                                "Plug-ins",
                                "LogJoint offers features via plug-ins. Do you want to choose plug-ins now?" + Environment.NewLine + Environment.NewLine +
                                "You can manage plug-ins any time in " + Environment.NewLine +
                                pluginsLocation,
                                AlertFlags.YesNoCancel
                                ) == AlertFlags.Yes)
                        {
                            optionsDialogPresenter.ShowDialog(Dialog.PageId.Plugins);
                        }
                    }
                }
            }

            mainFormPresenter.Loaded += handler;
        }
 bool IFormatsWizardScenario.Next()
 {
     try
     {
         System.IO.File.Delete(format.Location);
     }
     catch (Exception e)
     {
         alerts.ShowPopup("Error", e.Message, AlertFlags.Ok | AlertFlags.WarningIcon);
         return(false);
     }
     host.Finish();
     return(false);
 }
        bool IWizardPagePresenter.ExitPage(bool movingForward)
        {
            if (!movingForward)
            {
                return(true);
            }

            if (!ValidateInput())
            {
                return(false);
            }

            try
            {
                doc.Save(view.FileNameTextBoxValue);
            }
            catch (Log4NetImportException e)
            {
                alerts.ShowPopup("Error", "Failed to save the format:\n" + e.Message, AlertFlags.Ok | AlertFlags.WarningIcon);
                return(false);
            }
            return(true);
        }
Exemple #14
0
        void ApplyIndependentLogsMode()
        {
            string tmp = ((string)view.ReadControlValue(ControlId.FileSelector)).Trim();

            if (tmp == "")
            {
                return;
            }
            view.WriteControlValue(ControlId.FileSelector, "");
            foreach (string fname in FileListUtils.ParseFileList(tmp))
            {
                try
                {
                    model.Create(factory, factory.CreateParams(fname));
                }
                catch (Exception e)
                {
                    alerts.ShowPopup("Error",
                                     string.Format("Failed to create log source for '{0}': {1}", fname, e.Message),
                                     AlertFlags.Ok | AlertFlags.WarningIcon);
                    break;
                }
            }
        }
        void ExecRegex()
        {
            Regex re;

            try
            {
                string reTxt;
                if (emptyReModeIsAllowed && string.IsNullOrWhiteSpace(dialog.ReadControl(ControlId.RegExTextBox)))
                {
                    reTxt = RegularGrammar.FormatInfo.EmptyBodyReEquivalientTemplate;
                }
                else
                {
                    reTxt = dialog.ReadControl(ControlId.RegExTextBox);
                }
                re = new Regex(reTxt, headerReMode ? headerReOptions : bodyReOptions);
            }
            catch (Exception e)
            {
                alerts.ShowPopup("Failed to parse regular expression", e.Message, AlertFlags.Ok | AlertFlags.WarningIcon);
                return;
            }

            ResetReHilight();

            updateSampleEditLock = true;
            try
            {
                if (headerReMode)
                {
                    ExecHeaderReAndUpdateControls(re);
                }
                else
                {
                    ExecBodyReAndUpdateConstrol(re);
                }
                dialog.ResetSelection(ControlId.SampleLogTextBox);
            }
            finally
            {
                updateSampleEditLock = false;
            }
        }
        bool ValidateInput()
        {
            string msg = null;

            if (view[ControlId.FormatNameEdit] == "")
            {
                msg = "Format name is mandatory";
                view.SetFocus(ControlId.FormatNameEdit);
            }
            if (newFormatMode && registry.Find(view[ControlId.CompanyNameEdit], view[ControlId.FormatNameEdit]) != null)
            {
                msg = "Format with this company name/format name combination already exists";
                view.SetFocus(ControlId.FormatNameEdit);
            }
            if (msg != null)
            {
                alerts.ShowPopup("Validation", msg, AlertFlags.Ok | AlertFlags.WarningIcon);
                return(false);
            }
            return(true);
        }
        bool SaveTo(XmlNode formatNode)
        {
            var code = dialog.CodeTextBoxValue.Trim();

            try
            {
                JObject.Parse(code);                 // validate json syntax
            }
            catch (Exception e)
            {
                alerts.ShowPopup("Error", e.Message, AlertFlags.WarningIcon);
                return(false);
            }

            formatNode.SelectNodes("json/transform")
            .OfType <XmlNode>().ToList().ForEach(n => n.ParentNode.RemoveChild(n));

            var transform = formatNode.OwnerDocument.CreateElement("transform");

            transform.AppendChild(formatNode.OwnerDocument.CreateCDataSection(code));
            formatNode.SelectSingleNode("json")?.AppendChild(transform);

            return(true);
        }
Exemple #18
0
 bool GenerateGrammar()
 {
     try
     {
         var selectedLayout = importPage.GetSelectedLayout();
         if (selectedLayout is ImportNLogPage.ISimpleLayout)
         {
             NLog.LayoutImporter.GenerateRegularGrammarElementForSimpleLayout(
                 doc.DocumentElement, ((ImportNLogPage.ISimpleLayout)selectedLayout).Value, importLog);
         }
         else if (selectedLayout is ImportNLogPage.ICSVLayout)
         {
             NLog.LayoutImporter.GenerateRegularGrammarElementForCSVLayout(
                 doc.DocumentElement, ((ImportNLogPage.ICSVLayout)selectedLayout).Params, importLog);
         }
         else if (selectedLayout is ImportNLogPage.IJsonLayout)
         {
             NLog.LayoutImporter.GenerateRegularGrammarElementForJsonLayout(
                 doc.DocumentElement, ((ImportNLogPage.IJsonLayout)selectedLayout).Params, importLog);
         }
         else
         {
             throw new NLog.ImportException("bad layout");
         }
     }
     catch (NLog.ImportErrorDetectedException)
     {
         return(true);
     }
     catch (NLog.ImportException e)
     {
         alerts.ShowPopup("Error", "Failed to import the layout:\n" + e.Message, AlertFlags.Ok | AlertFlags.WarningIcon);
         return(false);
     }
     return(true);
 }