Beispiel #1
0
        public void Write()
        {
            string            outputFileName = UserData.Create(this.savePath) + this.saveName;
            XmlWriterSettings settings       = new XmlWriterSettings();

            settings.Indent   = true;
            settings.Encoding = Encoding.UTF8;
            XmlWriter writer = (XmlWriter)null;

            try
            {
                writer = XmlWriter.Create(outputFileName, settings);
                writer.WriteStartDocument();
                writer.WriteStartElement(this.rootName);
                foreach (Data data in this.dataList)
                {
                    data.Write(writer);
                }
                writer.WriteEndElement();
                writer.WriteEndDocument();
            }
            finally
            {
                writer?.Close();
            }
        }
        /// <summary>
        /// Generate the to-be signed content for the credential.
        /// </summary>
        ///
        /// <returns>
        /// Raw XML representing the ContentSection of the info secttion.
        /// </returns>
        ///
        internal string GetContentSection()
        {
            StringBuilder     requestXml = new StringBuilder(2048);
            XmlWriterSettings settings   = SDKHelper.XmlUnicodeWriterSettings;

            XmlWriter writer = null;

            try
            {
                writer = XmlWriter.Create(requestXml, settings);

                writer.WriteStartElement("content");

                writer.WriteStartElement("app-id");
                writer.WriteString(_webHealthVaultConfiguration.MasterApplicationId.ToString());
                writer.WriteEndElement();

                writer.WriteElementString("hmac", HealthVaultConstants.Cryptography.HmacAlgorithm);

                writer.WriteStartElement("signing-time");
                writer.WriteValue(SDKHelper.XmlFromInstant(SystemClock.Instance.GetCurrentInstant()));
                writer.WriteEndElement();

                writer.WriteEndElement(); // content
            }
            finally
            {
                writer?.Close();
            }

            return(requestXml.ToString());
        }
        public static async void PublishHelpFile(String path, ModuleObject module, ProgressBar pb)
        {
            XmlWriter     writer = null;
            StringBuilder SB     = new StringBuilder();

            if (module.Cmdlets.Count == 0)
            {
                return;
            }
            pb.Value      = 0;
            pb.Visibility = Visibility.Visible;
            XmlWriterSettings settings = new XmlWriterSettings {
                Indent           = true,
                IndentChars      = ("	"),
                NewLineHandling  = NewLineHandling.None,
                ConformanceLevel = ConformanceLevel.Document
            };

            try {
                writer = XmlWriter.Create(path, settings);
                writer.WriteStartDocument();
                await XmlProcessor.XmlGenerateHelp(SB, module.Cmdlets, pb, module.IsOffline);

                writer.WriteRaw(SB.ToString());
            } finally {
                pb.Visibility = Visibility.Collapsed;
                writer?.Close();
            }
        }
        /// <summary>
        /// 将对象序列化成Xml字符串。
        /// </summary>
        /// <typeparam name="T">对象的类型。</typeparam>
        /// <param name="sourceObject">被序列化的对象。</param>
        /// <param name="prefix">The prefix associated with an XML namespace.</param>
        /// <param name="ns">An XML namespace.</param>
        /// <returns></returns>
        public static string SerializeObjectToXmlString <T>(T sourceObject, string prefix = "", string ns = "")
        {
            string       xmlString    = null;
            StringWriter stringWriter = null;
            XmlWriter    xmlWriter    = null;

            try
            {
                stringWriter = new StringWriter();

                var xmlNamespaces = new XmlSerializerNamespaces();
                xmlNamespaces.Add(prefix, ns);
                var settings = new XmlWriterSettings {
                    Indent = true, IndentChars = "\t"
                };
                xmlWriter = XmlWriter.Create(stringWriter, settings);

                var serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(xmlWriter, sourceObject, xmlNamespaces);
                xmlString = xmlWriter.ToString();
            }
            finally
            {
                xmlWriter?.Close();
                xmlWriter?.Dispose();
                stringWriter?.Close();
                stringWriter?.Dispose();
            }

            return(xmlString);
        }
Beispiel #5
0
        protected void btnWrite_Click(object sender, EventArgs e)
        {
            //得到要写入的文件在服务器磁盘上的绝对路径
            var xmlFilePath = Server.MapPath("Employees4Write.xml");
            //声明一个XmlWriter类型的对象writer
            XmlWriter writer = null;

            try
            {
                //创建XmlWriter对象,参数为要写入的文件路径
                writer = XmlWriter.Create(xmlFilePath);

                //开始写XML文档
                //写入XML声明,其中参数控制standalone的值(true/false)
                writer.WriteStartDocument(false);
                //写入注释
                writer.WriteComment("This XML file represents the details of an employee");
                //从根节点开始
                //写入根元素employees的开始标签
                writer.WriteStartElement("employees");
                //写入元素employee的开始标签
                writer.WriteStartElement("employee");
                //在employee元素中写入属性:id="1"
                writer.WriteAttributeString("id", "1");
                //写入元素name的开始标签
                writer.WriteStartElement("name");
                //写入元素字符串<firstName>Nancy</firstName>
                writer.WriteElementString("firstName", "Nancy");
                //写入元素字符串<lastName>Davolio</lastName>
                writer.WriteElementString("lastName", "Davolio");
                //写入结束标签(name元素的)
                writer.WriteEndElement();
                //写入元素字符串<city>Seattle</city>
                writer.WriteElementString("city", "Seattle");
                //写入元素字符串<state>WA</state>
                writer.WriteElementString("state", "WA");
                //写入元素字符串<zipCode>98122</zipCode>
                writer.WriteElementString("zipCode", "98122");
                //写入结束标签(employee的)
                writer.WriteEndElement();
                //写入结束标签(根元素employees的)
                writer.WriteEndDocument();
                //将对象数据写入XML文档中
                writer.Flush();
                //在页面上输出成功信息
                Response.Write("文件写入成功");
            }
            catch (Exception ex) //捕捉异常
            {
                //输出异常消息
                Response.Write(ex.Message);
            }
            finally
            {
                //若writer对象不为null
                //关闭XmlWriter
                writer?.Close();
            }
        }
Beispiel #6
0
        //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

        /// <summary>
        /// Save the obj to an stream.
        /// </summary>
        /// <typeparam name="Tobj">Type of the object to save</typeparam>
        /// <param name="obj">Object to save</param>
        /// <param name="stream">Stream to save the object to</param>
        /// <param name="compress">Compress the file using GZip or not</param>
        /// <param name="closeStreamAfterWriting">Close the stream after writing or not</param>
        public static void SaveObjectToStream <Tobj>(this Tobj obj, Stream stream, bool compress, bool closeStreamAfterWriting)
        {
            if (obj == null)
            {
                return;
            }

            GZipStream compressedStream = null;
            XmlWriter  writer           = null;

            try
            {
                List <Type> knownTypes = new List <Type>();

                Type objType = typeof(Tobj);
                if (objType.IsGenericType && objType.GetGenericTypeDefinition() == typeof(List <>))
                {
                    knownTypes.Add(objType);
                    objType = objType.GetGenericArguments()[0];
                }
                else if (objType.IsArray)
                {
                    knownTypes.Add(objType);
                    objType = objType.GetElementType();
                }

                knownTypes.AddRange(objType.GetProperties().Select(p => p.PropertyType));
                Assembly    executingAssembly = Assembly.GetExecutingAssembly();
                List <Type> derivedTypes      = executingAssembly.GetTypes().Where(t => objType.IsAssignableFrom(t)).ToList();
                knownTypes.AddRange(derivedTypes);

                if (compress)
                {
                    compressedStream = new GZipStream(stream, CompressionMode.Compress, false);
                }
                writer = XmlWriter.Create(compress ? (Stream)compressedStream : stream);
                DataContractSerializer serializer = new DataContractSerializer(typeof(Tobj), knownTypes);
                serializer.WriteObject(writer, obj);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                writer?.Flush();
                writer?.Close();
                compressedStream?.Close();
                if (closeStreamAfterWriting)
                {
                    stream?.Close();
                }
            }
        }
Beispiel #7
0
 private static void ReleaseXmlWriter(XmlWriter writer)
 {
     try
     {
         writer?.Flush();
         writer?.Close();
     }
     catch (IOException ex)
     {
         ILogService logService = TestflowRunner.GetInstance().LogService;
         logService.Print(LogLevel.Error, CommonConst.PlatformLogSession, 0, ex, ex.Message);
         throw new TestflowRuntimeException(ModuleErrorCode.SerializeFailed, ex.Message, ex);
     }
 }
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // dispose managed state (managed objects)
                    semaphoreSlim.Dispose();
                    xmlWriter?.Close();
                    xmlWriter?.Dispose();
                }

                // free unmanaged resources (unmanaged objects) and override finalizer
                // set large fields to null
                disposedValue = true;
            }
        }
        /// <summary>
        /// 将对象序列化为Xml文件。
        /// </summary>
        /// <param name="sourceObject">源对象。</param>
        /// <param name="targetFile">序列化文件存储路径。</param>
        /// <param name="prefix">The prefix associated with an XML namespace.</param>
        /// <param name="ns">An XML namespace.</param>
        public static void SerializeObjectToXmlFile(object sourceObject, string targetFile, string prefix = "", string ns = "")
        {
            XmlWriter xmlWriter = null;

            try
            {
                var xmlNamespaces = new XmlSerializerNamespaces();
                xmlNamespaces.Add(prefix, ns);
                var settings = new XmlWriterSettings {
                    Indent = true, IndentChars = "\t"
                };
                xmlWriter = XmlWriter.Create(targetFile, settings);
                var xmlSerializer = new XmlSerializer(sourceObject.GetType());
                xmlSerializer.Serialize(xmlWriter, sourceObject, xmlNamespaces);
            }
            finally
            {
                xmlWriter?.Close();
                xmlWriter?.Dispose();
            }
        }
Beispiel #10
0
 /// <summary>
 /// Take the current settings configuration file and save it to the app data file location.
 /// </summary>
 public void SaveConfigurationFile()
 {
     XmlWriter writer = null;
     var xmlWriterSettings = new XmlWriterSettings { Indent = true };
     File.Create(_configurationLocation).Dispose();
     try
     {
         using (writer = XmlWriter.Create(_configurationLocation, xmlWriterSettings))
         {
             var serializer = new XmlSerializer(typeof(Configuration));
             serializer.Serialize(writer, _configuration);
         }
     }
     catch(Exception ex)
     {
         _logger.LogException(ex,"An error occured while attempting to print the configuration file.");
     }
     finally
     {
         writer?.Close();
     }
 }
Beispiel #11
0
        public string Serialize(Reporter reporter)
        {
            string                  str = "";
            StringWriter            sw  = null;
            XmlWriter               xw  = null;
            XmlSerializerNamespaces ns  = null;

            try
            {
                XmlWriterSettings settings = new XmlWriterSettings()
                {
                    Encoding           = Encoding.UTF8,
                    Indent             = true,
                    OmitXmlDeclaration = true
                };
                ns = new XmlSerializerNamespaces();
                ns.Add(string.Empty, string.Empty);

                sw = new StringWriter();
                xw = XmlWriter.Create(sw, settings);

                xmlSerializer.Serialize(xw, this, ns);
                str = sw.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                xw?.Close();
                xw?.Dispose();
                sw?.Close();
                sw?.Dispose();
            }
            return(str);
        }
Beispiel #12
0
    public static void SaveScene(bool timerActive, float scenelength, bool timerVisable, int audioNumber, string backgroundName)
    {
        xmlDoc = XmlWriter.Create((xmlDefaultPath + projectsMapName + tempName), writerSettings);
        xmlDoc.WriteStartDocument();
        xmlDoc.WriteStartElement("Scene");

        xmlDoc.WriteStartElement("SceneProperties");
        xmlDoc.WriteElementString("TimerActive", timerActive.ToString());
        xmlDoc.WriteElementString("Scenelength", scenelength.ToString());
        xmlDoc.WriteElementString("TimerVisable", timerVisable.ToString());
        xmlDoc.WriteElementString("AudioNumber", audioNumber.ToString());
        xmlDoc.WriteElementString("BackgroundName", backgroundName.ToString());

        xmlDoc.WriteEndElement();

        xmlDoc.WriteStartElement("Fires");
        #region FireObjects
        foreach(Fire FireObj in fireObjects) {
            xmlDoc.WriteStartElement("Fire");
            //Save the name
            xmlDoc.WriteElementString("Name", FireObj.obj.name);

            //Save position of the object
            xmlDoc.WriteStartElement("Position");
            xmlDoc.WriteElementString("posX", FireObj.obj.transform.position.x.ToString());
            xmlDoc.WriteElementString("posY", FireObj.obj.transform.position.y.ToString());
            xmlDoc.WriteElementString("posZ", FireObj.obj.transform.position.z.ToString());
            xmlDoc.WriteEndElement();

            //Save rotatie
            xmlDoc.WriteStartElement("Rotation");
            xmlDoc.WriteElementString("RotationX", FireObj.obj.transform.rotation.x.ToString());
            xmlDoc.WriteElementString("RotationY", FireObj.obj.transform.rotation.y.ToString());
            xmlDoc.WriteElementString("RotationZ", FireObj.obj.transform.rotation.z.ToString());
            xmlDoc.WriteEndElement();

            //Save if fire is Expandable
            xmlDoc.WriteElementString("Expanding", FireObj.expandable.ToString());

            //Save Extinguish Agent
            xmlDoc.WriteElementString("ExtinguishAgent", FireObj.ExtinguishAgent.ToString());

            xmlDoc.WriteEndElement();
        }
        #endregion
        xmlDoc.WriteEndElement();

        xmlDoc.WriteStartElement("GameObjects");

        #region gameObjects
        foreach(GameObject obj in gameObjects) {
            xmlDoc.WriteStartElement("GameObject");
            //Save the name
            xmlDoc.WriteElementString("Name", obj.name);

            //Save position of the object
            xmlDoc.WriteStartElement("Position");
            xmlDoc.WriteElementString("posX", obj.transform.position.x.ToString());
            xmlDoc.WriteElementString("posY", obj.transform.position.y.ToString());
            xmlDoc.WriteElementString("posZ", obj.transform.position.z.ToString());
            xmlDoc.WriteEndElement();

            //Save rotatie
            xmlDoc.WriteStartElement("Rotation");
            xmlDoc.WriteElementString("RotationX", obj.transform.rotation.x.ToString());
            xmlDoc.WriteElementString("RotationY", obj.transform.rotation.y.ToString());
            xmlDoc.WriteElementString("RotationZ", obj.transform.rotation.z.ToString());
            xmlDoc.WriteEndElement();

            xmlDoc.WriteEndElement();
        }
        #endregion

        xmlDoc.WriteEndElement();
        xmlDoc.WriteEndElement();
        xmlDoc.WriteEndDocument();
        xmlDoc.Flush();
        xmlDoc.Close();
    }
        /// <summary>
        /// Saves this out to a FDO XML configuration document
        /// </summary>
        /// <param name="xmlFile"></param>
        public void Save(string xmlFile)
        {
            using (var fact = new FgfGeometryFactory())
            using (var ws = new IoFileStream(xmlFile, "w"))
            {
                using (var writer = new XmlWriter(ws, true, XmlWriter.LineFormat.LineFormat_Indent))
                {
                    //Write spatial contexts
                    if (this.SpatialContexts != null && this.SpatialContexts.Length > 0)
                    {
                        var flags = new XmlSpatialContextFlags();
                        using (var scWriter = new XmlSpatialContextWriter(writer))
                        {
                            foreach (var sc in this.SpatialContexts)
                            {
                                //XmlSpatialContextWriter forbids writing dynamically calculated extents
                                if (sc.ExtentType == OSGeo.FDO.Commands.SpatialContext.SpatialContextExtentType.SpatialContextExtentType_Dynamic)
                                    continue;

                                scWriter.CoordinateSystem = sc.CoordinateSystem;
                                scWriter.CoordinateSystemWkt = sc.CoordinateSystemWkt;
                                scWriter.Description = sc.Description;
                                
                                scWriter.ExtentType = sc.ExtentType;

                                using (var geom = fact.CreateGeometry(sc.ExtentGeometryText))
                                {
                                    byte[] fgf = fact.GetFgf(geom);
                                    scWriter.Extent = fgf;
                                }

                                scWriter.Name = sc.Name;
                                scWriter.XYTolerance = sc.XYTolerance;
                                scWriter.ZTolerance = sc.ZTolerance;

                                scWriter.WriteSpatialContext();
                            }
                        }
                    }

                    

                    //Write logical schema
                    if (this.Schemas != null)
                    {
                        var schemas = CloneSchemas(this.Schemas);

                        schemas.WriteXml(writer);
                    }

                    //Write physical mappings
                    if (this.Mappings != null)
                    {
                        this.Mappings.WriteXml(writer);
                    }

                    writer.Close();
                }
                ws.Close();
            }
        }
