Пример #1
0
        private static Tuple <bool, string> SetXmlPath(string xmlPath = null)
        {
            string  desktopPath = FileManager.StandardPath();
            string  path;
            XmlInfo xmlInfo = XmlInfo.GetInstance;

            if (xmlPath == null)
            {
                Console.WriteLine("Insert XML path: ");
                path = Console.ReadLine();
            }
            else
            {
                path = xmlPath;
            }

            if (!XmlUtilities.IsValidPath(path))
            {
                return(new Tuple <bool, string>(false, "Error! XML path not valid"));
            }

            if (!XmlUtilities.FileExist(path))
            {
                return(new Tuple <bool, string>(false, "Error! XNL file not exist"));
            }

            xmlInfo.SetXmlPath(path);

            return(new Tuple <bool, string>(true, string.Empty));
        }
Пример #2
0
        private static int?FallbackAttributeCompletionHandler(XmlInfo info, ITextDocument textDoc, ITextView textView, IWorkspaceManager workspaceManager)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            if ((info.AttributeName == "Include" || info.AttributeName == "Update" || info.AttributeName == "Exclude" || info.AttributeName == "Remove"))
            {
                string            relativePath = info.AttributeValue;
                IWorkspace        workspace    = workspaceManager.GetWorkspace(textDoc.FilePath);
                List <Definition> matchedItems = workspace.GetItemProvenance(relativePath);

                if (matchedItems.Count == 1)
                {
                    string   absolutePath = Path.Combine(Path.GetDirectoryName(textDoc.FilePath), matchedItems[0].File);
                    FileInfo fileInfo     = new FileInfo(absolutePath);

                    if (fileInfo.Exists)
                    {
                        ServiceUtil.DTE.ItemOperations.OpenFile(fileInfo.FullName);
                        return(VSConstants.S_OK);
                    }
                }

                //Don't return the result of show in find all references, the caret may also be in a symbol,
                //  where we'd also want to go to that definition
                ShowInFar("Item Provenance", matchedItems);
            }

            return(null);
        }
Пример #3
0
        private static int?HandleGoToDefinitionOnProjectReference(XmlInfo info, ITextDocument textDoc, ITextView textView, IWorkspaceManager workspaceManager)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (info.AttributeName == "Include")
            {
                string            relativePath = info.AttributeValue;
                IWorkspace        workspace    = workspaceManager.GetWorkspace(textDoc.FilePath);
                List <Definition> matchedItems = workspace.GetItems(relativePath);

                if (matchedItems.Count == 1)
                {
                    string   absolutePath = Path.Combine(Path.GetDirectoryName(textDoc.FilePath), matchedItems[0].File);
                    FileInfo fileInfo     = new FileInfo(absolutePath);
                    if (fileInfo.Exists)
                    {
                        ServiceUtil.DTE.ItemOperations.OpenFile(fileInfo.FullName);
                        return(VSConstants.S_OK);
                        //ServiceUtil.DTE.Commands.Raise(VSConstants.CMDSETID.StandardCommandSet2K_string, (int)EditProjectFileCommandId, ref unusedArgs, ref unusedArgs);
                    }
                }
            }

            return(null);
        }
Пример #4
0
        private static int?HandleGoToDefinitionOnNuGetPackage(XmlInfo info, ITextDocument textDoc, ITextView textView, IWorkspaceManager workspaceManager)
        {
            if (PackageCompletionSource.TryGetPackageInfoFromXml(info, out string packageName, out string packageVersion) && PackageExistsOnNuGet(packageName, packageVersion, out string url))
            {
                System.Diagnostics.Process.Start(url);
                return(VSConstants.S_OK);
            }

            return(null);
        }
Пример #5
0
        private int?HandleAttributeCompletionResult(ITextDocument textDoc, XmlInfo info)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (GoToDefinitionAttributeHandlers.TryGetValue(info.TagName, out Func <XmlInfo, ITextDocument, ITextView, IWorkspaceManager, int?> handler))
            {
                return(handler(info, textDoc, TextView, _workspaceManager));
            }

            return(FallbackAttributeCompletionHandler(info, textDoc, TextView, _workspaceManager));
        }
Пример #6
0
        private static void SetXmlMainElementName(string xmlMainElementName = null)
        {
            XmlInfo xmlInfo = XmlInfo.GetInstance;

            if (xmlMainElementName == null)
            {
                Console.WriteLine("Insert XML main element name:");
                xmlMainElementName = Console.ReadLine();
            }

            xmlInfo.SetXmlMainElementName(xmlMainElementName);
        }
Пример #7
0
        private static void SetXmlNamespacePrefix(string xmlPrefix = null)
        {
            XmlInfo xmlInfo = XmlInfo.GetInstance;

            if (xmlPrefix == null)
            {
                Console.WriteLine("Insert XML namespace prefix: ");
                xmlPrefix = Console.ReadLine();
            }

            xmlInfo.SetXmlNamespacePrefix(xmlPrefix);
        }
Пример #8
0
        private static void SetXmlNamespaceUri(string xmlns = null)
        {
            XmlInfo xmlInfo = XmlInfo.GetInstance;

            if (xmlns == null)
            {
                Console.WriteLine("Insert target namespace URI (XMLNS): (Ex. http://tempuri.org/Test.xsd) ");
                xmlns = Console.ReadLine();
            }

            xmlInfo.SetXmlNamespaceUri(xmlns);
        }
Пример #9
0
        public async Task <QuickInfoItem> GetQuickInfoItemAsync(IAsyncQuickInfoSession session, CancellationToken cancellationToken)
        {
            if (!session.TextView.TextBuffer.Properties.TryGetProperty(typeof(ITextDocument), out ITextDocument textDoc))
            {
                return(null);
            }

            SnapshotPoint?triggerPoint = session.GetTriggerPoint(session.TextView.TextSnapshot);

            if (triggerPoint == null)
            {
                return(null);
            }

            int pos = triggerPoint.Value.Position;

            if (!PackageCompletionSource.IsInRangeForPackageCompletion(session.TextView.TextSnapshot, pos, out Span s, out string packageId, out string packageVersion, out string type))
            {
                XmlInfo info = XmlTools.GetXmlInfo(session.TextView.TextSnapshot, pos);

                if (info != null)
                {
                    IWorkspace    workspace      = workspace = _workspaceManager.GetWorkspace(textDoc.FilePath);
                    string        evaluatedValue = workspace.GetEvaluatedPropertyValue(info.AttributeValue);
                    ITrackingSpan target         = session.TextView.TextSnapshot.CreateTrackingSpan(new Span(info.AttributeValueStart, info.AttributeValueLength), SpanTrackingMode.EdgeNegative);

                    if (info.AttributeName == "Condition")
                    {
                        try
                        {
                            bool isTrue = workspace.EvaluateCondition(info.AttributeValue);
                            evaluatedValue = $"Expanded value: {evaluatedValue}\nEvaluation result: {isTrue}";
                            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                            return(new QuickInfoItem(target, evaluatedValue));
                        }
                        catch (Exception ex)
                        {
                            Debug.Fail(ex.ToString());
                        }
                    }
                    else
                    {
                        evaluatedValue = $"Value(s):\n    {string.Join("\n    ", evaluatedValue.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))}";
                        await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                        return(new QuickInfoItem(target, evaluatedValue));
                    }
                }
            }
Пример #10
0
        private static Tuple <bool, string> ValidateXml()
        {
            XmlInfo xmlInfo        = XmlInfo.GetInstance;
            var     schemaCompiler = new SchemaCompiler(new StreamReader(xmlInfo.GetXsdPath()));
            var     xmlString      = File.ReadAllText(xmlInfo.GetXmlPath());

            var validateXml = XmlUtilities.ValidateXmlAgainstXsd(xmlString, schemaCompiler);

            if (!validateXml.Item1)
            {
                return(new Tuple <bool, string>(false, validateXml.Item2));
            }

            return(new Tuple <bool, string>(true, string.Empty));
        }
Пример #11
0
        public static bool IsInRangeForPackageCompletion(ITextSnapshot snapshot, int pos, out Span span, out string packageName, out string packageVersion, out string completionType)
        {
            XmlInfo info = XmlTools.GetXmlInfo(snapshot, pos);

            if (info?.AttributeName != null && TryGetPackageInfoFromXml(info, out packageName, out packageVersion) && AttributeToCompletionTypeMap.TryGetValue(info.AttributeName, out completionType))
            {
                span = new Span(info.AttributeValueStart, info.AttributeValueLength);
                return(true);
            }

            completionType = null;
            packageName    = null;
            packageVersion = null;
            span           = default(Span);
            return(false);
        }
Пример #12
0
        public static bool TryGetPackageInfoFromXml(XmlInfo info, out string packageName, out string packageVersion)
        {
            if (info?.AttributeName != null &&
                (info.TagName == "PackageReference" || info.TagName == "DotNetCliToolReference") &&
                info.AttributeName != null && AttributeToCompletionTypeMap.ContainsKey(info.AttributeName) &&
                info.TryGetElement(out XElement element))
            {
                XAttribute name    = element.Attribute(XName.Get("Include"));
                XAttribute version = element.Attribute(XName.Get("Version"));
                packageName    = name?.Value;
                packageVersion = version?.Value;
                return(true);
            }

            packageName    = null;
            packageVersion = null;
            return(false);
        }
Пример #13
0
        private int?HandleGoToDefinition()
        {
            TextView.TextBuffer.Properties.TryGetProperty(typeof(ITextDocument), out ITextDocument textDoc);

            XmlInfo info = XmlTools.GetXmlInfo(TextView.TextSnapshot, TextView.Caret.Position.BufferPosition.Position);

            if (info != null)
            {
                int?attributeCompletionResult = HandleAttributeCompletionResult(textDoc, info);

                if (attributeCompletionResult.HasValue)
                {
                    return(attributeCompletionResult.Value);
                }
            }

            IWorkspace        workspace   = _workspaceManager.GetWorkspace(textDoc.FilePath);
            List <Definition> definitions = workspace.ResolveDefinition(textDoc.FilePath, TextView.TextSnapshot.GetText(), TextView.Caret.Position.BufferPosition.Position);

            if (definitions.Count == 1)
            {
                DTE dte = ServiceUtil.DTE;
                dte.MainWindow.Activate();

                using (var state = new NewDocumentStateScope(__VSNEWDOCUMENTSTATE.NDS_Provisional, Guid.Parse(ProjectFileToolsPackage.PackageGuidString)))
                {
                    Window w = dte.ItemOperations.OpenFile(definitions[0].File, EnvDTE.Constants.vsViewKindTextView);

                    if (definitions[0].Line.HasValue)
                    {
                        ((TextSelection)dte.ActiveDocument.Selection).GotoLine(definitions[0].Line.Value, true);
                    }
                }

                return(VSConstants.S_OK);
            }
            else if (definitions.Count > 1)
            {
                return(ShowInFar("Symbol Definition", definitions));
            }

            return(null);
        }
Пример #14
0
        public static XmlNodeList LoadXmlNodeList(string _xmlName, string _nodeName)
        {
            XmlDocument document;

            if (xmlDocumentList.ContainsKey(_xmlName))
            {
                document = xmlDocumentList[_xmlName].document;
                xmlDocumentList[_xmlName].AddRef();
            }
            else
            {
                string filePath;
                #if UNITY_EDITOR
                filePath = Application.dataPath + "/Resources/XmlFiles/";
                #elif UNITY_ANDROID
                filePath = Application.persistentDataPath + "/Resources/XmlFiles/";
                #else
                filePath = Application.dataPath + "/Resources/XmlFiles/";
                #endif
                filePath += string.Format("{0}.xml", _xmlName);

                document = new XmlDocument();
                if (File.Exists(filePath))
                {
                    document.Load(filePath);
                }
                else
                {
                    TextAsset tmpXml = Resources.Load(Path.Combine("XmlFiles", _xmlName)) as TextAsset;
                    document.LoadXml(tmpXml.text);
                    Resources.UnloadAsset(tmpXml);
                }

                XmlInfo xmlInfo = new XmlInfo(document);
                xmlDocumentList.Add(_xmlName, xmlInfo);
                xmlInfo.AddRef();
            }

            return(document.SelectNodes(string.Format("{0}/{1}", _xmlName, _nodeName)));
        }
Пример #15
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        private static bool ConsoleInteractiveMode()
        {
            XmlInfo xmlInfo = XmlInfo.GetInstance;

            xmlInfo.ClearData();

            var xsdData = LoadXsdData();

            if (!xsdData.Item1)
            {
                Console.WriteLine(xsdData.Item2);
                return(false);
            }

            var xmlData = LoadXmlData();

            if (!xmlData.Item1)
            {
                Console.WriteLine(xmlData.Item2);
                return(false);
            }

            if (string.Equals(xmlInfo.GetXsdPath(), xmlInfo.GetXmlPath()))
            {
                Console.WriteLine("Error! XSD and XML path are the same");
                return(false);
            }

            var validateXml = ValidateXml();

            if (!validateXml.Item1)
            {
                Console.WriteLine("XML validation against XSD schema failed!");
                Console.WriteLine(validateXml.Item2);
                return(false);
            }

            Console.WriteLine(SaveHeaderAndBiFile().Item2);
            return(true);
        }
Пример #16
0
        public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (pguidCmdGroup == _vSStd97CmdIDGuid && cCmds > 0 && prgCmds[0].cmdID == (uint)VSConstants.VSStd97CmdID.GotoDefn)
            {
                prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED);
                return(VSConstants.S_OK);
            }

            if (pguidCmdGroup == _vSStd97CmdIDGuid && cCmds > 0 && prgCmds[0].cmdID == (uint)VSConstants.VSStd97CmdID.FindReferences)
            {
                TextView.TextBuffer.Properties.TryGetProperty(typeof(ITextDocument), out ITextDocument textDoc);
                XmlInfo info = XmlTools.GetXmlInfo(TextView.TextSnapshot, TextView.Caret.Position.BufferPosition.Position);
                if (info?.AttributeName != null)
                {
                    prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED);
                    return(VSConstants.S_OK);
                }
            }

            return(Next?.QueryStatus(pguidCmdGroup, cCmds, prgCmds, pCmdText) ?? (int)Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED);
        }
Пример #17
0
        public static bool TryHealOrAdvanceAttributeSelection(ITextSnapshot snapshot, ref int pos, out Span targetSpan, out string newText, out bool isHealingRequired)
        {
            XmlInfo info = XmlTools.GetXmlInfo(snapshot, pos);

            if (info?.AttributeName == null || !info.TryGetElement(out XElement element) || info.TagName != "PackageReference" && info.TagName != "DotNetCliToolReference")
            {
                isHealingRequired = false;
                newText           = null;
                targetSpan        = default(Span);
                return(false);
            }

            XAttribute version = element.Attribute(XName.Get("Version"));

            if (version == null)
            {
                isHealingRequired = true;
                element.SetAttributeValue(XName.Get("Version"), "");
                newText = element.ToString();
                string versionString = "Version=\"";
                pos        = newText.IndexOf(versionString) + versionString.Length + info.TagStart;
                targetSpan = new Span(info.TagStart, info.RealDocumentLength);
                return(true);
            }

            newText           = info.ElementText;
            isHealingRequired = info.IsModified;
            int  versionIndex = info.ElementText.IndexOf("Version");
            int  quoteIndex   = info.ElementText.IndexOf('"', versionIndex);
            int  proposedPos  = info.TagStart + quoteIndex + 1;
            bool move         = info.AttributeName != "Version";

            pos        = proposedPos;
            targetSpan = new Span(info.TagStart, info.RealDocumentLength);
            return(move);
        }