Beispiel #14
0
        public void run(String catalogFile, String driverFile, String outputDirectory, String testPattern, String testSkip, String runXslt3Tests)
        {
            buildDriverList(driverFile);
            XmlReader   reader = XmlReader.Create(catalogFile);
            XmlDocument doc    = new XmlDocument();

            doc.Load(reader);

            Regex testPat = new Regex(testPattern);

            skipXslt3Tests = ("no" == runXslt3Tests);

            System.Uri catalogUri = new System.Uri(catalogFile);

            XmlElement catalogElement = (XmlElement)doc.SelectSingleNode("*");

            foreach (IDriver driver in drivers)
            {
                String outputDir       = System.IO.Path.Combine(outputDirectory, "output");
                String driverOutputDir = System.IO.Path.Combine(outputDir, driver.GetName());
                System.IO.Directory.CreateDirectory(driverOutputDir);
                String    outputFile      = System.IO.Path.Combine(outputDirectory, driver.GetName() + ".xml");
                XmlWriter xmlStreamWriter = XmlWriter.Create(outputFile);
                xmlStreamWriter.WriteStartDocument();
                xmlStreamWriter.WriteStartElement("testResults");
                xmlStreamWriter.WriteAttributeString("driver", driver.GetName());

                DateTime now = DateTime.Now;
                Console.WriteLine("Date " + now);
                xmlStreamWriter.WriteAttributeString("on", "" + now.ToString("s"));
                xmlStreamWriter.WriteAttributeString("baseline", (driver == baseline ? "yes" : "no"));
                Console.WriteLine("Driver implemented: " + driver.GetName());
                System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();
                double frequency      = System.Diagnostics.Stopwatch.Frequency;
                double nanosecPerTick = (1000 * 1000 * 1000) / frequency;
                foreach (XmlElement testCase in catalogElement.SelectNodes("test-case"))
                {
                    String name  = testCase.GetAttribute("name");
                    Match  match = testPat.Match(name);
                    if (!match.Success)
                    {
                        continue;
                    }
                    if ("no" == driver.GetTestRunOption(name))
                    {
                        continue;
                    }
                    if ((testSkip != null) && (driver.GetTestRunOption(name) != null) &&
                        int.Parse(driver.GetTestRunOption(name)) >= int.Parse(testSkip))
                    {
                        continue;
                    }
                    String attributeValue = testCase.GetAttribute("xslt-version");
                    double xsltVersion    = (attributeValue == "") ? 1.0 : Convert.ToDouble(attributeValue);
                    if (3.0 == xsltVersion && skipXslt3Tests)
                    {
                        continue;
                    }
                    Console.WriteLine("Running " + name);
                    driver.ResetVariables();
                    XmlElement schemaElement = (XmlElement)testCase.SelectSingleNode("test/schema");
                    String     schema        = schemaElement == null ? null : schemaElement.GetAttribute("file").ToString();
                    Uri        schemaUri     = schema == null ? null : new Uri(catalogUri, schema);
                    XmlElement sourceElement = (XmlElement)testCase.SelectSingleNode("test/source");
                    String     source        = sourceElement == null ? null : sourceElement.GetAttribute("file").ToString();
                    Uri        sourceUri     = source == null ? null : new Uri(catalogUri, source);
                    String     stylesheet    = ((XmlElement)testCase.SelectSingleNode("test/stylesheet")).GetAttribute("file");
                    Uri        stylesheetUri = new Uri(catalogUri, stylesheet);
                    if (xsltVersion <= driver.GetXsltVersion())
                    {
                        try
                        {
                            if (schema != null)
                            {
                                driver.LoadSchema(schemaUri);
                            }
                            if (source != null)
                            {
                                driver.BuildSource(sourceUri);
                            }
                            int    i;
                            double totalCompileStylesheet = 0;
                            for (i = 0; totalCompileStylesheet < MAX_TOTAL_TIME || i < MIN_ITERATIONS; i++)
                            {
                                double start = stopwatch.ElapsedTicks * nanosecPerTick;
                                driver.CompileStylesheet(stylesheetUri);
                                totalCompileStylesheet += stopwatch.ElapsedTicks * nanosecPerTick - start;
                            }
                            totalCompileStylesheet = 0;
                            GC.Collect();
                            // Wait for all finalizers to complete before continuing.
                            // Without this call to GC.WaitForPendingFinalizers,
                            // the worker loop below might execute at the same time
                            // as the finalizers.
                            // With this call, the worker loop executes only after
                            // all finalizers have been called.
                            GC.WaitForPendingFinalizers();
                            for (i = 0; totalCompileStylesheet < MAX_TOTAL_TIME || i < MIN_ITERATIONS; i++)
                            {
                                double start = stopwatch.ElapsedTicks * nanosecPerTick;
                                driver.CompileStylesheet(stylesheetUri);
                                totalCompileStylesheet += stopwatch.ElapsedTicks * nanosecPerTick - start;
                            }
                            double compileTime = totalCompileStylesheet / (1000000.0 * i);
                            Console.WriteLine("Average time for stylesheet compile: " + compileTime +
                                              "ms. Number of iterations: " + i);
                            double totalTransformFileToFile = 0;
                            for (i = 0; totalTransformFileToFile < MAX_TOTAL_TIME || i < MIN_ITERATIONS; i++)
                            {
                                double start = stopwatch.ElapsedTicks * nanosecPerTick;
                                driver.FileToFileTransform(sourceUri, driverOutputDir + "/" + name + ".xml");
                                totalTransformFileToFile += stopwatch.ElapsedTicks * nanosecPerTick - start;
                            }
                            totalTransformFileToFile = 0;
                            GC.Collect();
                            GC.WaitForPendingFinalizers();
                            for (i = 0; totalTransformFileToFile < MAX_TOTAL_TIME || i < MIN_ITERATIONS; i++)
                            {
                                double start = stopwatch.ElapsedTicks * nanosecPerTick;
                                driver.FileToFileTransform(sourceUri, driverOutputDir + "/" + name + ".xml");
                                totalTransformFileToFile += stopwatch.ElapsedTicks * nanosecPerTick - start;
                            }
                            double transformTimeFileToFile = totalTransformFileToFile / (1000000.0 * i);
                            Console.WriteLine("Average time for FileToFileTransform: " + transformTimeFileToFile +
                                              "ms. Number of iterations: " + i);
                            double totalTransformTreeToTree = 0;
                            for (i = 0; totalTransformTreeToTree < MAX_TOTAL_TIME || i < MIN_ITERATIONS; i++)
                            {
                                double start = stopwatch.ElapsedTicks * nanosecPerTick;
                                driver.TreeToTreeTransform();
                                totalTransformTreeToTree += stopwatch.ElapsedTicks * nanosecPerTick - start;
                            }
                            totalTransformTreeToTree = 0;
                            GC.Collect();
                            GC.WaitForPendingFinalizers();
                            for (i = 0; totalTransformTreeToTree < MAX_TOTAL_TIME || i < MIN_ITERATIONS; i++)
                            {
                                double start = stopwatch.ElapsedTicks * nanosecPerTick;
                                driver.TreeToTreeTransform();
                                totalTransformTreeToTree += stopwatch.ElapsedTicks * nanosecPerTick - start;
                            }
                            double transformTimeTreeToTree = totalTransformTreeToTree / (1000000.0 * i);
                            Console.WriteLine("Average time for TreeToTreeTransform: " + transformTimeTreeToTree +
                                              "ms. Number of iterations: " + i);
                            bool ok = true;
                            foreach (XmlElement assertion in testCase.SelectNodes("result/assert"))
                            {
                                String xpath = assertion.InnerText;
                                ok &= driver.TestAssertion(xpath);
                            }
                            Console.WriteLine("Test run succeeded with " + driver.GetName());
                            String scale       = testCase.GetAttribute("scale");
                            String scaleFactor = testCase.GetAttribute("scale-factor");
                            xmlStreamWriter.WriteStartElement("test");
                            xmlStreamWriter.WriteAttributeString("name", name);
                            if (scale != null && !scale.Equals(""))
                            {
                                xmlStreamWriter.WriteAttributeString("scale", scale);
                            }
                            if (scaleFactor != null && !scale.Equals(""))
                            {
                                xmlStreamWriter.WriteAttributeString("scale-factor", scaleFactor);
                            }
                            xmlStreamWriter.WriteAttributeString("run", (ok ? "success" : "wrongAnswer"));
                            xmlStreamWriter.WriteAttributeString("compileTime", "" + compileTime);
                            xmlStreamWriter.WriteAttributeString("transformTimeFileToFile", "" + transformTimeFileToFile);
                            xmlStreamWriter.WriteAttributeString("transformTimeTreeToTree", "" + transformTimeTreeToTree);
                            xmlStreamWriter.WriteEndElement();
                        }
                        catch (Exception e)
                        {
                            driver.DisplayResultDocument();
                            Console.WriteLine("Test run failed: " + e.Message);
                            xmlStreamWriter.WriteStartElement("test");
                            xmlStreamWriter.WriteAttributeString("name", name);
                            xmlStreamWriter.WriteAttributeString("run", "failure");
                            xmlStreamWriter.WriteEndElement();
                        }
                    }
                }
                xmlStreamWriter.WriteEndElement();
                xmlStreamWriter.WriteEndDocument();
                xmlStreamWriter.Close();
            }
        }