Пример #18
0
        private int?HandleFindAllReferences()
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            if (!TextView.TextBuffer.Properties.TryGetProperty(typeof(ITextDocument), out ITextDocument textDoc))
            {
                return(null);
            }

            XmlInfo info = XmlTools.GetXmlInfo(TextView.TextSnapshot, TextView.Caret.Position.BufferPosition.Position);

            if (info != null)
            {
                if (info.AttributeName == "Include" || info.AttributeName == "Update" || info.AttributeName == "Exclude" || info.AttributeName == "Remove")
                {
                    string            relativePath = info.AttributeValue;
                    IWorkspace        workspace    = _workspaceManager.GetWorkspace(textDoc.FilePath);
                    List <Definition> matchedItems = workspace.GetItems(relativePath);

                    if (matchedItems.Count == 1)
                    {
                        string   absolutePath = Path.Combine(Path.GetDirectoryName(textDoc.FilePath), matchedItems[0].File);
                        FileInfo fileInfo     = new FileInfo(absolutePath);

                        if (fileInfo.Exists)
                        {
                            ServiceUtil.DTE.ItemOperations.OpenFile(fileInfo.FullName);
                            return(VSConstants.S_OK);
                        }
                    }

                    return(ShowInFar("Files Matching Glob", matchedItems));
                }
            }

            return(null);
        }
Пример #19
0
 public BuilderHelper()
 {
     Xml  = new XmlInfo();
     Data = new DataInfo();
 }
Пример #20
0
        private static bool ConsoleArgumentsMode(string[] args, bool interactiveMode)
        {
            string xsdPath            = null;
            string xmlPath            = null;
            string xmlns              = null;
            string xmlPrefix          = null;
            string xmlMainElementName = null;
            string savePath           = null;

            for (int i = 0; i < args.Length; i++)
            {
                switch (args[i])
                {
                case xsdPath_opt:
                    xsdPath = args[i + 1];
                    continue;

                case xmlPath_opt:
                    xmlPath = args[i + 1];
                    continue;

                case xmlns_opt:
                    xmlns = args[i + 1];
                    continue;

                case xmlpx_opt:
                    xmlPrefix = args[i + 1];
                    continue;

                case xmlMainElement_opt:
                    xmlMainElementName = args[i + 1];
                    continue;

                case output_opt:
                    savePath = args[i + 1];
                    continue;

                case interactive_opt:
                    continue;
                }
            }


            if (!interactiveMode && (xsdPath == null || xmlPath == null || xmlns == null || xmlPrefix == null ||
                                     xmlMainElementName == null))
            {
                Console.WriteLine("Wrong Arguments! Application not in interactive mode. Mandatory arguments: [ -xsd | -xml | -xns | -xpx | -xen ]");
                Console.WriteLine("Help mode: XmlBinaryConverter -help");
                Console.WriteLine("Interactive mode: XmlBinaryConverter -it");
                return(false);
            }


            XmlInfo xmlInfo = XmlInfo.GetInstance;

            xmlInfo.ClearData();

            var xsdData = LoadXsdData(xsdPath);

            if (!xsdData.Item1)
            {
                Console.WriteLine(xsdData.Item2);
                return(false);
            }

            var xmlData = LoadXmlData(xmlPath, xmlns, xmlPrefix, xmlMainElementName);

            if (!xmlData.Item1)
            {
                Console.WriteLine(xmlData.Item2);
                return(false);
            }

            if (string.Equals(xmlInfo.GetXsdPath(), xmlInfo.GetXmlPath()))
            {
                Console.WriteLine("Error! XSD and XML path are the same");
                return(false);
            }

            var validateXml = ValidateXml();

            if (!validateXml.Item1)
            {
                Console.WriteLine("XML validation against XSD schema failed!");
                Console.WriteLine(validateXml.Item2);
                return(false);
            }

            Console.WriteLine(SaveHeaderAndBiFile(savePath).Item2);
            return(true);
        }
Пример #21
0
 public BuilderHelper()
 {
     Xml = new XmlInfo();
     Data = new DataInfo();
 }
Пример #22
0
 private static void node(XmlInfo info, string config_key, string config_data, string name = "data", string flag = "configuration")
 {
     info.key = info.config.CreateAttribute(flag);
     info.xmlnode = info.config.CreateElement(name);
     info.key.Value = config_key;
     info.xmlnode.Attributes.Append(info.key);
     info.xmlnode.InnerText = config_data;
     info.conf.AppendChild(info.xmlnode);
 }
Пример #23
0
        /// <summary>
        /// Saves the local config.
        /// </summary>
        public static void SaveLocalConfig()
        {
            Core.History("SaveLocalConfig()");
            try
            {
                string config_file = Core.LocalPath() + "config.xml";
                if (File.Exists(config_file))
                {
                    File.Copy(config_file, config_file + "~", true);
                }
                XmlDocument document = new XmlDocument();
                XmlNode xmlNode = document.CreateElement("huggle");
                System.Xml.XmlNode curr = null;
                XmlInfo info = new XmlInfo();
                info.xmlnode = curr;
                info.config = document;
                info.conf = xmlNode;

                node(info, "Config.AutoAdvance", Config.AutoAdvance.ToString());
                node(info, "Config.AutoWarn", Config.AutoWarn.ToString());
                node(info, "Config.AutoWhitelist", Config.AutoWhitelist.ToString());
                node(info, "Config.BlockMessage", Config.BlockMessage);
                node(info, "Config.BlockMessageDefault", Config.BlockMessageDefault.ToString());
                node(info, "Config.BlockMessageIndef", Config.BlockMessageIndef);
                node(info, "Config.BlockReason", Config.BlockReason);
                node(info, "Config.BlockSummary", Config.BlockSummary);
                node(info, "Config.BlockTime", Config.BlockTime);
                node(info, "Config.BlockTimeAnon", Config.BlockTimeAnon);
                node(info, "Config.ConfirmIgnored", Config.ConfirmIgnored.ToString());
                node(info, "Config.ConfirmMultiple", Config.ConfirmMultiple.ToString());
                node(info, "Config.ConfirmPage", Config.ConfirmPage.ToString());
                node(info, "Config.ConfirmRange", Config.ConfirmRange.ToString());
                node(info, "Config.ConfirmSame", Config.ConfirmSame.ToString());
                node(info, "Config.ConfirmSelfRevert", Config.ConfirmSelfRevert.ToString());
                node(info, "Config.ConfirmWarned", Config.ConfirmWarned.ToString());
                node(info, "Config.ContribsBlockSize", Config.ContribsBlockSize.ToString());
                node(info, "Config.CountBatchSize", Config.CountBatchSize.ToString());
                node(info, "Config.DefaultQueue", Config.DefaultQueue);
                node(info, "Config.DefaultQueue2", Config.DefaultQueue2);
                node(info, "Config.DefaultSummary", Config.DefaultSummary);
                node(info, "Config.Delete", Config.Delete.ToString());
                node(info, "Config.DiffFontSize", Config.DiffFontSize);
                node(info, "Config.Email", Config.Email.ToString());
                node(info, "Config.EmailSubject", Config.EmailSubject);
                node(info, "Config.ExtendReports", Config.ExtendReports.ToString());
                node(info, "Config.FeedSize", Config.FeedSize.ToString());
                node(info, "Config.FullHistoryBlockSize", Config.FullHistoryBlockSize.ToString());
                node(info, "Config.HistoryBlockSize", Config.HistoryBlockSize.ToString());
                node(info, "Config.HistoryLenght", Config.HistoryLenght.ToString());
                node(info, "Config.HistoryScrollSpeed", Config.HistoryScrollSpeed.ToString());
                node(info, "Config.HistoryTrim", Config.HistoryTrim.ToString());
                node(info, "Config.IrcConnectionTimeout", Config.IrcConnectionTimeout.ToString());
                node(info, "Config.IrcMode", Config.IrcMode.ToString());
                node(info, "Config.IrcPort", Config.IrcPort.ToString());
                node(info, "Config.IrcServer", Config.IrcServer.ToString());
                node(info, "Config.ItemSize", Config.ItemSize.ToString());
                node(info, "Config.Language", Config.Language.ToString());
                node(info, "Config.LogFile", Config.LogFile.ToString());
                node(info, "Config.Project", Config.Project);

                foreach (KeyValuePair<string, string> hh in Config.Projects)
                {
                    node(info, hh.Key, hh.Value, "project", "name");
                }

                document.AppendChild(xmlNode);

                document.Save(config_file);

                if (File.Exists(config_file + "~"))
                {
                    File.Delete(config_file + "~");
                }
            }
            catch (Exception fail)
            {
                Core.ExceptionHandler(fail);
            }
        }
Пример #24
0
    //xml读取 获取内容
    public XmlInfo GetXmlContent(string id, string type)
    {
        XmlInfo info = new XmlInfo();

        if (!Directory.Exists(dir))
        {
            return(info);
        }
        string m_data_path = xmlFileName;

        if (!File.Exists(m_data_path))
        {
            return(info);
        }
        try
        {
            XmlDocument xml = new XmlDocument();
            xml.Load(m_data_path);
            XmlNode root     = xml.SelectSingleNode("UNI");
            XmlNode typeNode = root.SelectSingleNode(type);
            //根据id搜索节点并返回内容
            XmlNodeList nodes = typeNode.SelectNodes("Info");
            foreach (XmlNode item in nodes)
            {
                if (item.Attributes["id"].Value == id)
                {
                    if (item.InnerText != null)
                    {
                        info.id   = id;
                        info.type = type;
                        if (item.Attributes["date"] != null)//创建时间
                        {
                            info.date = item.Attributes["date"].Value;
                        }
                        if (item.Attributes["alter"] != null)//修改时间
                        {
                            info.alter = item.Attributes["alter"].Value;
                        }
                        if (item.Attributes["state"] != null)//状态
                        {
                            info.state = item.Attributes["state"].Value;
                        }
                        if (item.Attributes["title"] != null)//标题
                        {
                            info.title = item.Attributes["title"].Value;
                        }
                        if (item.Attributes["attrs"] != null)//属性
                        {
                            info.attrs = item.Attributes["attrs"].Value;
                        }
                        string str = item.InnerText;
                        if (str.Length > 2)
                        {
                            info.content = str.Substring(1, str.Length - 2);
                        }
                        else
                        {
                            info.content = "";
                        }
                        return(info);
                    }
                }
            }
            return(info);
        }
        catch (Exception ex)
        {
            //info.content="<span style='display:none;'>错误:" + ex.Message + "</span>";
            return(info);
        }
    }
Пример #25
0
    //获取xml内容列表
    public XmlInfo[] GetXmlList(string type, int startline, int need, int start, int end, bool byContent)
    {
        if (!Directory.Exists(dir))
        {
            return(null);
        }
        string m_data_path = xmlFileName;

        if (!File.Exists(m_data_path))
        {
            return(null);
        }
        try
        {
            XmlDocument xml = new XmlDocument();
            xml.Load(m_data_path);
            XmlNode root     = xml.SelectSingleNode("UNI");
            XmlNode typeNode = root.SelectSingleNode(type);
            //根据id搜索节点并返回内容
            XmlNodeList    nodes = typeNode.SelectNodes("Info");
            List <XmlInfo> list  = new List <XmlInfo>();
            int            ori   = 0;
            int            line  = startline + need;
            foreach (XmlNode item in nodes)
            {
                if (item.Attributes["date"] == null)
                {
                    continue;
                }
                //日期
                int date = Convert.ToInt32(item.Attributes["date"].Value.Substring(0, 8));
                if (date < start)
                {
                    continue;
                }
                if (date > end)
                {
                    break;
                }
                //条目
                ori++;
                if (ori < startline)
                {
                    continue;
                }
                if (ori >= line)
                {
                    break;
                }
                //
                XmlInfo info = new XmlInfo();
                info.id   = item.Attributes["id"].Value;
                info.type = type;
                if (byContent)
                {
                    string str = item.InnerText;
                    if (str.Length > 2)
                    {
                        info.content = str.Substring(1, str.Length - 2);
                    }
                    else
                    {
                        info.content = "";
                    }
                }
                info.date = item.Attributes["date"].Value;
                if (item.Attributes["alter"] != null)//修改时间
                {
                    info.alter = item.Attributes["alter"].Value;
                }
                if (item.Attributes["state"] != null)//状态
                {
                    info.state = item.Attributes["state"].Value;
                }
                if (item.Attributes["title"] != null)//标题
                {
                    info.title = item.Attributes["title"].Value;
                }
                if (item.Attributes["attrs"] != null)
                {
                    info.attrs = item.Attributes["attrs"].Value;
                }
                list.Add(info);
            }
            return(list.ToArray());
        }
        catch (Exception ex)
        {
            return(null);
        }
    }
Пример #26
0
        public string GetMapInfo()
        {
            XmlInfo xmlInfo = ReadXml.GetXmlInfo();

            return(JsonConvert.SerializeObject(xmlInfo));
        }
Пример #27
0
        private static void Main(string[] args)
        {
            XmlInfo xmlInfo = XmlInfo.GetInstance;

            if (args == null)
            {
                Console.WriteLine("Bad args parameter!");
                return;
            }

            if (args.Length == 0)
            {
                var interactiveMode = true;
                while (interactiveMode)
                {
                    var consoleModeResult = ConsoleInteractiveMode();

                    if (consoleModeResult)
                    {
                        Console.WriteLine("----");
                        Console.WriteLine("Everything went as planned! Reload: Y/N ?");

                        var readKey = Console.ReadLine();
                        if (readKey == null || readKey.ToUpper() != "Y")
                        {
                            interactiveMode = false;
                        }
                    }
                    else
                    {
                        Console.WriteLine("----");
                        Console.WriteLine("Something went wrong! Reload: Y/N ?");

                        var readKey = Console.ReadLine();
                        if (readKey == null || readKey.ToUpper() != "Y")
                        {
                            interactiveMode = false;
                        }
                    }
                }

                Console.WriteLine("Press any key to exit...");
                Console.Read();
                return;
            }

            if (args[0] == "-help")
            {
                ShowArgumentsHelp();
            }

            if (IsConsoleInInteractiveMode(args))
            {
                Console.WriteLine($"Time start : {DateTime.Now}");
                Console.WriteLine("----");
                Console.WriteLine("");

                var consoleArgumentsModeResult = ConsoleArgumentsMode(args, true);

                if (consoleArgumentsModeResult)
                {
                    Console.WriteLine("");
                    Console.WriteLine("Everything went as planned!");
                    Console.WriteLine("----");
                    Console.WriteLine($"Time end : {DateTime.Now}");
                    return;
                }

                Console.WriteLine("");
                Console.WriteLine("Something went wrong!");
                Console.WriteLine("----");
                Console.WriteLine($"Time end : {DateTime.Now}");
                Console.WriteLine("Press any key to exit...");
                Console.Read();
            }
            else
            {
                // save output to file
                // if the args are not valid an error file will be created
                using StreamWriter writer = new StreamWriter($"{FileManager.StandardPath()}\\log.txt");

                Console.SetOut(writer);

                Console.WriteLine($"Time start : {DateTime.Now}");
                Console.WriteLine("----");
                Console.WriteLine("");

                var consoleArgumentsModeResult = ConsoleArgumentsMode(args, false);

                if (!consoleArgumentsModeResult)
                {
                    Console.WriteLine("");
                    Console.WriteLine("----");
                    Console.WriteLine("Something went wrong!");
                    Console.WriteLine("----");
                    Console.WriteLine("");
                }

                Console.WriteLine("");
                Console.WriteLine("----");
                Console.WriteLine($"Time end : {DateTime.Now}");
            }
        }