Beispiel #15
0
        /// <summary>
        /// Exports this BgfFile instance to XML
        /// </summary>
        /// <param name="Filename"></param>
        /// <param name="IsStoryboard"></param>
        /// <param name="TotalHeight"></param>
        /// <param name="TotalWidth"></param>
        private void WriteXmlData(string Filename, bool IsStoryboard = false, uint TotalHeight = 0, uint TotalWidth = 0)
        {
            string path     = Path.GetDirectoryName(Filename);
            string filename = Path.GetFileNameWithoutExtension(Filename);

            // start writing XML
            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent      = true;
            settings.IndentChars = "  ";

            XmlWriter writer = XmlWriter.Create(Path.Combine(path, filename + FileExtensions.XML), settings);

            // begin
            writer.WriteStartDocument();
            writer.WriteStartElement("bgf");
            writer.WriteAttributeString("version", "10");
            writer.WriteAttributeString("shrink", ShrinkFactor.ToString());
            writer.WriteAttributeString("maxindices", MaxIndices.ToString());

            // frames
            writer.WriteStartElement("frames");
            writer.WriteAttributeString("count", Frames.Count.ToString());
            writer.WriteAttributeString("imageformat", "bmp");
            if (IsStoryboard)
            {
                writer.WriteAttributeString("totalheight", TotalHeight.ToString());
                writer.WriteAttributeString("totalwidth", TotalWidth.ToString());
            }

            for (int i = 0; i < Frames.Count; i++)
            {
                writer.WriteStartElement("frame");
                writer.WriteAttributeString("width", Frames[i].Width.ToString());
                writer.WriteAttributeString("height", Frames[i].Height.ToString());
                writer.WriteAttributeString("xoffset", Frames[i].XOffset.ToString());
                writer.WriteAttributeString("yoffset", Frames[i].YOffset.ToString());

                if (!IsStoryboard)
                {
                    writer.WriteAttributeString("file", Filename + "-" + i.ToString() + FileExtensions.BMP);
                }

                // hotspots
                writer.WriteStartElement("hotspots");
                writer.WriteAttributeString("count", Frames[i].HotSpots.Count.ToString());
                for (int j = 0; j < Frames[i].HotSpots.Count; j++)
                {
                    writer.WriteStartElement("hotspot");
                    writer.WriteAttributeString("index", Frames[i].HotSpots[j].Index.ToString());
                    writer.WriteAttributeString("x", Frames[i].HotSpots[j].X.ToString());
                    writer.WriteAttributeString("y", Frames[i].HotSpots[j].Y.ToString());
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();

                writer.WriteEndElement();
            }
            writer.WriteEndElement();

            // framesets
            writer.WriteStartElement("framesets");
            writer.WriteAttributeString("count", FrameSets.Count.ToString());
            for (int i = 0; i < FrameSets.Count; i++)
            {
                writer.WriteStartElement("frameset");
                string indices = String.Empty;
                for (int j = 0; j < FrameSets[i].FrameIndices.Count; j++)
                {
                    indices += FrameSets[i].FrameIndices[j] + " ";
                }
                indices = indices.TrimEnd();
                writer.WriteAttributeString("indices", indices);
                writer.WriteEndElement();
            }

            // end
            writer.WriteEndElement();
            writer.WriteEndDocument();

            writer.Close();
        }
Beispiel #16
0
        ///<summary>XML file.</summary>
        private static void SendDataServer(Program ProgramCur, List <ProgramProperty> ForProgram, Patient pat)
        {
            ProgramProperty PPCur = ProgramProperties.GetCur(ForProgram, "Enter 0 to use PatientNum, or 1 to use ChartNum");
            string          id    = "";

            if (PPCur.PropertyValue == "0")
            {
                id = pat.PatNum.ToString();
            }
            else
            {
                id = pat.ChartNumber;
            }
            PPCur = ProgramProperties.GetCur(ForProgram, "XML output file path");
            string      xmlOutputFile = PPCur.PropertyValue;
            XmlDocument doc           = new XmlDocument();

            if (File.Exists(xmlOutputFile))
            {
                try {
                    doc.Load(xmlOutputFile);
                }
                catch {
                }
            }
            else
            {
                if (!Directory.Exists(Path.GetDirectoryName(xmlOutputFile)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(xmlOutputFile));
                }
            }
            XmlElement elementPatients = doc.DocumentElement;

            if (elementPatients == null)           //if no Patients element, then document is corrupt or new
            {
                doc             = new XmlDocument();
                elementPatients = doc.CreateElement("Patients");
                doc.AppendChild(elementPatients);
            }
            //figure out if patient is already in the list------------------------------------------
            bool       patAlreadyExists = false;
            XmlElement elementPat       = null;

            for (int i = 0; i < elementPatients.ChildNodes.Count; i++)
            {
                if (elementPatients.ChildNodes[i].SelectSingleNode("ID").InnerXml == id)
                {
                    patAlreadyExists = true;
                    elementPat       = (XmlElement)elementPatients.ChildNodes[i];
                }
            }
            if (patAlreadyExists)
            {
                elementPat.RemoveAll();                //clear it out.
            }
            else
            {
                elementPat = doc.CreateElement("Patient");
            }
            //add or edit patient-------------------------------------------------------------------------
            XmlElement el = doc.CreateElement("ID");

            el.InnerXml = id;
            elementPat.AppendChild(el);
            //LastName
            el          = doc.CreateElement("LastName");
            el.InnerXml = pat.LName;
            elementPat.AppendChild(el);
            //FirstName
            el          = doc.CreateElement("FirstName");
            el.InnerXml = pat.FName;
            elementPat.AppendChild(el);
            //MiddleName
            el          = doc.CreateElement("MiddleName");
            el.InnerXml = pat.MiddleI;
            elementPat.AppendChild(el);
            //Birthdate
            el          = doc.CreateElement("BirthDate");
            el.InnerXml = pat.Birthdate.ToString("yyyy/MM/dd");
            elementPat.AppendChild(el);
            //Gender
            el = doc.CreateElement("Gender");
            if (pat.Gender == PatientGender.Female)
            {
                el.InnerXml = "Female";
            }
            else
            {
                el.InnerXml = "Male";
            }
            elementPat.AppendChild(el);
            //Remarks
            el          = doc.CreateElement("Remarks");
            el.InnerXml = "";
            elementPat.AppendChild(el);
            //ReturnPath
            el    = doc.CreateElement("ReturnPath");
            PPCur = ProgramProperties.GetCur(ForProgram, "Return folder path");
            string returnFolder = PPCur.PropertyValue;

            if (!Directory.Exists(returnFolder))
            {
                Directory.CreateDirectory(returnFolder);
            }
            el.InnerXml = returnFolder.Replace(@"\", "/");
            elementPat.AppendChild(el);
            if (!patAlreadyExists)
            {
                elementPatients.AppendChild(elementPat);
            }
            //lock file--------------------------------------------------------------------------
            //they say to lock the file.  But I'm the only one writing to it.
            //write text-----------------------------------------------------------------------
            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent      = true;
            settings.IndentChars = "   ";
            XmlWriter writer = XmlWriter.Create(xmlOutputFile, settings);

            doc.Save(writer);
            writer.Close();            //This probably "unlocks" the file.
            //unlock file----------------------------------------------------------------------
            //They say to unlock the file here
            //Process.Start(xmlOutputFile);
            //MessageBox.Show(
            MessageBox.Show("Done.");
        }
Beispiel #17
0
        //=====================================================================

        /// <inheritdoc />
        public override void Apply(XmlDocument targetDocument, IXmlNamespaceResolver context)
        {
            // Get the index entry content
            XPathExpression keyExpr = this.Key.Clone();

            keyExpr.SetContext(context);

            string keyValue = (string)targetDocument.CreateNavigator().Evaluate(keyExpr);

            XPathNavigator data = this.SourceIndex[keyValue];

            if (data == null && !String.IsNullOrWhiteSpace(keyValue))
            {
                if (this.IgnoreCase)
                {
                    data = this.SourceIndex[keyValue.ToLowerInvariant()];
                }

                if (data == null)
                {
                    // For certain inherited explicitly implemented interface members, Microsoft is using
                    // incorrect member IDs in the XML comments files and on the content service.  If the
                    // failed member ID looks like one of them, try using the broken ID for the look up.
                    string brokenId = keyValue;

                    if (reDictionaryEII.IsMatch(brokenId))
                    {
                        brokenId = reGenericEII.Replace(brokenId, "#I$1{TKey@TValue}#");
                    }
                    else
                    if (reGenericEII.IsMatch(brokenId))
                    {
                        brokenId = reGenericEII.Replace(brokenId, "#I$1{T}#");
                    }

                    // Don't bother if they are the same
                    if (brokenId != keyValue)
                    {
                        data = this.SourceIndex[brokenId];
                    }
                }
            }

            // Notify if no entry
            if (data == null)
            {
                this.ParentComponent.WriteMessage(this.MissingEntry, "No index entry found for key '{0}'.",
                                                  keyValue);
                return;
            }

            // Get the target node
            XPathExpression targetExpr = this.Target.Clone();

            targetExpr.SetContext(context);
            XPathNavigator target = targetDocument.CreateNavigator().SelectSingleNode(targetExpr);

            // notify if no target found
            if (target == null)
            {
                this.ParentComponent.WriteMessage(this.MissingTarget, "Target node '{0}' not found.",
                                                  targetExpr.Expression);
                return;
            }

            // get the source nodes
            XPathExpression sourceExpr = this.Source.Clone();

            sourceExpr.SetContext(context);
            XPathNodeIterator sources = data.CreateNavigator().Select(sourceExpr);

            // Append the source nodes to the target node
            foreach (XPathNavigator source in sources)
            {
                // If IsAttribute is true, add the source attributes to current target.  Otherwise append source
                // as a child element to target.
                if (this.IsAttribute && source.HasAttributes)
                {
                    string    sourceName = source.LocalName;
                    XmlWriter attributes = target.CreateAttributes();

                    source.MoveToFirstAttribute();

                    do
                    {
                        string attrValue = target.GetAttribute(String.Format(CultureInfo.InvariantCulture,
                                                                             "{0}_{1}", sourceName, source.Name), String.Empty);

                        if (string.IsNullOrEmpty(attrValue))
                        {
                            attributes.WriteAttributeString(String.Format(CultureInfo.InvariantCulture,
                                                                          "{0}_{1}", sourceName, source.Name), source.Value);
                        }
                    } while(source.MoveToNextAttribute());

                    attributes.Close();
                }
                else
                {
                    target.AppendChild(source);
                }
            }

            // Notify if no source found
            if (sources.Count == 0)
            {
                this.ParentComponent.WriteMessage(this.MissingSource, "Source node '{0}' not found.",
                                                  sourceExpr.Expression);
            }
        }
Beispiel #18
0
        /// <summary>
        /// Searches through one or multiple files using a regular expression.
        /// Resulting matches can be printed or exported. They can also optionally
        /// be replaced.
        ///
        /// Command line switches:
        ///
        /// -p PATH               Path to start the search. If not provided, the
        ///                       current path will be used, with *.* as search
        ///                       pattern. Can be used multiple times to search
        ///                       through multiple paths, or use multiple search
        ///                       patterns.
        /// -f REGEX              Regular expression to use for finding matches.
        /// -r REPLACE            If used, will be used to replace found matches.
        /// -x FILENAME           Export findings to an XML file.
        /// -enc ENCODING         Text encoding if Byte-order-marks not available.
        ///                       Default=UTF-8
        /// -s                    Include subfolders in search.
        /// -o                    Print findings on the standard output.
        /// -ci                   Culture invariant search.
        /// -ecma                 Use ECMA script.
        /// -ic                   Ignore case.
        /// -iw                   Ignore pattern whitespace.
        /// -m                    Multi-line matching
        /// -n                    Single-line matching
        /// -t                    Test Mode. Files are not updated.
        /// -?                    Help.
        /// </summary>
        /// <example>
        /// Updating copyright statements in csproj, nuspec and cs files:
        /// Waher.Utility.RegEx.exe -p "C:\My Projects\IoTGateway\*.csproj" -p "C:\My Projects\IoTGateway\*.cs" -p "C:\My Projects\IoTGateway\*.nuspec" -f "Copyright (©|\([cC]\)) (?'Name'Waher( *\w+)*)\s*(?'From'\d{4})(-(?'To'\d{4}))?" -x "C:\Downloads\Temp\1.xml" -s -o -n -r "Copyright © ${Name} ${From}-2019"
        ///
        /// Updating copyright statements in markdown files:
        /// Waher.Utility.RegEx.exe -p "C:\My Projects\IoTGateway\*.md" -f "\([cC]\) \[(?'Name'Waher( *\w+)*)\]\((?'Url'[^)\n]*)\)\s*(?'From'\d{4})(-(?'To'\d{4}))?" -x "C:\Downloads\Temp\2.xml" -s -o -n -r "(c) [${Name}](${Url}) ${From}-2019"
        ///
        /// Updating copyright statements in RTF files:
        /// Waher.Utility.RegEx.exe -p "C:\My Projects\IoTGateway\*.rtf" -f "\\'a9 (?'Name'Waher( *\w+)*)\s*(?'From'\d{4})(-(?'To'\d{4}))?" -x "C:\Downloads\Temp\3.xml" -s -o -n -r "\'a9 ${Name} ${From}-2019"
        /// </example>
        static int Main(string[] args)
        {
            FileStream    FileOutput        = null;
            XmlWriter     Output            = null;
            Encoding      Encoding          = Encoding.Default;
            RegexOptions  Options           = RegexOptions.Compiled;
            List <string> Paths             = new List <string>();
            string        Expression        = null;
            string        ReplaceExpression = null;
            string        XmlFileName       = null;
            bool          Subfolders        = false;
            bool          Help  = false;
            bool          Print = false;
            bool          Test  = false;
            int           i     = 0;
            int           c     = args.Length;
            string        s;

            try
            {
                while (i < c)
                {
                    s = args[i++].ToLower();

                    switch (s)
                    {
                    case "-p":
                        if (i >= c)
                        {
                            throw new Exception("Missing path.");
                        }

                        Paths.Add(args[i++]);
                        break;

                    case "-f":
                        if (i >= c)
                        {
                            throw new Exception("Missing regular expression.");
                        }

                        if (string.IsNullOrEmpty(Expression))
                        {
                            Expression = args[i++];
                        }
                        else
                        {
                            throw new Exception("Only one regular expression allowed.");
                        }
                        break;

                    case "-r":
                        if (i >= c)
                        {
                            throw new Exception("Missing replace expression.");
                        }

                        if (string.IsNullOrEmpty(ReplaceExpression))
                        {
                            ReplaceExpression = args[i++];
                        }
                        else
                        {
                            throw new Exception("Only one replace expression allowed.");
                        }
                        break;

                    case "-x":
                        if (i >= c)
                        {
                            throw new Exception("Missing export filename.");
                        }

                        if (string.IsNullOrEmpty(XmlFileName))
                        {
                            XmlFileName = args[i++];
                        }
                        else
                        {
                            throw new Exception("Only one export file allowed.");
                        }
                        break;

                    case "-enc":
                        if (i >= c)
                        {
                            throw new Exception("Text encoding missing.");
                        }

                        Encoding = Encoding.GetEncoding(args[i++]);
                        break;

                    case "-s":
                        Subfolders = true;
                        break;

                    case "-o":
                        Print = true;
                        break;

                    case "-t":
                        Test = true;
                        break;

                    case "-?":
                        Help = true;
                        break;

                    case "-ci":
                        Options |= RegexOptions.CultureInvariant;
                        break;

                    case "-ecma":
                        Options |= RegexOptions.ECMAScript;
                        break;

                    case "-ic":
                        Options |= RegexOptions.IgnoreCase;
                        break;

                    case "-iw":
                        Options |= RegexOptions.IgnorePatternWhitespace;
                        break;

                    case "-m":
                        if ((Options & RegexOptions.Singleline) != 0)
                        {
                            throw new Exception("Contradictive options.");
                        }

                        Options |= RegexOptions.Multiline;
                        break;

                    case "-n":
                        if ((Options & RegexOptions.Multiline) != 0)
                        {
                            throw new Exception("Contradictive options.");
                        }

                        Options |= RegexOptions.Singleline;
                        break;

                    default:
                        throw new Exception("Unrecognized switch: " + s);
                    }
                }

                if (Help || c == 0)
                {
                    Console.Out.WriteLine("Searches through one or multiple files using a regular expression.");
                    Console.Out.WriteLine("Resulting matches can be printed or exported. They can also optionally");
                    Console.Out.WriteLine("be replaced.");
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Command line switches:");
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("-p PATH               Path to start the search. If not provided, the");
                    Console.Out.WriteLine("                      current path will be used, with *.* as search");
                    Console.Out.WriteLine("                      pattern. Can be used multiple times to search");
                    Console.Out.WriteLine("                      through multiple paths, or use multiple search");
                    Console.Out.WriteLine("                      patterns.");
                    Console.Out.WriteLine("-f REGEX              Regular expression to use for finding matches.");
                    Console.Out.WriteLine("-r REPLACE            If used, will be used to replace found matches.");
                    Console.Out.WriteLine("-x FILENAME           Export findings to an XML file.");
                    Console.Out.WriteLine("-enc ENCODING         Text encoding if Byte-order-marks not available.");
                    Console.Out.WriteLine("                      Default=UTF-8");
                    Console.Out.WriteLine("-s                    Include subfolders in search.");
                    Console.Out.WriteLine("-o                    Print findings on the standard output.");
                    Console.Out.WriteLine("-ci                   Culture invariant search.");
                    Console.Out.WriteLine("-ecma                 Use ECMA script.");
                    Console.Out.WriteLine("-ic                   Ignore case.");
                    Console.Out.WriteLine("-iw                   Ignore pattern whitespace.");
                    Console.Out.WriteLine("-m                    Multi-line matching");
                    Console.Out.WriteLine("-n                    Single-line matching");
                    Console.Out.WriteLine("-t                    Test Mode. Files are not updated.");
                    Console.Out.WriteLine("-?                    Help.");
                    return(0);
                }

                if (string.IsNullOrEmpty(Expression))
                {
                    throw new Exception("No regular expression specified.");
                }

                Regex  Regex = new Regex(Expression, Options);
                string SearchPattern;

                if (Paths.Count == 0)
                {
                    Paths.Add(Directory.GetCurrentDirectory());
                }

                if (!string.IsNullOrEmpty(XmlFileName))
                {
                    XmlWriterSettings Settings = new XmlWriterSettings()
                    {
                        CloseOutput             = true,
                        ConformanceLevel        = ConformanceLevel.Document,
                        Encoding                = Encoding.UTF8,
                        Indent                  = true,
                        IndentChars             = "\t",
                        NewLineChars            = "\r\n",
                        NewLineHandling         = NewLineHandling.Entitize,
                        NewLineOnAttributes     = false,
                        OmitXmlDeclaration      = false,
                        WriteEndDocumentOnClose = true
                    };

                    FileOutput = File.Create(XmlFileName);
                    Output     = XmlWriter.Create(FileOutput, Settings);
                }

                Output?.WriteStartDocument();
                Output?.WriteStartElement("Search", "http://waher.se/schema/RegExMatches.xsd");
                Output?.WriteStartElement("Files");

                Dictionary <string, bool> FileProcessed = new Dictionary <string, bool>();
                Dictionary <string, bool> FileMatches   = new Dictionary <string, bool>();
                Dictionary <string, bool> FileUpdates   = new Dictionary <string, bool>();
                SortedDictionary <string, SortedDictionary <string, int> > GroupCount = new SortedDictionary <string, SortedDictionary <string, int> >();

                foreach (string Path0 in Paths)
                {
                    string Path = Path0;

                    if (Directory.Exists(Path))
                    {
                        SearchPattern = "*.*";
                    }
                    else
                    {
                        SearchPattern = System.IO.Path.GetFileName(Path);
                        Path          = System.IO.Path.GetDirectoryName(Path);

                        if (!Directory.Exists(Path))
                        {
                            throw new Exception("Path does not exist.");
                        }
                    }

                    string[] FileNames = Directory.GetFiles(Path, SearchPattern, Subfolders ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);

                    foreach (string FileName in FileNames)
                    {
                        if (FileProcessed.ContainsKey(FileName))
                        {
                            continue;
                        }

                        FileProcessed[FileName] = true;

                        byte[] Data   = File.ReadAllBytes(FileName);
                        string Text   = CommonTypes.GetString(Data, Encoding);
                        string Text2  = Text;
                        int    Offset = 0;

                        MatchCollection Matches = Regex.Matches(Text);
                        c = Matches.Count;

                        if (c > 0)
                        {
                            FileMatches[FileName] = true;

                            Output?.WriteStartElement("File");
                            Output?.WriteAttributeString("name", FileName);
                            Output?.WriteAttributeString("count", c.ToString());

                            if (Print)
                            {
                                Console.Out.WriteLine("File: " + FileName);
                                Console.Out.WriteLine(new string('-', Math.Max(20, FileName.Length + 10)));
                                Console.Out.WriteLine("Matches: " + c.ToString());
                            }

                            foreach (Match M in Matches)
                            {
                                Output?.WriteStartElement("Match");
                                Output?.WriteAttributeString("index", M.Index.ToString());
                                Output?.WriteAttributeString("length", M.Length.ToString());
                                Output?.WriteAttributeString("value", M.Value);

                                if (Print)
                                {
                                    Console.Out.WriteLine("Pos " + M.Index.ToString() + ": " + M.Value);
                                }

                                if (!string.IsNullOrEmpty(ReplaceExpression))
                                {
                                    string ReplaceWith = M.Result(ReplaceExpression);

                                    i       = M.Index + Offset;
                                    Text2   = Text2.Remove(i, M.Length).Insert(i, ReplaceWith);
                                    Offset += ReplaceWith.Length - M.Length;

                                    Output?.WriteAttributeString("replacedWith", ReplaceWith);

                                    if (Print)
                                    {
                                        Console.Out.WriteLine("Replaced with: " + ReplaceWith);
                                    }
                                }

                                foreach (Group G in M.Groups)
                                {
                                    if (int.TryParse(G.Name, out i))
                                    {
                                        continue;
                                    }

                                    Output?.WriteStartElement("Group");
                                    Output?.WriteAttributeString("name", G.Name);
                                    Output?.WriteAttributeString("count", G.Value);
                                    Output?.WriteEndElement();

                                    if (Print)
                                    {
                                        Console.Out.WriteLine(G.Name + ": " + G.Value);
                                    }

                                    if (!GroupCount.TryGetValue(G.Name, out SortedDictionary <string, int> Counts))
                                    {
                                        Counts             = new SortedDictionary <string, int>();
                                        GroupCount[G.Name] = Counts;
                                    }

                                    if (Counts.TryGetValue(G.Value, out int Count))
                                    {
                                        Counts[G.Value] = Count + 1;
                                    }
                                    else
                                    {
                                        Counts[G.Value] = 1;
                                    }
                                }

                                Output?.WriteEndElement();
                            }

                            Output?.WriteEndElement();

                            if (Print)
                            {
                                Console.Out.WriteLine();
                            }

                            if (!string.IsNullOrEmpty(ReplaceExpression) && Text2 != Text)
                            {
                                FileUpdates[FileName] = true;

                                if (!Test)
                                {
                                    File.WriteAllText(FileName, Text2, Encoding);
                                }
                            }
                        }
                    }
                }

                Output?.WriteEndElement();

                Output?.WriteStartElement("Statistics");
                Output?.WriteAttributeString("fileCount", FileProcessed.Count.ToString());
                Output?.WriteAttributeString("fileMatchCount", FileMatches.Count.ToString());
                Output?.WriteAttributeString("fileUpdateCount", FileUpdates.Count.ToString());

                if (Print)
                {
                    Console.Out.WriteLine("Files processed: " + FileProcessed.Count.ToString());
                    Console.Out.WriteLine("Files matched: " + FileMatches.Count.ToString());
                }

                foreach (KeyValuePair <string, SortedDictionary <string, int> > GroupStat in GroupCount)
                {
                    Output?.WriteStartElement("Group");
                    Output?.WriteAttributeString("name", GroupStat.Key);

                    if (Print)
                    {
                        Console.Out.WriteLine(GroupStat.Key + ":");
                    }

                    foreach (KeyValuePair <string, int> Rec in GroupStat.Value)
                    {
                        Output?.WriteStartElement("Group");
                        Output?.WriteAttributeString("value", Rec.Key);
                        Output?.WriteAttributeString("count", Rec.Value.ToString());
                        Output?.WriteEndElement();

                        if (Print)
                        {
                            Console.Out.WriteLine("\t" + Rec.Key + ": " + Rec.Value.ToString());
                        }
                    }

                    Output?.WriteEndElement();
                }

                Output?.WriteEndElement();
                Output?.WriteEndDocument();

                return(0);
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
                return(-1);
            }
            finally
            {
                Output?.Flush();
                Output?.Close();
                Output?.Dispose();
                FileOutput?.Dispose();
            }
        }
Beispiel #19
0
 public override void Close()
 {
     _wrapped.Close();
 }
Beispiel #20
0
        public void SaveData()
        {
            FileInfo settings = new FileInfo(Path.Combine(Application.StartupPath, RulesetName + ".xml"));

            if (settings.Exists)
            {
                try
                {
                    DialogResult dr = MessageBox.Show(Resources.Setup_buttonSave_Click_ReplaceExistingInfoText,
                                                      Resources.Setup_buttonSave_Click_ReplaceExistingInfoCaption, MessageBoxButtons.YesNo,
                                                      MessageBoxIcon.Exclamation);

                    if (dr == DialogResult.Yes)
                    {
                        settings.Delete();
                    }
                }
                catch
                {
                }
            }
            settings = new FileInfo(Path.Combine(Application.StartupPath, RulesetName + ".xml"));
            if (!settings.Exists)
            {
                XmlWriter xw = XmlWriter.Create(settings.FullName, new XmlWriterSettings {
                    ConformanceLevel = ConformanceLevel.Auto, NewLineChars = "\r\n", IndentChars = "    ", CloseOutput = true, Encoding = Encoding.UTF8, NewLineOnAttributes = true, NamespaceHandling = NamespaceHandling.OmitDuplicates, Indent = true, CheckCharacters = true, NewLineHandling = NewLineHandling.None, OmitXmlDeclaration = true
                });
                xw.WriteStartDocument();
                xw.WriteStartElement("Config", "Setup");
                foreach (Control c in Controls)
                {
                    if (c.GetType() == new TextBox().GetType())
                    {
                        try
                        {
                            if (c.Name.ToLower().Contains("password") || ((TextBox)c).PasswordChar != '\0' || ((TextBox)c).UseSystemPasswordChar) // Criptografa os campos de senha
                            {
                                xw.WriteElementString(c.Name, "Setup", Crypto.EncryptStringAES(c.Text, "906"));
                            }
                            else
                            {
                                xw.WriteElementString(c.Name, "Setup", c.Text);
                            }
                        }
                        catch
                        {
                        }
                    }
                    else if (c.GetType() == new DataGridView().GetType())
                    {
                        xw.WriteStartElement(c.Name, "Setup");
                        foreach (DataGridViewRow row in ((DataGridView)c).Rows)
                        {
                            foreach (DataGridViewCell cell in row.Cells)
                            {
                                if (cell.Value != null)
                                {
                                    xw.WriteElementString(cell.OwningColumn.Name, "Setup", cell.Value.ToString());
                                }
                            }
                        }
                        xw.WriteEndElement();
                    }
                    else if (c.GetType() == new CheckBox().GetType())
                    {
                        xw.WriteElementString(c.Name, "Setup", ((CheckBox)c).Checked.ToString());
                    }
                    else if (c.GetType() == new DateTimePicker().GetType())
                    {
                        xw.WriteElementString(c.Name, "Setup", ((DateTimePicker)c).Value.ToBinary().ToString(CultureInfo.InvariantCulture));
                    }
                    else if (c.GetType() == new ComboBox().GetType())
                    {
                        xw.WriteStartElement(c.Name, "Setup");
                        foreach (String item in ((ComboBox)c).Items)
                        {
                            if (!String.IsNullOrEmpty(item))
                            {
                                xw.WriteElementString("li", "Setup", item);
                            }
                        }
                        xw.WriteEndElement();
                    }
                    else if (c.GetType() == new ListBox().GetType())
                    {
                        xw.WriteStartElement(c.Name, "Setup");
                        foreach (String item in ((ListBox)c).Items)
                        {
                            if (!String.IsNullOrEmpty(item))
                            {
                                xw.WriteElementString("li", "Setup", item);
                            }
                        }
                        xw.WriteEndElement();
                    }
                }
                xw.WriteEndElement();
                xw.WriteEndDocument();
                xw.Close();
            }
        }
Beispiel #21
0
        public bool SaveProfile(Profile prof)
        {
            _rwl.EnterWriteLock();

            bool isSuccessful;

            XmlWriter writer = null;

            try
            {
                writer = XmlWriter.Create(Path.Combine(GetFolderPath(), prof.Name + ".xml"));

                writer.WriteStartDocument();

                writer.WriteStartElement("Profile");

                writer.WriteElementString("Name", prof.Name);

                writer.WriteStartElement("Days");
                foreach (bool day in prof.Days)
                {
                    writer.WriteStartElement("Day");
                    writer.WriteValue(day);
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();

                writer.WriteStartElement("StartTimes");
                foreach (TimeUnit startTime in prof.StartTimes)
                {
                    writer.WriteElementString("StartTime", startTime.ToString());
                }
                writer.WriteEndElement();

                writer.WriteStartElement("EndTimes");
                foreach (TimeUnit endTime in prof.EndTimes)
                {
                    writer.WriteElementString("EndTime", endTime.ToString());
                }
                writer.WriteEndElement();

                writer.WriteStartElement("Active");
                writer.WriteValue(prof.Active);
                writer.WriteEndElement();

                writer.WriteStartElement("Allowed");
                writer.WriteValue(prof.Allowed);
                writer.WriteEndElement();

                writer.WriteStartElement("Mode");
                writer.WriteValue((int)prof.Mode);
                writer.WriteEndElement();

                writer.WriteStartElement("PhoneNumbersAsStrings");
                if (prof.PhoneNumbersAsStrings.Count == 0)
                {
                    writer.WriteStartElement("PhoneNumberString");
                    writer.WriteEndElement();
                }
                else
                {
                    foreach (string number in prof.PhoneNumbersAsStrings)
                    {
                        writer.WriteElementString("PhoneNumberString", number);
                    }
                }
                writer.WriteEndElement();

                writer.WriteStartElement("PhoneNumbersAsLongs");
                if (prof.PhoneNumbersAsLongs.Count == 0)
                {
                    writer.WriteStartElement("PhoneNumberLong");
                    writer.WriteEndElement();
                }
                else
                {
                    foreach (long number in prof.PhoneNumbersAsLongs)
                    {
                        writer.WriteStartElement("PhoneNumberLong");
                        writer.WriteValue(number);
                        writer.WriteEndElement();
                    }
                }
                writer.WriteEndElement();

                writer.WriteStartElement("ContactNames");
                if (prof.ContactNames.Count == 0)
                {
                    writer.WriteStartElement("ContactName");
                    writer.WriteEndElement();
                }
                else
                {
                    foreach (string name in prof.ContactNames)
                    {
                        writer.WriteElementString("ContactName", name);
                    }
                }
                writer.WriteEndElement();

                writer.WriteEndElement();

                isSuccessful = true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
                isSuccessful = false;
            }
            writer?.Close();
            _rwl.ExitWriteLock();

            return(isSuccessful);
        }
Beispiel #22
0
        /// <summary>
        /// Searches through exception log files in a folder, counting exceptions,
        /// genering an XML file with some basic statistics.
        ///
        /// Command line switches:
        ///
        /// -p PATH               Path to start the search. If not provided, the
        ///                       current path will be used, with *.* as search
        ///                       pattern. Can be used multiple times to search
        ///                       through multiple paths, or use multiple search
        ///                       patterns.
        /// -x FILENAME           Export findings to an XML file.
        /// -s                    Include subfolders in search.
        /// -?                    Help.
        /// </summary>
        static int Main(string[] args)
        {
            FileStream    FileOutput  = null;
            XmlWriter     Output      = null;
            List <string> Paths       = new List <string>();
            string        XmlFileName = null;
            bool          Subfolders  = false;
            bool          Help        = false;
            int           i           = 0;
            int           c           = args.Length;
            string        s;

            try
            {
                while (i < c)
                {
                    s = args[i++].ToLower();

                    switch (s)
                    {
                    case "-p":
                        if (i >= c)
                        {
                            throw new Exception("Missing path.");
                        }

                        Paths.Add(args[i++]);
                        break;

                    case "-x":
                        if (i >= c)
                        {
                            throw new Exception("Missing export filename.");
                        }

                        if (string.IsNullOrEmpty(XmlFileName))
                        {
                            XmlFileName = args[i++];
                        }
                        else
                        {
                            throw new Exception("Only one export file allowed.");
                        }
                        break;

                    case "-s":
                        Subfolders = true;
                        break;

                    case "-?":
                        Help = true;
                        break;

                    default:
                        throw new Exception("Unrecognized switch: " + s);
                    }
                }

                if (Help || c == 0)
                {
                    Console.Out.WriteLine("Searches through exception log files in a folder, counting exceptions,");
                    Console.Out.WriteLine("genering an XML file with some basic statistics.");
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Command line switches:");
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("-p PATH               Path to start the search. If not provided, the");
                    Console.Out.WriteLine("                      current path will be used, with *.* as search");
                    Console.Out.WriteLine("                      pattern. Can be used multiple times to search");
                    Console.Out.WriteLine("                      through multiple paths, or use multiple search");
                    Console.Out.WriteLine("                      patterns.");
                    Console.Out.WriteLine("-x FILENAME           Export findings to an XML file.");
                    Console.Out.WriteLine("-enc ENCODING         Text encoding if Byte-order-marks not available.");
                    Console.Out.WriteLine("                      Default=UTF-8");
                    Console.Out.WriteLine("-s                    Include subfolders in search.");
                    Console.Out.WriteLine("-?                    Help.");
                    return(0);
                }

                string SearchPattern;

                if (Paths.Count == 0)
                {
                    Paths.Add(Directory.GetCurrentDirectory());
                }

                if (string.IsNullOrEmpty(XmlFileName))
                {
                    throw new Exception("Missing output file name.");
                }

                XmlWriterSettings Settings = new XmlWriterSettings()
                {
                    CloseOutput             = true,
                    ConformanceLevel        = ConformanceLevel.Document,
                    Encoding                = Encoding.UTF8,
                    Indent                  = true,
                    IndentChars             = "\t",
                    NewLineChars            = "\n",
                    NewLineHandling         = NewLineHandling.Entitize,
                    NewLineOnAttributes     = false,
                    OmitXmlDeclaration      = false,
                    WriteEndDocumentOnClose = true
                };

                FileOutput = File.Create(XmlFileName);
                Output     = XmlWriter.Create(FileOutput, Settings);

                Output.WriteStartDocument();
                Output.WriteStartElement("Statistics", "http://waher.se/schema/ExStat.xsd");

                Dictionary <string, bool> FileProcessed = new Dictionary <string, bool>();

                foreach (string Path0 in Paths)
                {
                    string Path = Path0;

                    if (Directory.Exists(Path))
                    {
                        SearchPattern = "*.*";
                    }
                    else
                    {
                        SearchPattern = System.IO.Path.GetFileName(Path);
                        Path          = System.IO.Path.GetDirectoryName(Path);

                        if (!Directory.Exists(Path))
                        {
                            throw new Exception("Path does not exist.");
                        }
                    }

                    string[]   FileNames  = Directory.GetFiles(Path, SearchPattern, Subfolders ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
                    Statistics Statistics = new Statistics();
                    byte[]     Buffer     = new byte[BufSize];
                    int        NrRead     = 0;
                    int        Last       = 0;
                    int        j;
                    bool       SkipHyphens;

                    foreach (string FileName in FileNames)
                    {
                        if (FileProcessed.ContainsKey(FileName))
                        {
                            continue;
                        }

                        FileProcessed[FileName] = true;

                        Console.Out.WriteLine(FileName + "...");

                        using (FileStream fs = File.OpenRead(FileName))
                        {
                            do
                            {
                                SkipHyphens = false;
                                i           = 0;

                                if (Last > 0)
                                {
                                    if (Last < BufSize)
                                    {
                                        Array.Copy(Buffer, Last, Buffer, 0, (i = BufSize - Last));
                                    }
                                    else
                                    {
                                        SkipHyphens = true;
                                    }

                                    Last = 0;
                                }

                                NrRead = fs.Read(Buffer, i, BufSize - i);
                                if (NrRead <= 0)
                                {
                                    break;
                                }

                                if (SkipHyphens)
                                {
                                    while (i < BufSize && NrRead > 0 && Buffer[i] == '-')
                                    {
                                        i++;
                                    }

                                    Last = i;
                                }
                                else
                                {
                                    NrRead += i;
                                    i       = 0;
                                }

                                j = NrRead - 4;
                                while (i < j)
                                {
                                    if (Buffer[i] == '-' && Buffer[i + 1] == '-' && Buffer[i + 2] == '-' &&
                                        Buffer[i + 3] == '-' && Buffer[i + 4] == '-')
                                    {
                                        s = Encoding.Default.GetString(Buffer, Last, i - Last);
                                        Process(s, Statistics);

                                        i += 5;
                                        while (i < NrRead && Buffer[i] == '-')
                                        {
                                            i++;
                                        }

                                        Last = i;
                                    }
                                    else
                                    {
                                        i++;
                                    }
                                }
                            }while (NrRead == BufSize);

                            if (Last < NrRead)
                            {
                                s = Encoding.Default.GetString(Buffer, Last, NrRead - Last);
                                Process(s, Statistics);
                            }
                        }
                    }


                    Export(Output, "PerType", "type", Statistics.PerType, "PerMessage", "PerSource");
                    Export(Output, "PerMessage", "message", Statistics.PerMessage, "PerType", "PerSource");
                    Export(Output, "PerSource", string.Empty, Statistics.PerSource, "PerType", "PerMessage");
                    Export(Output, "PerHour", "hour", "yyyy-MM-ddTHH", Statistics.PerHour);
                    Export(Output, "PerDay", "day", "yyyy-MM-dd", Statistics.PerDay);
                    Export(Output, "PerMonth", "month", "yyyy-MM", Statistics.PerMonth);
                }

                Output.WriteEndElement();
                Output.WriteEndDocument();

                return(0);
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
                return(-1);
            }
            finally
            {
                Output?.Flush();
                Output?.Close();
                Output?.Dispose();
                FileOutput?.Dispose();
            }
        }
Beispiel #23
0
        public void saveHistory(List <patient> pL)
        {
            foreach (patient p in pL)
            {
                if (currentPatientId == p.idNumber)
                {
                    int       illnessHistoryIndex = this.parent.illnessHistoryList.FindIndex(x => x.patientID == p.idNumber);
                    XmlWriter writer = null;

                    try
                    {
                        XmlWriterSettings settings = new XmlWriterSettings();
                        settings.Indent = true;
                        writer          = XmlWriter.Create("history/" + p.firstName + p.lastName + ".xml", settings);
                        writer.WriteStartDocument();
                        writer.WriteStartElement("patient-info");

                        writer.WriteStartElement("patient");
                        writer.WriteElementString("first-name", p.firstName);
                        writer.WriteElementString("last-name", p.lastName);
                        writer.WriteElementString("age", p.age.ToString());
                        writer.WriteElementString("sex", p.sex);
                        writer.WriteElementString("id", p.idNumber.ToString());
                        writer.WriteElementString("country", p.contacts.country);
                        writer.WriteElementString("city", p.contacts.city);
                        writer.WriteElementString("street", p.contacts.street);
                        writer.WriteElementString("house-number", p.contacts.houseNumber.ToString());
                        writer.WriteElementString("flat-number", p.contacts.flatNumber.ToString());
                        writer.WriteElementString("phone-number", p.contacts.phoneNumber.ToString());
                        writer.WriteEndElement();

                        writer.WriteStartElement("history");
                        writer.WriteElementString("patient", parent.illnessHistoryList[illnessHistoryIndex].patientID.ToString());
                        writer.WriteStartElement("startDate");
                        writer.WriteElementString("day", parent.illnessHistoryList[illnessHistoryIndex].startingDate.Day.ToString());
                        writer.WriteElementString("month", parent.illnessHistoryList[illnessHistoryIndex].startingDate.Month.ToString());
                        writer.WriteElementString("year", parent.illnessHistoryList[illnessHistoryIndex].startingDate.Year.ToString());
                        writer.WriteEndElement();
                        writer.WriteElementString("desease", parent.illnessHistoryList[illnessHistoryIndex].deseaseName);
                        writer.WriteElementString("sympthoms", parent.illnessHistoryList[illnessHistoryIndex].sympthoms);
                        writer.WriteElementString("drugs", parent.illnessHistoryList[illnessHistoryIndex].drugs);
                        writer.WriteElementString("status", parent.illnessHistoryList[illnessHistoryIndex].curingStatus);
                        writer.WriteElementString("doctor", parent.illnessHistoryList[illnessHistoryIndex].currentDoctor.ToString());
                        writer.WriteStartElement("endDate");
                        writer.WriteElementString("day", parent.illnessHistoryList[illnessHistoryIndex].approxEndingDate.Day.ToString());
                        writer.WriteElementString("month", parent.illnessHistoryList[illnessHistoryIndex].approxEndingDate.Month.ToString());
                        writer.WriteElementString("year", parent.illnessHistoryList[illnessHistoryIndex].approxEndingDate.Year.ToString());
                        writer.WriteEndElement();
                        writer.WriteEndElement();
                        writer.WriteEndElement();
                        writer.WriteEndDocument();
                    }
                    finally
                    {
                        if (writer != null)
                        {
                            writer.Close();
                        }
                    }
                }
            }
        }
Beispiel #24
0
        public static bool SaveConfig()
        {
            XmlWriter writer = XmlWriter.Create(CSettings.sFileConfig, _settings);

            writer.WriteStartDocument();
            writer.WriteStartElement("root");

            #region Info
            writer.WriteStartElement("Info");

            writer.WriteElementString("Version", CSettings.GetFullVersionText());
            writer.WriteElementString("Time", System.DateTime.Now.ToString());
            writer.WriteElementString("Platform", System.Environment.OSVersion.Platform.ToString());
            writer.WriteElementString("OSVersion", System.Environment.OSVersion.ToString());
            writer.WriteElementString("ProcessorCount", System.Environment.ProcessorCount.ToString());

            writer.WriteElementString("Screens", Screen.AllScreens.Length.ToString());
            writer.WriteElementString("PrimaryScreenResolution", Screen.PrimaryScreen.Bounds.Size.ToString());

            writer.WriteElementString("Directory", System.Environment.CurrentDirectory.ToString());

            writer.WriteEndElement();
            #endregion Info

            #region Debug
            writer.WriteStartElement("Debug");

            writer.WriteComment("DebugLevel: " + ListStrings(Enum.GetNames(typeof(EDebugLevel))));
            writer.WriteElementString("DebugLevel", Enum.GetName(typeof(EDebugLevel), DebugLevel));

            writer.WriteEndElement();
            #endregion Debug

            #region Graphics
            writer.WriteStartElement("Graphics");

            writer.WriteComment("Renderer: " + ListStrings(Enum.GetNames(typeof(ERenderer))));
            writer.WriteElementString("Renderer", Enum.GetName(typeof(ERenderer), Renderer));

            writer.WriteComment("TextureQuality: " + ListStrings(Enum.GetNames(typeof(ETextureQuality))));
            writer.WriteElementString("TextureQuality", Enum.GetName(typeof(ETextureQuality), TextureQuality));

            writer.WriteComment("CoverSize (pixels): 32, 64, 128, 256, 512, 1024 (default: 128)");
            writer.WriteElementString("CoverSize", CoverSize.ToString());

            writer.WriteComment("Screen width and height (pixels)");
            writer.WriteElementString("ScreenW", ScreenW.ToString());
            writer.WriteElementString("ScreenH", ScreenH.ToString());

            writer.WriteComment("AAMode: " + ListStrings(Enum.GetNames(typeof(EAntiAliasingModes))));
            writer.WriteElementString("AAMode", Enum.GetName(typeof(EAntiAliasingModes), AAMode));

            writer.WriteComment("Colors: " + ListStrings(Enum.GetNames(typeof(EColorDeep))));
            writer.WriteElementString("Colors", Enum.GetName(typeof(EColorDeep), Colors));

            writer.WriteComment("MaxFPS should be between 1..200");
            writer.WriteElementString("MaxFPS", MaxFPS.ToString("#"));

            writer.WriteComment("VSync: " + ListStrings(Enum.GetNames(typeof(EOffOn))));
            writer.WriteElementString("VSync", Enum.GetName(typeof(EOffOn), VSync));

            writer.WriteComment("FullScreen: " + ListStrings(Enum.GetNames(typeof(EOffOn))));
            writer.WriteElementString("FullScreen", Enum.GetName(typeof(EOffOn), FullScreen));

            writer.WriteComment("FadeTime should be between 0..3 Seconds");
            writer.WriteElementString("FadeTime", FadeTime.ToString("#0.00"));

            writer.WriteEndElement();
            #endregion Graphics

            #region Theme
            writer.WriteStartElement("Theme");

            writer.WriteComment("Theme name");
            writer.WriteElementString("Name", Theme);

            writer.WriteComment("Skin name");
            writer.WriteElementString("Skin", Skin);

            writer.WriteComment("Name of cover-theme");
            writer.WriteElementString("Cover", CoverTheme);

            writer.WriteComment("Draw note-lines:" + ListStrings(Enum.GetNames(typeof(EOffOn))));
            writer.WriteElementString("DrawNoteLines", Enum.GetName(typeof(EOffOn), DrawNoteLines));

            writer.WriteComment("Draw tone-helper:" + ListStrings(Enum.GetNames(typeof(EOffOn))));
            writer.WriteElementString("DrawToneHelper", Enum.GetName(typeof(EOffOn), DrawToneHelper));

            writer.WriteComment("Look of timer:" + ListStrings(Enum.GetNames(typeof(ETimerLook))));
            writer.WriteElementString("TimerLook", Enum.GetName(typeof(ETimerLook), TimerLook));

            writer.WriteComment("Cover Loading:" + ListStrings(Enum.GetNames(typeof(ECoverLoading))));
            writer.WriteElementString("CoverLoading", Enum.GetName(typeof(ECoverLoading), CoverLoading));

            writer.WriteEndElement();
            #endregion Theme

            #region Sound
            writer.WriteStartElement("Sound");

            writer.WriteComment("PlayBackLib: " + ListStrings(Enum.GetNames(typeof(EPlaybackLib))));
            writer.WriteElementString("PlayBackLib", Enum.GetName(typeof(EPlaybackLib), PlayBackLib));

            writer.WriteComment("RecordLib: " + ListStrings(Enum.GetNames(typeof(ERecordLib))));
            writer.WriteElementString("RecordLib", Enum.GetName(typeof(ERecordLib), RecordLib));

            writer.WriteComment("AudioBufferSize: " + ListStrings(Enum.GetNames(typeof(EBufferSize))));
            writer.WriteElementString("AudioBufferSize", Enum.GetName(typeof(EBufferSize), AudioBufferSize));

            writer.WriteComment("AudioLatency from -500 to 500 ms");
            writer.WriteElementString("AudioLatency", AudioLatency.ToString());

            writer.WriteComment("Background Music");
            writer.WriteElementString("BackgroundMusic", Enum.GetName(typeof(EOffOn), BackgroundMusic));

            writer.WriteComment("Background Music Volume from 0 to 100");
            writer.WriteElementString("BackgroundMusicVolume", BackgroundMusicVolume.ToString());

            writer.WriteComment("Background Music Source");
            writer.WriteElementString("BackgroundMusicSource", Enum.GetName(typeof(EBackgroundMusicSource), BackgroundMusicSource));

            writer.WriteEndElement();
            #endregion Sound

            #region Game
            writer.WriteStartElement("Game");

            writer.WriteComment("Game-Language:");
            writer.WriteElementString("Language", Language);

            // SongFolder
            // Check, if program was started with songfolder-parameters
            if (SongFolderOld.Count > 0)
            {
                //Write "old" song-folders to config.
                writer.WriteComment("SongFolder: SongFolder1, SongFolder2, SongFolder3, ...");
                for (int i = 0; i < SongFolderOld.Count; i++)
                {
                    writer.WriteElementString("SongFolder" + (i + 1).ToString(), SongFolderOld[i]);
                }
            }
            else
            {
                //Write "normal" song-folders to config.
                writer.WriteComment("SongFolder: SongFolder1, SongFolder2, SongFolder3, ...");
                for (int i = 0; i < SongFolder.Count; i++)
                {
                    writer.WriteElementString("SongFolder" + (i + 1).ToString(), SongFolder[i]);
                }
            }

            writer.WriteComment("SongMenu: " + ListStrings(Enum.GetNames(typeof(ESongMenu))));
            writer.WriteElementString("SongMenu", Enum.GetName(typeof(ESongMenu), SongMenu));

            writer.WriteComment("SongSorting: " + ListStrings(Enum.GetNames(typeof(ESongSorting))));
            writer.WriteElementString("SongSorting", Enum.GetName(typeof(ESongSorting), SongSorting));

            writer.WriteComment("ScoreAnimationTime: Values >= 1 or 0 for no animation. Time is in seconds.");
            writer.WriteElementString("ScoreAnimationTime", ScoreAnimationTime.ToString());

            writer.WriteComment("TimerMode: " + ListStrings(Enum.GetNames(typeof(ETimerMode))));
            writer.WriteElementString("TimerMode", Enum.GetName(typeof(ETimerMode), TimerMode));

            writer.WriteComment("NumPlayer: 1.." + CSettings.MaxNumPlayer.ToString());
            writer.WriteElementString("NumPlayer", NumPlayer.ToString());

            writer.WriteComment("Order songs in tabs: " + ListStrings(Enum.GetNames(typeof(EOffOn))));
            writer.WriteElementString("Tabs", Enum.GetName(typeof(EOffOn), Tabs));

            writer.WriteComment("Lyrics also on Top of screen: " + ListStrings(Enum.GetNames(typeof(EOffOn))));
            writer.WriteElementString("LyricsOnTop", Enum.GetName(typeof(EOffOn), LyricsOnTop));

            writer.WriteEndElement();
            #endregion Game

            #region Video
            writer.WriteStartElement("Video");

            writer.WriteComment("VideoDecoder: " + ListStrings(Enum.GetNames(typeof(EVideoDecoder))));
            writer.WriteElementString("VideoDecoder", Enum.GetName(typeof(EVideoDecoder), VideoDecoder));

            writer.WriteComment("VideoBackgrounds: " + ListStrings(Enum.GetNames(typeof(EOffOn))));
            writer.WriteElementString("VideoBackgrounds", Enum.GetName(typeof(EOffOn), VideoBackgrounds));

            writer.WriteComment("VideoPreview: " + ListStrings(Enum.GetNames(typeof(EOffOn))));
            writer.WriteElementString("VideoPreview", Enum.GetName(typeof(EOffOn), VideoPreview));

            writer.WriteComment("Show Videos while singing: " + ListStrings(Enum.GetNames(typeof(EOffOn))));
            writer.WriteElementString("VideosInSongs", Enum.GetName(typeof(EOffOn), VideosInSongs));

            writer.WriteEndElement();
            #endregion Video

            #region Record
            writer.WriteStartElement("Record");

            for (int p = 1; p <= CSettings.MaxNumPlayer; p++)
            {
                if (MicConfig[p - 1].DeviceName != String.Empty && MicConfig[p - 1].InputName != String.Empty && MicConfig[p - 1].Channel > 0)
                {
                    writer.WriteStartElement("MicConfig" + p.ToString());

                    writer.WriteElementString("DeviceName", MicConfig[p - 1].DeviceName);
                    writer.WriteElementString("DeviceDriver", MicConfig[p - 1].DeviceDriver);
                    writer.WriteElementString("InputName", MicConfig[p - 1].InputName);
                    writer.WriteElementString("Channel", MicConfig[p - 1].Channel.ToString());

                    writer.WriteEndElement();
                }
            }

            writer.WriteComment("Mic delay in ms. 0, 20, 40, 60 ... 500");
            writer.WriteElementString("MicDelay", MicDelay.ToString());

            writer.WriteEndElement();
            #endregion Record

            // End of File
            writer.WriteEndElement(); //end of root
            writer.WriteEndDocument();

            writer.Flush();
            writer.Close();
            return(true);
        }
	public void SaveRobo ()
	{
		CurrentID = -1;
		GameObject Base = parts [0];
		XmlWriterSettings xws = new XmlWriterSettings { Indent = true };
		using (writer = new FileStream (Path.Combine (BPpath, "BoneProperty.xml"), FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)) {
			using (xw = XmlWriter.Create (writer, xws)) {

				xw.WriteStartDocument ();
				xw.WriteStartElement ("BoneProperty");
				xw.WriteAttributeString ("Count", parts.Count.ToString ());

				//write bone data
				BoneData BD = Base.GetComponent<BoneData> ();
				xw.WriteStartElement (Base.name);
				xw.WriteStartElement ("Level");
				xw.WriteAttributeString ("Value", 0.ToString ());
				xw.WriteEndElement ();
				xw.WriteStartElement ("ParentBoneIdx");
				xw.WriteAttributeString ("Value", (-1).ToString ());
				xw.WriteEndElement ();
				xw.WriteStartElement ("TransMat");
				BD.SMatrix = Matrix4x4.TRS (Base.transform.position, Base.transform.rotation, Base.transform.localScale);
				xw.WriteString (MatrixToString (BD.SMatrix.transpose));
				xw.WriteEndElement ();
				xw.WriteStartElement ("OffsetMat");
				xw.WriteString (MatrixToString (BD.SMatrix.transpose.inverse));
				xw.WriteEndElement ();
				xw.WriteStartElement ("EulerMode");
				xw.WriteAttributeString ("Value", BD.EulerMode.ToString ());
				xw.WriteEndElement ();
				xw.WriteStartElement ("BoneLayers");
				xw.WriteAttributeString ("Value", BD.BoneLayers.ToString ());
				xw.WriteEndElement ();
				xw.WriteStartElement ("BoneFlag");
				xw.WriteAttributeString ("Value", BD.BoneFlag [0].ToString ());
				xw.WriteAttributeString ("Value2", BD.BoneFlag [1].ToString ());
				xw.WriteEndElement ();
				xw.WriteStartElement ("LimitAng");
				xw.WriteString (LimitAngToString (BD.LimitAng));
				xw.WriteEndElement ();
				xw.WriteStartElement ("Windom_FileName");
				xw.WriteAttributeString ("Text", BD.Windom_FileName);
				xw.WriteEndElement ();
				xw.WriteStartElement ("Windom_Hide");
				xw.WriteAttributeString ("Value", BD.Windom_Hide.ToString ());
				xw.WriteEndElement ();
				xw.WriteEndElement ();
				CurrentID++;
				setChildren (Base.transform, 1, CurrentID);
				xw.WriteEndDocument ();
				xw.Close ();
			}
		}
	}
 protected virtual string EncryptPassword(string document)
 {
   string str1 = document;
   XmlWriter xmlWriter = (XmlWriter) null;
   XmlReader reader = (XmlReader) null;
   bool flag1 = false;
   try
   {
     StringBuilder sb = new StringBuilder();
     xmlWriter = (XmlWriter) new XmlTextWriter((TextWriter) new StringWriter(sb));
     XmlReaderSettings settings = new XmlReaderSettings();
     settings.IgnoreWhitespace = true;
     reader = XmlReader.Create((TextReader) new StringReader(document), settings);
     if (reader.Read())
     {
       do
       {
         if (reader.NodeType == XmlNodeType.Element && (reader.LocalName == "__session" || reader.LocalName == "__connect"))
           reader.Read();
         else if (reader.NodeType == XmlNodeType.Element && (reader.LocalName == "password" || reader.LocalName == "sessionId"))
         {
           for (bool flag2 = reader.MoveToFirstAttribute(); flag2; flag2 = reader.MoveToNextAttribute())
           {
             if (reader.LocalName == "__encrypted" && string.Compare(reader.Value, "yes", true) == 0)
               flag1 = true;
           }
           reader.Close();
         }
         else
           reader.Read();
       }
       while (!reader.EOF && reader.ReadState != System.Xml.ReadState.Closed);
     }
     reader = XmlReader.Create((TextReader) new StringReader(document), settings);
     if (reader.Read())
     {
       do
       {
         if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "__InSite")
         {
           string str2 = (string) null;
           xmlWriter.WriteStartElement(reader.LocalName);
           for (bool flag2 = reader.MoveToFirstAttribute(); flag2; flag2 = reader.MoveToNextAttribute())
           {
             if (reader.LocalName == "__encryption")
               str2 = reader.Value;
             else
               xmlWriter.WriteAttributeString(reader.LocalName, reader.Value);
           }
           if (!flag1)
             str2 = "2";
           if (!string.IsNullOrEmpty(str2))
             xmlWriter.WriteAttributeString("__encryption", str2);
           reader.Read();
         }
         else if (reader.NodeType == XmlNodeType.Element && (reader.LocalName == "__session" || reader.LocalName == "__connect"))
         {
           xmlWriter.WriteStartElement(reader.LocalName);
           xmlWriter.WriteAttributes(reader, true);
           reader.Read();
         }
         else if (reader.NodeType == XmlNodeType.EndElement && (reader.LocalName == "__session" || reader.LocalName == "__connect"))
         {
           xmlWriter.WriteEndElement();
           reader.Read();
         }
         else if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "password")
         {
           if (!flag1)
           {
             xmlWriter.WriteStartElement(reader.LocalName);
             for (bool flag2 = reader.MoveToFirstAttribute(); flag2; flag2 = reader.MoveToNextAttribute())
             {
               if (reader.LocalName != "__encrypted")
                 xmlWriter.WriteAttributeString(reader.LocalName, reader.Value);
             }
             xmlWriter.WriteAttributeString("__encrypted", "yes");
             int content = (int) reader.MoveToContent();
             string fieldData = reader.ReadElementContentAsString();
             xmlWriter.WriteValue(CryptUtil.Encrypt(fieldData));
             xmlWriter.WriteEndElement();
           }
           else
             xmlWriter.WriteNode(reader, true);
         }
         else
           xmlWriter.WriteNode(reader, true);
       }
       while (!reader.EOF);
       str1 = sb.ToString();
     }
   }
   catch (Exception ex)
   {
     str1 = document;
     this.LogEntry(string.Format("Password encrypting error: {0}", (object) ex.Message), EventLogEntryType.Error);
   }
   finally
   {
     reader?.Close();
     xmlWriter?.Close();
   }
   return str1;
 }
	public void SavePaths ()
	{
		XmlWriterSettings xws = new XmlWriterSettings { Indent = true };
		xw = XmlWriter.Create ("Settings.xml", xws);
		xw.WriteStartDocument ();
		xw.WriteStartElement ("Settings");
		xw.WriteStartElement ("Xed");
		xw.WriteAttributeString ("Path", BPpath);
		xw.WriteEndElement ();
		xw.WriteStartElement ("Models");
		xw.WriteAttributeString ("Path", Modelpath);
		xw.WriteEndElement ();
		xw.WriteEndElement ();
		xw.WriteEndDocument ();
		xw.Close ();
	}
Beispiel #28
0
        // How much deep to scan. (of course you can also pass it to the method)
        //const int HowDeepToScan = 255;

        public bool ProcessDir(string sourceDir, string LogName, List <string> ExceptionStr)
        {
            int totalFilecounter = 1;
            XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();

            xmlWriterSettings.Indent = true;
            xmlWriterSettings.NewLineOnAttributes = true;

            try
            {
                // Process the list of files found in the directory.
                //string[] fileEntries = Directory.GetFiles(sourceDir);
                var fileEntries = Directory.EnumerateFiles(sourceDir);

                //string[] files = Directory.GetFiles(sourceDir, "*.*", SearchOption.AllDirectories);
                foreach (string fileName in fileEntries)
                {
                    // do something with fileName
                    string isolateFilename = System.IO.Path.GetFileName(fileName);
                    string renamedFile     = RemoveChar(isolateFilename, ExceptionStr);

                    if (isolateFilename != renamedFile)
                    {
                        // Periodically report progress to the main thread so that it can
                        // update the UI.  In most cases you'll just need to send an
                        // integer that will update a ProgressBar
                        //m_oWorker2.ReportProgress(totalFilecounter / files.Length);

                        #region Write File Changes
                        if (File.Exists(LogName) == false)
                        {
                            using (XmlWriter xmlWriter = XmlWriter.Create(LogName, xmlWriterSettings))
                            {
                                xmlWriter.WriteStartDocument();
                                xmlWriter.WriteStartElement("Files_Folders");

                                xmlWriter.WriteStartElement("File");
                                xmlWriter.WriteElementString("Full_Path", fileName);
                                xmlWriter.WriteElementString("Proposed_Name", renamedFile);
                                xmlWriter.WriteEndElement();

                                xmlWriter.WriteEndElement();
                                xmlWriter.WriteEndDocument();
                                xmlWriter.Flush();
                                xmlWriter.Close();
                            }
                        }
                        else
                        {
                            XDocument xDocument         = XDocument.Load(LogName);
                            XElement  root              = xDocument.Element("Files_Folders");
                            IEnumerable <XElement> rows = root.Descendants("File");
                            XElement firstRow           = rows.First();
                            firstRow.AddBeforeSelf(
                                new XElement("File",
                                             new XElement("Full_Path", fileName),
                                             new XElement("Proposed_Name", renamedFile)));
                            xDocument.Save(LogName);
                        }
                        #endregion
                    }
                    totalFilecounter++;
                }

                //Parallel.ForEach(fileEntries, fileName => {
                //    // do something with fileName
                //    string isolateFilename = System.IO.Path.GetFileName(fileName);
                //    string renamedFile = RemoveChar(isolateFilename, ExceptionStr);

                //    if (isolateFilename != renamedFile)
                //    {

                //        // Periodically report progress to the main thread so that it can
                //        // update the UI.  In most cases you'll just need to send an
                //        // integer that will update a ProgressBar
                //        //m_oWorker2.ReportProgress(totalFilecounter / files.Length);

                //        #region Write File Changes
                //        if (File.Exists(LogName) == false)
                //        {
                //            using (XmlWriter xmlWriter = XmlWriter.Create(LogName, xmlWriterSettings))
                //            {
                //                xmlWriter.WriteStartDocument();
                //                xmlWriter.WriteStartElement("Files_Folders");

                //                xmlWriter.WriteStartElement("File");
                //                xmlWriter.WriteElementString("Full_Path", fileName);
                //                xmlWriter.WriteElementString("Proposed_Name", renamedFile);
                //                xmlWriter.WriteEndElement();

                //                xmlWriter.WriteEndElement();
                //                xmlWriter.WriteEndDocument();
                //                xmlWriter.Flush();
                //                xmlWriter.Close();
                //            }
                //        }
                //        else
                //        {
                //            XDocument xDocument = XDocument.Load(LogName);
                //            XElement root = xDocument.Element("Files_Folders");
                //            IEnumerable<XElement> rows = root.Descendants("File");
                //            XElement firstRow = rows.First();
                //            firstRow.AddBeforeSelf(
                //               new XElement("File",
                //               new XElement("Full_Path", fileName),
                //               new XElement("Proposed_Name", renamedFile)));
                //            xDocument.Save(LogName);
                //        }
                //        #endregion
                //    }
                //    totalFilecounter++;
                //});

                // Recurse into subdirectories of this directory.
                //string[] subdirEntries = Directory.GetDirectories(sourceDir);
                var subdirEntries = Directory.EnumerateDirectories(sourceDir);

                Parallel.ForEach(subdirEntries, subdir =>
                {
                    // Do not iterate through reparse points
                    if ((File.GetAttributes(subdir) &
                         FileAttributes.ReparsePoint) !=
                        FileAttributes.ReparsePoint)
                    {
                        //REM Thread.Sleep(1);

                        ProcessDir(subdir, LogName, ExceptionStr);

                        string isolateDirectory = System.IO.Path.GetFileName(subdir);
                        string renamedDirectory = RemoveChar(isolateDirectory, ExceptionStr);

                        if (isolateDirectory != renamedDirectory)
                        {
                            #region Write Directory Changes
                            if (File.Exists(LogName) == false)
                            {
                                using (XmlWriter xmlWriter = XmlWriter.Create(LogName, xmlWriterSettings))
                                {
                                    xmlWriter.WriteStartDocument();
                                    xmlWriter.WriteStartElement("Files_Folders");

                                    xmlWriter.WriteStartElement("Directory");
                                    xmlWriter.WriteElementString("Full_Path", subdir);
                                    xmlWriter.WriteElementString("Proposed_Name", renamedDirectory);
                                    xmlWriter.WriteEndElement();

                                    xmlWriter.WriteEndElement();
                                    xmlWriter.WriteEndDocument();
                                    xmlWriter.Flush();
                                    xmlWriter.Close();
                                }
                            }
                            else
                            {
                                XDocument xDocument         = XDocument.Load(LogName);
                                XElement root               = xDocument.Element("Files_Folders");
                                IEnumerable <XElement> rows = root.Descendants("File");
                                XElement firstRow           = rows.First();
                                firstRow.AddBeforeSelf(
                                    new XElement("Directory",
                                                 new XElement("Full_Path", subdir),
                                                 new XElement("Proposed_Name", renamedDirectory)));
                                xDocument.Save(LogName);
                            }
                            #endregion
                        }
                        //recursionLvl++;
                    }
                });

                return(true);
            }
            catch (Exception ex)
            {
                LogError(ErrorLogName, ex.Message.ToString());
                return(false);
            }
        }
        /// <summary>
        /// Write the image reference collection to a map file ready for use by <strong>BuildAssembler</strong>
        /// </summary>
        /// <param name="filename">The file to which the image reference collection is saved</param>
        /// <param name="imagePath">The path to which the image files should be copied</param>
        /// <param name="builder">The build process</param>
        /// <remarks>Images with their <see cref="ImageReference.CopyToMedia" /> property set to true are copied
        /// to the media folder immediately.</remarks>
        public void SaveImageSharedContent(string filename, string imagePath, BuildProcess builder)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            XmlWriter         writer   = null;
            string            destFile;

            builder.EnsureOutputFoldersExist("media");

            try
            {
                settings.Indent      = true;
                settings.CloseOutput = true;
                writer = XmlWriter.Create(filename, settings);

                writer.WriteStartDocument();

                // There are normally some attributes on this element but they aren't used by Sandcastle so we'll
                // ignore them.
                writer.WriteStartElement("stockSharedContentDefinitions");

                foreach (var ir in imageFiles)
                {
                    writer.WriteStartElement("item");
                    writer.WriteAttributeString("id", ir.Id);
                    writer.WriteStartElement("image");

                    // The art build component assumes everything is in a single, common folder.  The build
                    // process will ensure that happens.  As such, we only need the filename here.
                    writer.WriteAttributeString("file", ir.Filename);

                    if (!String.IsNullOrEmpty(ir.AlternateText))
                    {
                        writer.WriteStartElement("altText");
                        writer.WriteValue(ir.AlternateText);
                        writer.WriteEndElement();
                    }

                    writer.WriteEndElement();   // </image>
                    writer.WriteEndElement();   // </item>

                    destFile = Path.Combine(imagePath, ir.Filename);

                    if (File.Exists(destFile))
                    {
                        builder.ReportWarning("BE0010", "Image file '{0}' already exists.  It will be replaced " +
                                              "by '{1}'.", destFile, ir.FullPath);
                    }

                    builder.ReportProgress("    {0} -> {1}", ir.FullPath, destFile);

                    // The attributes are set to Normal so that it can be deleted after the build
                    File.Copy(ir.FullPath, destFile, true);
                    File.SetAttributes(destFile, FileAttributes.Normal);

                    // Copy it to the output media folders if CopyToMedia is true
                    if (ir.CopyToMedia)
                    {
                        foreach (string baseFolder in builder.HelpFormatOutputFolders)
                        {
                            destFile = Path.Combine(baseFolder + "media", ir.Filename);

                            builder.ReportProgress("    {0} -> {1} (Always copied)", ir.FullPath, destFile);

                            File.Copy(ir.FullPath, destFile, true);
                            File.SetAttributes(destFile, FileAttributes.Normal);
                        }
                    }
                }

                writer.WriteEndElement();   // </stockSharedContentDefinitions>
                writer.WriteEndDocument();
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }
Beispiel #30
0
        /// <summary>
        /// Analyzes exceptions and extracts basic statistics.
        /// </summary>
        /// <param name="ExceptionFileName">File name of exception file.</param>
        /// <param name="OutputFileName">XML Output file.</param>
        public static void Process(string ExceptionFileName, string OutputFileName)
        {
            string            s;
            FileStream        FileOutput = null;
            XmlWriter         Output     = null;
            XmlWriterSettings Settings   = new XmlWriterSettings()
            {
                CloseOutput             = true,
                ConformanceLevel        = ConformanceLevel.Document,
                Encoding                = Encoding.UTF8,
                Indent                  = true,
                IndentChars             = "\t",
                NewLineChars            = "\n",
                NewLineHandling         = NewLineHandling.Entitize,
                NewLineOnAttributes     = false,
                OmitXmlDeclaration      = false,
                WriteEndDocumentOnClose = true,
                CheckCharacters         = false
            };

            Statistics Statistics = new Statistics();

            byte[] Buffer = new byte[BufSize];
            int    NrRead = 0;
            int    Last = 0;
            int    i, j;
            bool   SkipHyphens;

            try
            {
                using (FileStream fs = File.OpenRead(ExceptionFileName))
                {
                    FileOutput = File.Create(OutputFileName);
                    Output     = XmlWriter.Create(FileOutput, Settings);

                    Output.WriteStartDocument();
                    Output.WriteStartElement("Statistics", "http://waher.se/schema/ExStat.xsd");

                    do
                    {
                        SkipHyphens = false;
                        i           = 0;

                        if (Last > 0)
                        {
                            if (Last < BufSize)
                            {
                                Array.Copy(Buffer, Last, Buffer, 0, (i = BufSize - Last));
                            }
                            else
                            {
                                SkipHyphens = true;
                            }

                            Last = 0;
                        }

                        NrRead = fs.Read(Buffer, i, BufSize - i);
                        if (NrRead <= 0)
                        {
                            break;
                        }

                        if (SkipHyphens)
                        {
                            while (i < BufSize && NrRead > 0 && Buffer[i] == '-')
                            {
                                i++;
                            }

                            Last = i;
                        }
                        else
                        {
                            NrRead += i;
                            i       = 0;
                        }

                        j = NrRead - 4;
                        while (i < j)
                        {
                            if (Buffer[i] == '-' && Buffer[i + 1] == '-' && Buffer[i + 2] == '-' &&
                                Buffer[i + 3] == '-' && Buffer[i + 4] == '-')
                            {
                                s = Encoding.Default.GetString(Buffer, Last, i - Last);
                                Process(s, Statistics);

                                i += 5;
                                while (i < NrRead && Buffer[i] == '-')
                                {
                                    i++;
                                }

                                Last = i;
                            }
                            else
                            {
                                i++;
                            }
                        }
                    }while (NrRead == BufSize);

                    if (Last < NrRead)
                    {
                        s = Encoding.Default.GetString(Buffer, Last, NrRead - Last);
                        Process(s, Statistics);
                    }
                }

                Export(Output, "PerType", "type", Statistics.PerType, "PerMessage", "PerSource");
                Export(Output, "PerMessage", "message", Statistics.PerMessage, "PerType", "PerSource");
                Export(Output, "PerSource", string.Empty, Statistics.PerSource, "PerType", "PerMessage");
                Export(Output, "PerHour", "hour", "yyyy-MM-ddTHH", Statistics.PerHour);
                Export(Output, "PerDay", "day", "yyyy-MM-dd", Statistics.PerDay);
                Export(Output, "PerMonth", "month", "yyyy-MM", Statistics.PerMonth);

                Output.WriteEndElement();
                Output.WriteEndDocument();
            }
            catch (Exception ex)
            {
                Log.Critical(ex, ExceptionFileName);
            }
            finally
            {
                Output?.Flush();
                Output?.Close();
                Output?.Dispose();
                FileOutput?.Dispose();
            }
        }
Beispiel #31
0
 protected override void CloseStream()
 {
     XmlWriter?.WriteEndElement();
     XmlWriter?.Flush();
     XmlWriter?.Close();
 }
Beispiel #32
0
        internal string PersistToXml()
        {
            using (StringWriter stringWriter = new StringWriter())
            {
                XmlWriterSettings settings = new XmlWriterSettings {
                    Indent = true, Encoding = Encoding.UTF8, ConformanceLevel = ConformanceLevel.Document, OmitXmlDeclaration = false, NewLineOnAttributes = false
                };

                using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings))
                {
                    xmlWriter.WriteProcessingInstruction("xml", @"version=""1.0"" encoding=""utf-8"" ");
                    xmlWriter.WriteStartElement("TestSuite", "http://tempuri.org/SsisUnit.xsd");

                    xmlWriter.WriteStartElement("ConnectionList");

                    foreach (ConnectionRef conn in ConnectionList.Values)
                    {
                        xmlWriter.WriteRaw(conn.PersistToXml());
                    }

                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteStartElement("PackageList");

                    foreach (PackageRef pkg in PackageList.Values)
                    {
                        xmlWriter.WriteRaw(pkg.PersistToXml());
                    }

                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteStartElement("DatasetList");

                    foreach (Dataset dataset in Datasets.Values)
                    {
                        xmlWriter.WriteRaw(dataset.PersistToXml());
                    }

                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteStartElement("TestSuiteSetup");
                    xmlWriter.WriteRaw(TestSuiteSetup.PersistToXml());
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteStartElement("Setup");
                    xmlWriter.WriteRaw(SetupCommands.PersistToXml());
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteStartElement("Tests");

                    foreach (Test test in Tests.Values)
                    {
                        xmlWriter.WriteRaw(test.PersistToXml());
                    }

                    foreach (TestRef testRef in TestRefs.Values)
                    {
                        xmlWriter.WriteRaw(testRef.PersistToXml());
                    }

                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteStartElement("Teardown");
                    xmlWriter.WriteRaw(TeardownCommands.PersistToXml());
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteStartElement("TestSuiteTeardown");
                    xmlWriter.WriteRaw(TestSuiteTeardown.PersistToXml());
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteEndElement();
                    xmlWriter.WriteEndDocument();

                    xmlWriter.Close();
                }

                return(stringWriter.ToString());
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            var schema = _schema;
            //Remove elements that have been unchecked. 
            foreach (TreeNode clsNode in treeSchema.Nodes)
            {
                string className = clsNode.Name;
                int index = schema.Classes.IndexOf(className);
                if (!clsNode.Checked)
                {
                    if (index >= 0)
                        schema.Classes.RemoveAt(index);
                }
                else
                {
                    if (index >= 0)
                    {
                        ClassDefinition clsDef = schema.Classes[index];
                        foreach (TreeNode propNode in clsNode.Nodes)
                        {
                            if (!propNode.Checked)
                            {
                                string propName = propNode.Text;
                                int pidx = clsDef.Properties.IndexOf(propName);
                                if (pidx >= 0)
                                {
                                    clsDef.Properties.RemoveAt(pidx);
                                    if (clsDef.IdentityProperties.Contains(propName))
                                    {
                                        int idpdx = clsDef.IdentityProperties.IndexOf(propName);
                                        clsDef.IdentityProperties.RemoveAt(idpdx);
                                    }
                                    if (clsDef.ClassType == ClassType.ClassType_FeatureClass)
                                    {
                                        FeatureClass fc = (FeatureClass)clsDef;
                                        if (fc.GeometryProperty.Name == propName)
                                        {
                                            fc.GeometryProperty = null;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (rdXml.Checked)
            {
                using (var ios = new IoFileStream(txtXml.Text, "w"))
                {
                    using (var writer = new XmlWriter(ios, false, XmlWriter.LineFormat.LineFormat_Indent))
                    {
                        schema.WriteXml(writer);
                        writer.Close();
                    }
                    ios.Close();
                }
                
                MessageService.ShowMessage("Schema saved to: " + txtXml.Text);
                this.DialogResult = DialogResult.OK;
            }
            else if (rdFile.Checked)
            {
                string fileName = txtFile.Text;
                if (ExpressUtility.CreateFlatFileDataSource(fileName))
                {
                    FdoConnection conn = ExpressUtility.CreateFlatFileConnection(fileName);
                    bool disposeConn = true;
                    using (FdoFeatureService svc = conn.CreateFeatureService())
                    {
                        svc.ApplySchema(schema);
                        if (MessageService.AskQuestion("Schema saved to: " + txtFile.Text + " connect to it?", "Saved"))
                        {
                            FdoConnectionManager mgr = ServiceManager.Instance.GetService<FdoConnectionManager>();
                            string name = MessageService.ShowInputBox(ResourceService.GetString("TITLE_CONNECTION_NAME"), ResourceService.GetString("PROMPT_ENTER_CONNECTION"), "");
                            if (name == null)
                                return;

                            while (name == string.Empty || mgr.NameExists(name))
                            {
                                MessageService.ShowError(ResourceService.GetString("ERR_CONNECTION_NAME_EMPTY_OR_EXISTS"));
                                name = MessageService.ShowInputBox(ResourceService.GetString("TITLE_CONNECTION_NAME"), ResourceService.GetString("PROMPT_ENTER_CONNECTION"), name);

                                if (name == null)
                                    return;
                            }
                            disposeConn = false;
                            mgr.AddConnection(name, conn);
                        }
                    }
                    if (disposeConn)
                    {
                        conn.Close();
                        conn.Dispose();
                    }
                    this.DialogResult = DialogResult.OK;
                }
            }
        }
Beispiel #34
0
        /// <summary>
        /// Upraví jeden přepis, transformuje ho do podoby pro ediční modul
        /// </summary>
        /// <param name="prp">Přepis (informace o něm)</param>
        /// <param name="emnNastaveni">Nastavení exportu pro ediční modul</param>
        /// <param name="glsTransformacniSablony">Seznam transformačních šablon XSLT, které se při úpravách použijí</param>
        public static void Uprav(IPrepis prp, IExportNastaveni emnNastaveni, List <string> glsTransformacniSablony)
        {
            //
            string sCesta = Path.Combine(emnNastaveni.VstupniSlozka, prp.Soubor.Nazev);

            sCesta = sCesta.Replace(".docx", ".xml").Replace(".doc", ".xml");
            FileInfo fi = new FileInfo(sCesta);

            if (!fi.Exists)
            {
                throw new FileNotFoundException("Zadaný soubor '" + sCesta + "' neexistuje.");
            }

            if (emnNastaveni.DocasnaSlozka == null)
            {
                emnNastaveni.DocasnaSlozka = Path.GetTempPath();
            }

            //Zpracovat hlavičku a front
            string strNazev = fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length);

            Console.WriteLine("Zpracovávám soubor '{0}'", strNazev);


            string sHlavicka = Path.Combine(emnNastaveni.SlozkaXslt, "EM_Vytvorit_hlavicku_TEI.xsl");
            //string sHlavicka = Path.Combine(emnNastaveni.SlozkaXslt, "EB_Vytvorit_hlavicku_TEI.xsl");

            string sHlavickaVystup = Path.Combine(emnNastaveni.DocasnaSlozka, strNazev + "_hlavicka.xml");

            string sFront       = Path.Combine(emnNastaveni.SlozkaXslt, "Vytvorit_front_TEI.xsl");
            string sFrontVystup = Path.Combine(emnNastaveni.DocasnaSlozka, strNazev + "_front.xml");

            List <string> glsVystupy = new List <string>(glsTransformacniSablony.Count + 2);

            XslCompiledTransform xctHlavick = new XslCompiledTransform();

            xctHlavick.Load(sHlavicka);
            XsltArgumentList xal = new XsltArgumentList();

            xal.AddParam("soubor", "", prp.NazevSouboru);
            XmlWriter xw = XmlWriter.Create(sHlavickaVystup);

            xctHlavick.Transform(emnNastaveni.SouborMetadat, xal, xw);
            xw.Close();

            glsVystupy.Add(sHlavickaVystup);

            XslCompiledTransform xctFront = new XslCompiledTransform();

            xctFront.Load(sFront);
            xw = XmlWriter.Create(sFrontVystup);
            xctFront.Transform(emnNastaveni.SouborMetadat, xal, xw);
            xw.Close();
            glsVystupy.Add(sFrontVystup);

            string strVstup  = sCesta;
            string strVystup = null;

            for (int i = 0; i < glsTransformacniSablony.Count; i++)
            {
                strVystup = Path.Combine(emnNastaveni.DocasnaSlozka, String.Format("{0}_{1:00}.xml", strNazev, i));
                glsVystupy.Add(strVystup);

                XslCompiledTransform xslt = new XslCompiledTransform();
                Console.WriteLine("{0} = {1}", String.Format("{0}_{1:00}.xml", strNazev, i), glsTransformacniSablony[i]);

                xslt.Load(glsTransformacniSablony[i]);
                xslt.Transform(strVstup, strVystup);
                strVstup = strVystup;
            }


            //EBV

            /*
             *     if (prp.LiterarniZanr == "biblický text") {
             *             strVstup = ZpracovatBiblickyText(emnNastaveni, strNazev, glsTransformacniSablony, glsVystupy, strVystup);
             *     }
             *     else
             *     {
             *             strVstup = ZpracovatOdkazyNaBiblickaMista(emnNastaveni, strNazev, glsTransformacniSablony, glsVystupy, strVystup);
             *     }
             */


            //string sSlouceni = Path.Combine(emnNastaveni.SlozkaXslt, "EM_Spojit_s_hlavickou_a_front.xsl");//EBV

            string sSlouceni = Path.Combine(emnNastaveni.SlozkaXslt, "EB_Vybor_Spojit_s_hlavickou_a_front.xsl");            //EBV

            //string sSlouceni = Path.Combine(emnNastaveni.SlozkaXslt, "EB_Spojit_s_hlavickou_a_front.xsl");

            strVystup = Path.Combine(emnNastaveni.DocasnaSlozka, String.Format("{0}_{1:00}.xml", strNazev, glsVystupy.Count));

            XsltSettings         xsltSettings = new XsltSettings(true, false);
            XslCompiledTransform xctSlouceni  = new XslCompiledTransform();

            xctSlouceni.Load(sSlouceni, xsltSettings, null);
            xal = new XsltArgumentList();
            xal.AddParam("hlavicka", "", sHlavickaVystup);
            xal.AddParam("zacatek", "", sFrontVystup);
            xw = XmlWriter.Create(strVystup);
            xctSlouceni.Transform(strVstup, xal, xw);
            xw.Close();
            strVstup = strVystup;
            glsVystupy.Add(strVystup);

            /*
             * strVystup = Path.Combine(emnNastaveni.DocasnaSlozka, String.Format("{0}_{1:00}.xml", strNazev, glsVystupy.Count));
             * PresunoutMezeryVneTagu(strVstup, strVystup);
             * glsVystupy.Add(strVystup);
             * strVstup = strVystup;
             */
            string sEdicniKomentar = Path.Combine(emnNastaveni.SlozkaXslt, "EM_Presunout_edicni_komentar.xsl");

            strVystup = Path.Combine(emnNastaveni.DocasnaSlozka, String.Format("{0}_{1:00}.xml", strNazev, glsVystupy.Count));

            XmlUrlResolver       xrl = new XmlUrlResolver();
            XslCompiledTransform xctEdicniKomentare = new XslCompiledTransform();

            xctEdicniKomentare.Load(sEdicniKomentar, xsltSettings, xrl);
            xw = XmlWriter.Create(strVystup);
            xctEdicniKomentare.Transform(strVstup, xal, xw);
            xw.Close();
            glsVystupy.Add(strVystup);

            strVstup  = strVystup;
            strVystup = Path.Combine(emnNastaveni.VystupniSlozka, strNazev + ".xml");
            PresunoutMezeryVneTagu(strVstup, strVystup);


            //File.Copy(strVystup, Path.Combine(emnNastaveni.VystupniSlozka, strNazev + ".xml"),true);
        }
Beispiel #35
0
        /// <summary>
        /// Searches through exception log files in a folder, counting exceptions,
        /// genering an XML file with some basic statistics.
        ///
        /// Command line switches:
        ///
        /// -p PATH               Path to start the search. If not provided,
        ///                       and no comparison paths are provided, the
        ///                       current path will be used, with *.* as search
        ///                       pattern. Can be used multiple times to search
        ///                       through multiple paths, or use multiple search
        ///                       patterns.
        /// -c PATH               Compares XML files output by ExStat. Only
        ///                       exceptions common in all files will be output.
        /// -x FILENAME           Export findings to an XML file.
        /// -s                    Include subfolders in search.
        /// -?                    Help.
        /// </summary>
        static int Main(string[] args)
        {
            FileStream    FileOutput      = null;
            XmlWriter     Output          = null;
            List <string> Paths           = new List <string>();
            List <string> ComparisonPaths = new List <string>();
            string        XmlFileName     = null;
            bool          Subfolders      = false;
            bool          Help            = false;
            int           i = 0;
            int           c = args.Length;
            string        s;

            try
            {
                while (i < c)
                {
                    s = args[i++].ToLower();

                    switch (s)
                    {
                    case "-p":
                        if (i >= c)
                        {
                            throw new Exception("Missing path.");
                        }

                        Paths.Add(args[i++]);
                        break;

                    case "-c":
                        if (i >= c)
                        {
                            throw new Exception("Missing path.");
                        }

                        ComparisonPaths.Add(args[i++]);
                        break;

                    case "-x":
                        if (i >= c)
                        {
                            throw new Exception("Missing export filename.");
                        }

                        if (string.IsNullOrEmpty(XmlFileName))
                        {
                            XmlFileName = args[i++];
                        }
                        else
                        {
                            throw new Exception("Only one export file allowed.");
                        }
                        break;

                    case "-s":
                        Subfolders = true;
                        break;

                    case "-?":
                        Help = true;
                        break;

                    default:
                        throw new Exception("Unrecognized switch: " + s);
                    }
                }

                if (Help || c == 0)
                {
                    Console.Out.WriteLine("Searches through exception log files in a folder, counting exceptions,");
                    Console.Out.WriteLine("genering an XML file with some basic statistics.");
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Command line switches:");
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("-p PATH               Path to start the search. If not provided,");
                    Console.Out.WriteLine("                      and no comparison paths are provided, the");
                    Console.Out.WriteLine("                      current path will be used, with *.* as search");
                    Console.Out.WriteLine("                      pattern. Can be used multiple times to search");
                    Console.Out.WriteLine("                      through multiple paths, or use multiple search");
                    Console.Out.WriteLine("                      patterns.");
                    Console.Out.WriteLine("-c PATH               Compares XML files output by ExStat. Only");
                    Console.Out.WriteLine("                      exceptions common in all files will be output.");
                    Console.Out.WriteLine("-x FILENAME           Export findings to an XML file.");
                    Console.Out.WriteLine("-enc ENCODING         Text encoding if Byte-order-marks not available.");
                    Console.Out.WriteLine("                      Default=UTF-8");
                    Console.Out.WriteLine("-s                    Include subfolders in search.");
                    Console.Out.WriteLine("-?                    Help.");
                    return(0);
                }

                string SearchPattern;

                if (Paths.Count == 0 && ComparisonPaths.Count == 0)
                {
                    Paths.Add(Directory.GetCurrentDirectory());
                }

                if (string.IsNullOrEmpty(XmlFileName))
                {
                    throw new Exception("Missing output file name.");
                }

                XmlWriterSettings Settings = new XmlWriterSettings()
                {
                    CloseOutput             = true,
                    ConformanceLevel        = ConformanceLevel.Document,
                    Encoding                = Encoding.UTF8,
                    Indent                  = true,
                    IndentChars             = "\t",
                    NewLineChars            = "\n",
                    NewLineHandling         = NewLineHandling.Entitize,
                    NewLineOnAttributes     = false,
                    OmitXmlDeclaration      = false,
                    WriteEndDocumentOnClose = true,
                    CheckCharacters         = false
                };

                FileOutput = File.Create(XmlFileName);
                Output     = XmlWriter.Create(FileOutput, Settings);

                Output.WriteStartDocument();
                Output.WriteStartElement("Statistics", "http://waher.se/schema/ExStat.xsd");

                Dictionary <string, bool> FileProcessed = new Dictionary <string, bool>();
                Statistics Statistics = new Statistics();

                foreach (string Path0 in Paths)
                {
                    string Path = Path0;

                    if (Directory.Exists(Path))
                    {
                        SearchPattern = "*.*";
                    }
                    else
                    {
                        SearchPattern = System.IO.Path.GetFileName(Path);
                        Path          = System.IO.Path.GetDirectoryName(Path);

                        if (!Directory.Exists(Path))
                        {
                            throw new Exception("Path does not exist.");
                        }
                    }

                    string[] FileNames = Directory.GetFiles(Path, SearchPattern, Subfolders ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
                    byte[]   Buffer    = new byte[BufSize];
                    int      NrRead    = 0;
                    int      Last      = 0;
                    int      j;
                    bool     SkipHyphens;

                    foreach (string FileName in FileNames)
                    {
                        if (FileProcessed.ContainsKey(FileName))
                        {
                            continue;
                        }

                        FileProcessed[FileName] = true;

                        Console.Out.WriteLine(FileName + "...");

                        try
                        {
                            using (FileStream fs = File.OpenRead(FileName))
                            {
                                do
                                {
                                    SkipHyphens = false;
                                    i           = 0;

                                    if (Last > 0)
                                    {
                                        if (Last < BufSize)
                                        {
                                            Array.Copy(Buffer, Last, Buffer, 0, (i = BufSize - Last));
                                        }
                                        else
                                        {
                                            SkipHyphens = true;
                                        }

                                        Last = 0;
                                    }

                                    NrRead = fs.Read(Buffer, i, BufSize - i);
                                    if (NrRead <= 0)
                                    {
                                        break;
                                    }

                                    if (SkipHyphens)
                                    {
                                        while (i < BufSize && NrRead > 0 && Buffer[i] == '-')
                                        {
                                            i++;
                                        }

                                        Last = i;
                                    }
                                    else
                                    {
                                        NrRead += i;
                                        i       = 0;
                                    }

                                    j = NrRead - 4;
                                    while (i < j)
                                    {
                                        if (Buffer[i] == '-' && Buffer[i + 1] == '-' && Buffer[i + 2] == '-' &&
                                            Buffer[i + 3] == '-' && Buffer[i + 4] == '-')
                                        {
                                            s = Encoding.Default.GetString(Buffer, Last, i - Last);
                                            Process(s, Statistics);

                                            i += 5;
                                            while (i < NrRead && Buffer[i] == '-')
                                            {
                                                i++;
                                            }

                                            Last = i;
                                        }
                                        else
                                        {
                                            i++;
                                        }
                                    }
                                }while (NrRead == BufSize);

                                if (Last < NrRead)
                                {
                                    s = Encoding.Default.GetString(Buffer, Last, NrRead - Last);
                                    Process(s, Statistics);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.Out.WriteLine(ex.Message);
                        }
                    }
                }

                Statistics.RemoveUntouched();

                bool First = Paths.Count == 0;

                foreach (string Path0 in ComparisonPaths)
                {
                    string Path = Path0;

                    if (Directory.Exists(Path))
                    {
                        SearchPattern = "*.xml";
                    }
                    else
                    {
                        SearchPattern = System.IO.Path.GetFileName(Path);
                        Path          = System.IO.Path.GetDirectoryName(Path);

                        if (!Directory.Exists(Path))
                        {
                            throw new Exception("Path does not exist.");
                        }
                    }

                    string[] FileNames = Directory.GetFiles(Path, SearchPattern, Subfolders ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);

                    foreach (string FileName in FileNames)
                    {
                        if (FileProcessed.ContainsKey(FileName))
                        {
                            continue;
                        }

                        FileProcessed[FileName] = true;

                        Console.Out.WriteLine(FileName + "...");

                        try
                        {
                            XmlDocument Doc = new XmlDocument();
                            Doc.Load(FileName);

                            foreach (XmlNode N in Doc.DocumentElement.ChildNodes)
                            {
                                if (!(N is XmlElement E))
                                {
                                    continue;
                                }

                                switch (E.LocalName)
                                {
                                case "PerType":
                                    foreach (XmlNode N2 in E.ChildNodes)
                                    {
                                        if (!(N2 is XmlElement E2) || E2.LocalName != "Stat")
                                        {
                                            continue;
                                        }

                                        string Type  = XML.Attribute(E2, "type");
                                        int    Count = XML.Attribute(E2, "count", 0);

                                        foreach (XmlNode N3 in E2.ChildNodes)
                                        {
                                            if (!(N3 is XmlElement E3))
                                            {
                                                continue;
                                            }

                                            switch (E3.LocalName)
                                            {
                                            case "PerMessage":
                                                foreach (XmlNode N4 in E3.ChildNodes)
                                                {
                                                    if (!(N4 is XmlElement E4) || E4.LocalName != "Stat")
                                                    {
                                                        continue;
                                                    }

                                                    string Message = E4["Value"]?.InnerText;
                                                    int    Count2  = XML.Attribute(E4, "count", 0);

                                                    Statistics.PerType.Join(Type, Count2, First, Message, null);
                                                    Statistics.PerMessage.Join(Message, Count2, First, Type, null);
                                                }
                                                break;

                                            case "PerSource":
                                                foreach (XmlNode N4 in E3.ChildNodes)
                                                {
                                                    if (!(N4 is XmlElement E4) || E4.LocalName != "Stat")
                                                    {
                                                        continue;
                                                    }

                                                    string StackTrace = E4["Value"]?.InnerText;
                                                    int    Count2     = XML.Attribute(E4, "count", 0);

                                                    Statistics.PerType.Join(Type, Count2, First, null, StackTrace);
                                                    Statistics.PerSource.Join(StackTrace, Count2, First, Type, null);
                                                }
                                                break;

                                            default:
                                                throw new Exception("Unknown element: " + E3.LocalName);
                                            }
                                        }
                                    }
                                    break;

                                case "PerMessage":
                                    foreach (XmlNode N2 in E.ChildNodes)
                                    {
                                        if (!(N2 is XmlElement E2) || E2.LocalName != "Stat")
                                        {
                                            continue;
                                        }

                                        string Message = XML.Attribute(E2, "message");
                                        int    Count   = XML.Attribute(E2, "count", 0);

                                        foreach (XmlNode N3 in E2.ChildNodes)
                                        {
                                            if (!(N3 is XmlElement E3))
                                            {
                                                continue;
                                            }

                                            switch (E3.LocalName)
                                            {
                                            case "PerType":
                                                foreach (XmlNode N4 in E3.ChildNodes)
                                                {
                                                    if (!(N4 is XmlElement E4) || E4.LocalName != "Stat")
                                                    {
                                                        continue;
                                                    }

                                                    string Type   = E4["Value"]?.InnerText;
                                                    int    Count2 = XML.Attribute(E4, "count", 0);

                                                    Statistics.PerType.Join(Type, Count2, First, Message, null);
                                                    Statistics.PerMessage.Join(Message, Count2, First, Type, null);
                                                }
                                                break;

                                            case "PerSource":
                                                foreach (XmlNode N4 in E3.ChildNodes)
                                                {
                                                    if (!(N4 is XmlElement E4) || E4.LocalName != "Stat")
                                                    {
                                                        continue;
                                                    }

                                                    string StackTrace = E4["Value"]?.InnerText;
                                                    int    Count2     = XML.Attribute(E4, "count", 0);

                                                    Statistics.PerMessage.Join(Message, Count2, First, null, StackTrace);
                                                    Statistics.PerSource.Join(StackTrace, Count2, First, null, Message);
                                                }
                                                break;

                                            default:
                                                throw new Exception("Unknown element: " + E3.LocalName);
                                            }
                                        }
                                    }
                                    break;

                                case "PerSource":
                                    foreach (XmlNode N2 in E.ChildNodes)
                                    {
                                        if (!(N2 is XmlElement E2) || E2.LocalName != "Stat")
                                        {
                                            continue;
                                        }

                                        string StackTrace = null;
                                        int    Count      = XML.Attribute(E2, "count", 0);

                                        foreach (XmlNode N3 in E2.ChildNodes)
                                        {
                                            if (!(N3 is XmlElement E3))
                                            {
                                                continue;
                                            }

                                            switch (E3.LocalName)
                                            {
                                            case "Value":
                                                StackTrace = E3.InnerText;
                                                break;

                                            case "PerType":
                                                foreach (XmlNode N4 in E3.ChildNodes)
                                                {
                                                    if (!(N4 is XmlElement E4) || E4.LocalName != "Stat")
                                                    {
                                                        continue;
                                                    }

                                                    string Type   = E4["Value"]?.InnerText;
                                                    int    Count2 = XML.Attribute(E4, "count", 0);

                                                    Statistics.PerType.Join(Type, Count2, First, null, StackTrace);
                                                    Statistics.PerSource.Join(StackTrace, Count2, First, Type, null);
                                                }
                                                break;

                                            case "PerMessage":
                                                foreach (XmlNode N4 in E3.ChildNodes)
                                                {
                                                    if (!(N4 is XmlElement E4) || E4.LocalName != "Stat")
                                                    {
                                                        continue;
                                                    }

                                                    string Message = E4["Value"]?.InnerText;
                                                    int    Count2  = XML.Attribute(E4, "count", 0);

                                                    Statistics.PerMessage.Join(Message, Count2, First, null, StackTrace);
                                                    Statistics.PerSource.Join(StackTrace, Count2, First, null, Message);
                                                }
                                                break;

                                            default:
                                                throw new Exception("Unknown element: " + E3.LocalName);
                                            }
                                        }
                                    }
                                    break;

                                case "PerHour":
                                    foreach (XmlNode N2 in E.ChildNodes)
                                    {
                                        if (!(N2 is XmlElement E2) || E2.LocalName != "Stat")
                                        {
                                            continue;
                                        }

                                        string TP = XML.Attribute(E2, "hour");
                                        if (XML.TryParse(TP + ":00:00", out DateTime Hour))
                                        {
                                            int Count = XML.Attribute(E2, "count", 0);

                                            Statistics.PerHour.Join(Hour, Count, First);
                                        }
                                    }
                                    break;

                                case "PerDay":
                                    foreach (XmlNode N2 in E.ChildNodes)
                                    {
                                        if (!(N2 is XmlElement E2) || E2.LocalName != "Stat")
                                        {
                                            continue;
                                        }

                                        DateTime Day   = XML.Attribute(E2, "day", DateTime.MinValue);
                                        int      Count = XML.Attribute(E2, "count", 0);

                                        Statistics.PerDay.Join(Day, Count, First);
                                    }
                                    break;

                                case "PerMonth":
                                    foreach (XmlNode N2 in E.ChildNodes)
                                    {
                                        if (!(N2 is XmlElement E2) || E2.LocalName != "Stat")
                                        {
                                            continue;
                                        }

                                        string TP = XML.Attribute(E2, "month");
                                        if (XML.TryParse(TP + "-01", out DateTime Month))
                                        {
                                            int Count = XML.Attribute(E2, "count", 0);

                                            Statistics.PerMonth.Join(Month, Count, First);
                                        }
                                    }
                                    break;

                                default:
                                    throw new Exception("Unknown element: " + E.LocalName);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.Out.WriteLine(ex.Message);
                        }

                        Statistics.RemoveUntouched();
                        First = false;
                    }
                }

                Export(Output, "PerType", "type", Statistics.PerType, "PerMessage", "PerSource");
                Export(Output, "PerMessage", "message", Statistics.PerMessage, "PerType", "PerSource");
                Export(Output, "PerSource", string.Empty, Statistics.PerSource, "PerType", "PerMessage");
                Export(Output, "PerHour", "hour", "yyyy-MM-ddTHH", Statistics.PerHour);
                Export(Output, "PerDay", "day", "yyyy-MM-dd", Statistics.PerDay);
                Export(Output, "PerMonth", "month", "yyyy-MM", Statistics.PerMonth);

                Output.WriteEndElement();
                Output.WriteEndDocument();

                return(0);
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
                return(-1);
            }
            finally
            {
                Output?.Flush();
                Output?.Close();
                Output?.Dispose();
                FileOutput?.Dispose();
            }
        }
        public static ushort WriteFile()
        {
            bool success = false;
            FileStream myFS = null;
            XmlWriter myXMLWriter = null;
            myCC.Enter(); // Will not finish, until you have the Critical Section
            try
            {
                myFS = new FileStream(String.Format("\\NVRAM\\{0}\\SmartThings\\Credentials.xml", InitialParametersClass.ProgramIDTag), FileMode.Create);
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.IndentChars = "     "; // note: default is two spaces
                settings.NewLineOnAttributes = false;
                settings.OmitXmlDeclaration = true;
                myXMLWriter = new XmlWriter(myFS, settings);

                myXMLWriter.WriteStartElement("SmartThingsCredentials");
                myXMLWriter.WriteElementString("ClientID", SmartThingsReceiver.ClientID);
                myXMLWriter.WriteElementString("ClientSecret", SmartThingsReceiver.ClientSecret);
                myXMLWriter.WriteElementString("AuthCode", SmartThingsReceiver.AuthCode);
                myXMLWriter.WriteElementString("AccessToken", SmartThingsReceiver.AccessToken);
                myXMLWriter.WriteElementString("InstallationURL", SmartThingsReceiver.InstallationURL);
                myXMLWriter.WriteEndElement();                
                myXMLWriter.WriteEndDocument();
                myXMLWriter.Flush();
                success = true;
            }
            catch (Exception e)
            {
                Crestron.SimplSharp.ErrorLog.Error(String.Format("Write File Error: {0}\n", e.Message));
                success = false;
            }
            finally
            {
                if (myXMLWriter != null)
                    myXMLWriter.Close();
                if (myFS != null)
                    myFS.Close();
                myCC.Leave();
            }
            if (success)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }