Write(
            System.Xml.XmlDocument document)
        {
            var settings = new System.Xml.XmlWriterSettings();

            settings.CheckCharacters     = true;
            settings.CloseOutput         = true;
            settings.ConformanceLevel    = System.Xml.ConformanceLevel.Auto;
            settings.Indent              = true;
            settings.IndentChars         = new string(' ', 4);
            settings.NewLineChars        = "\n";
            settings.NewLineHandling     = System.Xml.NewLineHandling.None;
            settings.NewLineOnAttributes = false;
            settings.OmitXmlDeclaration  = false;
            settings.Encoding            = new System.Text.UTF8Encoding(false); // do not write BOM

            var xmlString = new System.Text.StringBuilder();

            using (var xmlWriter = System.Xml.XmlWriter.Create(xmlString, settings))
            {
                document.WriteTo(xmlWriter);
                xmlWriter.WriteWhitespace(settings.NewLineChars);
            }

            return(xmlString);
        }
Пример #2
0
        WriteXMLIfDifferent(
            string targetPath,
            System.Xml.XmlWriterSettings settings,
            System.Xml.XmlDocument document)
        {
            var targetExists = System.IO.File.Exists(targetPath);
            var writePath    = targetExists ? Bam.Core.IOWrapper.CreateTemporaryFile() : targetPath;

            using (var xmlwriter = System.Xml.XmlWriter.Create(writePath, settings))
            {
                //Bam.Core.Log.MessageAll("Writing {0}", writePath);
                document.WriteTo(xmlwriter);
            }
            if (targetExists)
            {
                if (AreTextFilesIdentical(targetPath, writePath))
                {
                    // delete temporary
                    System.IO.File.Delete(writePath);
                }
                else
                {
                    //Bam.Core.Log.MessageAll("\tXML has changed, moving {0} to {1}", writePath, targetPath);
                    System.IO.File.Delete(targetPath);
                    System.IO.File.Move(writePath, targetPath);
                }
            }
        }
Пример #3
0
 /// <summary>
 /// 将xml字符串格式化
 /// </summary>
 /// <param name="originalString">原始字符串</param>
 /// <param name="formatString">格式化后的数据,或错误信息</param>
 /// <returns>是否成功</returns>
 public static bool FormatXmlString(string originalString, out string formatString)
 {
     System.Xml.XmlDocument   xmlDoc = new System.Xml.XmlDocument();
     System.IO.StringWriter   sw     = new System.IO.StringWriter();
     System.Xml.XmlTextWriter xtw    = new System.Xml.XmlTextWriter(sw);
     xtw.Formatting  = System.Xml.Formatting.Indented;
     xtw.Indentation = 1;
     xtw.IndentChar  = '\t';
     try
     {
         xmlDoc.LoadXml(originalString);
         xmlDoc.WriteTo(xtw);
         formatString = sw.ToString();
         return(true);
     }
     catch (Exception ex)
     {
         formatString = ex.Message;
         return(false);
     }
     finally
     {
         sw.Dispose();
     }
 }
Пример #4
0
        private void saveConfigurationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var xml = Brain.KB.ToXML();
            var doc = new System.Xml.XmlDocument();

            doc.LoadXml(xml);
            var sw  = new System.IO.StringWriter();
            var xtw = new System.Xml.XmlTextWriter(sw);

            xtw.Formatting = System.Xml.Formatting.Indented;
            doc.WriteTo(xtw);

            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter           = "KickBrain File|*.kickb";
            saveFileDialog1.Title            = "Save Configuration";
            saveFileDialog1.RestoreDirectory = true;
            saveFileDialog1.ShowDialog();

            if (saveFileDialog1.FileName == "")
            {
                return;
            }

            System.IO.File.WriteAllText(saveFileDialog1.FileName, sw.ToString());
        }
Пример #5
0
 public static string FormatXML(string str)
 {
     System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
     doc.LoadXml(str);
     System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
     System.IO.StringWriter    stringWriter  = new System.IO.StringWriter(stringBuilder);
     System.Xml.XmlTextWriter  xmlWriter     = new System.Xml.XmlTextWriter(stringWriter);
     xmlWriter.Formatting = System.Xml.Formatting.Indented;
     doc.WriteTo(xmlWriter);
     return(stringBuilder.ToString());
 }
Пример #6
0
 /// <summary>
 /// hack tip:通过更新web.config文件方式来重启IIS进程池(注:iis中web园数量须大于1,且为非虚拟主机用户才可调用该方法)
 /// </summary>
 public static void RestartIISProcess()
 {
     try {
         System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
         xmldoc.Load("~/web.config".GetMapPath());
         System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter("~/web.config".GetMapPath(), null);
         writer.Formatting = System.Xml.Formatting.Indented;
         xmldoc.WriteTo(writer);
         writer.Flush();
         writer.Close();
     } catch {; }
 }
Пример #7
0
 /// <summary>
 /// 保存Config参数
 /// </summary>
 public static void UpdateConfig(string name, string nKey, string nValue)
 {
     if (ReadConfig(name, nKey) != "")
     {
         System.Xml.XmlDocument XmlDoc = new System.Xml.XmlDocument();
         XmlDoc.Load(HttpContext.Current.Server.MapPath(name + ".config"));
         System.Xml.XmlNodeList elemList = XmlDoc.GetElementsByTagName(nKey);
         System.Xml.XmlNode     mNode    = elemList[0];
         mNode.InnerText = nValue;
         System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(new System.IO.StreamWriter(HttpContext.Current.Server.MapPath(name + ".config")));
         xw.Formatting = System.Xml.Formatting.Indented;
         XmlDoc.WriteTo(xw);
         xw.Close();
     }
 }
Пример #8
0
 /// <summary>
 /// 保存Config参数
 /// </summary>
 public static void UpdateConfig(string name, string nKey, string nValue)
 {
     if (ReadConfig(name, nKey) != "")
     {
         System.Xml.XmlDocument XmlDoc = new System.Xml.XmlDocument();
         XmlDoc.Load(HttpContext.Current.Server.MapPath(name + ".config"));
         System.Xml.XmlNodeList elemList = XmlDoc.GetElementsByTagName(nKey);
         System.Xml.XmlNode mNode = elemList[0];
         mNode.InnerText = nValue;
         System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(new System.IO.StreamWriter(HttpContext.Current.Server.MapPath(name + ".config")));
         xw.Formatting = System.Xml.Formatting.Indented;
         XmlDoc.WriteTo(xw);
         xw.Close();
     }
 }
Пример #9
0
        WriteResXFile(
            string projectPath)
        {
            if (0 == Graph.Instance.Packages.Count())
            {
                throw new Exception("Package has not been specified. Run 'bam' from the package directory.");
            }

            var masterPackage = Graph.Instance.MasterPackage;

            var projectDirectory = System.IO.Path.GetDirectoryName(projectPath);

            if (!System.IO.Directory.Exists(projectDirectory))
            {
                System.IO.Directory.CreateDirectory(projectDirectory);
            }

            var resourceFilePathName = System.IO.Path.Combine(projectDirectory, "PackageInfoResources.resx");

            var resourceFile = new System.Xml.XmlDocument();
            var root         = resourceFile.CreateElement("root");

            resourceFile.AppendChild(root);

            AddResHeader(resourceFile, "resmimetype", "text/microsoft-resx", root);
            AddResHeader(resourceFile, "version", "2.0", root);
            // TODO: this looks like the System.Windows.Forms.dll assembly
            AddResHeader(resourceFile, "reader", "System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", root);
            AddResHeader(resourceFile, "writer", "System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", root);

            AddData(resourceFile, "BamInstallDir", Core.Graph.Instance.ProcessState.ExecutableDirectory, root);
            // TODO: could be Core.Graph.Instance.ProcessState.WorkingDirectory?
            AddData(resourceFile, "WorkingDir", masterPackage.GetPackageDirectory(), root);

            var xmlWriterSettings = new System.Xml.XmlWriterSettings();

            xmlWriterSettings.Indent             = true;
            xmlWriterSettings.CloseOutput        = true;
            xmlWriterSettings.OmitXmlDeclaration = true;
            using (var xmlWriter = System.Xml.XmlWriter.Create(resourceFilePathName, xmlWriterSettings))
            {
                resourceFile.WriteTo(xmlWriter);
                xmlWriter.WriteWhitespace(xmlWriterSettings.NewLineChars);
            }

            return(resourceFilePathName);
        }
Пример #10
0
 private static string GetFormattedXmlString(string xml)
 {
     if (!string.IsNullOrEmpty(xml))
     {
         var xmlDoc = new System.Xml.XmlDocument();
         xmlDoc.LoadXml(xml);
         using (var writer = new System.IO.StringWriter())
             using (var xmlW = new System.Xml.XmlTextWriter(writer))
             {
                 xmlW.Formatting = System.Xml.Formatting.Indented;
                 xmlDoc.WriteTo(xmlW);
                 xmlW.Flush();
                 return(writer.ToString());
             }
     }
     return(null);
 }
Пример #11
0
        WriteXMLIfDifferent(
            string targetPath,
            System.Xml.XmlWriterSettings settings,
            System.Xml.XmlDocument document)
        {
            var targetExists = System.IO.File.Exists(targetPath);
            var writePath    = targetExists ? System.IO.Path.GetTempFileName() : targetPath;

            using (var xmlwriter = System.Xml.XmlWriter.Create(writePath, settings))
            {
                document.WriteTo(xmlwriter);
            }
            Bam.Core.Log.DebugMessage(PrettyPrintXMLDoc(document));
            if (targetExists && !AreTextFilesIdentical(targetPath, writePath))
            {
                Bam.Core.Log.DebugMessage("\tXML has changed, moving {0} to {1}", writePath, targetPath);
                System.IO.File.Delete(targetPath);
                System.IO.File.Move(writePath, targetPath);
            }
        }
        protected virtual void WriteToStream(System.IO.Stream stream, PersistenceFlags flags)
        {
//			System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(stream, System.Text.Encoding.UTF8);
//
//			writer.Formatting = System.Xml.Formatting.Indented;
//			writer.WriteStartDocument();
//			writer.WriteStartElement("settings");
//
//			writer.WriteStartElement("items");
//			writer.WriteAttributeString("schemaversion", "1");
//
//			foreach (PersistableItem item in m_Dictionary.Values)
//			{
//				if ( (flags & PersistenceFlags.OnlyChanges) == PersistenceFlags.OnlyChanges &&
//					item.IsChanged == false)
//					continue;
//
//				writer.WriteStartElement("item");
//				writer.WriteAttributeString("name", item.Name);
//				writer.WriteAttributeString("type", item.Type.FullName);
//				writer.WriteAttributeString("schemaversion", "1");
//				writer.WriteString(item.Validator.ValueToString(item.Value));
//				writer.WriteEndElement();
//			}
//
//			writer.WriteEndElement();
//
//			writer.WriteEndElement();
//			writer.WriteEndDocument();
//			writer.Flush();


            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.AppendChild(doc.CreateElement("settings"));
            WriteToXmlElement(doc.DocumentElement, flags);

            System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(stream, System.Text.Encoding.UTF8);
            writer.Formatting = System.Xml.Formatting.Indented;
            doc.WriteTo(writer);
            writer.Flush();
        }
Пример #13
0
            public void Save()
            {
                System.Xml.XmlDocument xmlDoc   = new System.Xml.XmlDocument();
                System.Xml.XmlNode     rootNode = xmlDoc.CreateElement(Utility.GetSettingsName());
                xmlDoc.AppendChild(rootNode);

                foreach (KeyValuePair <string, string> pair in this.dictionary)
                {
                    System.Xml.XmlNode node = xmlDoc.CreateElement(pair.Key);
                    node.InnerText = pair.Value;
                    rootNode.AppendChild(node);
                }

                using (var stringWriter = new System.IO.StringWriter())
                {
                    using (var xmlTextWriter = System.Xml.XmlWriter.Create(stringWriter))
                    {
                        xmlDoc.WriteTo(xmlTextWriter);
                        xmlTextWriter.Flush();
                        EditorPrefs.SetString(Utility.GetSettingsName(), stringWriter.GetStringBuilder().ToString());
                    }
                }
            }
Пример #14
0
        Write(
            System.Xml.XmlDocument document,
            string path)
        {
            // do not write a Byte-Ordering-Mark (BOM)
            var encoding = new System.Text.UTF8Encoding(false);

            Bam.Core.IOWrapper.CreateDirectory(System.IO.Path.GetDirectoryName(path));
            using (var writer = new System.IO.StreamWriter(path, false, encoding))
            {
                var settings = new System.Xml.XmlWriterSettings();
                settings.OmitXmlDeclaration  = false;
                settings.NewLineChars        = "\n";
                settings.Indent              = true;
                settings.IndentChars         = "   ";
                settings.NewLineOnAttributes = true;
                using (var xmlWriter = System.Xml.XmlWriter.Create(writer, settings))
                {
                    document.WriteTo(xmlWriter);
                    xmlWriter.WriteWhitespace(settings.NewLineChars);
                }
            }
        }
Пример #15
0
        public static void test()
        {
            //检查XML解析测试
            string xmlString = _config.Entity.ToString();

            System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
            try
            {
                xmldoc.LoadXml(xmlString);
            }
            catch (Exception e)
            {
                Console.Write(e.StackTrace);
            }
            //格式化XML
            StringBuilder sbStr = new StringBuilder();

            System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(new StringWriter(sbStr));
            writer.Formatting  = System.Xml.Formatting.Indented;
            writer.IndentChar  = '\t';
            writer.Indentation = 1;
            xmldoc.WriteTo(writer);
            Console.Write(sbStr.ToString());
        }
Пример #16
0
        Create()
        {
            Core.PackageUtilities.IdentifyAllPackages();

            var masterPackage     = Core.Graph.Instance.MasterPackage;
            var masterPackageName = masterPackage.Name;
            var projectPathname   = masterPackage.GetDebugPackageProjectPathname();

            RootUri = new System.Uri(projectPathname);

            var projectDir = System.IO.Path.GetDirectoryName(projectPathname);

            Core.IOWrapper.CreateDirectoryIfNotExists(projectDir);

            var mainSourceFile = System.IO.Path.Combine(projectDir, "main.cs");

            WriteEntryPoint(mainSourceFile);

            Document.AppendChild(Document.CreateComment("Automatically generated by BuildAMation"));
            var project = CreateElement("Project", Document);

            CreateAttribute("ToolsVersion", "12.0", project);
            CreateAttribute("DefaultsTarget", "Build", project);

            CreateImport(@"$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props", true, project);

            var generalProperties = CreatePropertyGroup(parent: project);

            CreateElement("Configuration", condition: @" '$(Configuration)' == '' ", parent: generalProperties, value: "Debug");
            CreateElement("Platform", condition: @" '$(Platform)' == '' ", parent: generalProperties, value: "AnyCPU");
            CreateElement("ProjectGuid", parent: generalProperties, value: System.Guid.NewGuid().ToString("B").ToUpper());
            CreateElement("OutputType", parent: generalProperties, value: "Exe");
            CreateElement("RootNamespace", parent: generalProperties, value: masterPackageName);
            CreateElement("AssemblyName", parent: generalProperties, value: masterPackageName);
            CreateElement("TargetFrameworkVersion", parent: generalProperties, value: "v4.5");
            CreateElement("WarningLevel", parent: generalProperties, value: "4");
            CreateElement("TreatWarningsAsErrors", parent: generalProperties, value: "true");

            var debugProperties = CreatePropertyGroup(condition: @" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ", parent: project);

            CreateElement("PlatformTarget", parent: debugProperties, value: "AnyCPU");
            CreateElement("DebugSymbols", parent: debugProperties, value: "true");
            CreateElement("DebugType", parent: debugProperties, value: "full");
            CreateElement("Optimize", parent: debugProperties, value: "false");
            CreateElement("OutputPath", parent: debugProperties, value: @"bin\Debug\");
            CreateElement("CheckForOverflowUnderflow", parent: debugProperties, value: "true");
            CreateElement("AllowUnsafeBlocks", parent: debugProperties, value: "false");
            CreateElement("DefineConstants", parent: debugProperties, value: GetPreprocessorDefines());

            var references = CreateItemGroup(parent: project);

            foreach (var desc in masterPackage.DotNetAssemblies)
            {
                CreateReference(desc.Name, references, targetframework: desc.RequiredTargetFramework);
            }
            if (Core.Graph.Instance.ProcessState.RunningMono)
            {
                CreateReference("Mono.Posix", references);
            }
            foreach (var assembly in masterPackage.BamAssemblies)
            {
                var assemblyPath = System.IO.Path.Combine(Core.Graph.Instance.ProcessState.ExecutableDirectory, assembly.Name) + ".dll";
                CreateReference(assembly.Name, references, hintpath: assemblyPath);
            }

            var mainSource = CreateItemGroup(parent: project);

            CreateCompilableSourceFile(mainSourceFile, null, mainSource);
            foreach (var package in Core.Graph.Instance.Packages)
            {
                var packageSource = CreateItemGroup(parent: project);

                CreateOtherSourceFile(package.XMLFilename, package, packageSource);

                foreach (var script in package.GetScriptFiles(allBuilders: true))
                {
                    CreateCompilableSourceFile(script, package, packageSource);
                }
            }

            var resourceFilePathName = Core.PackageListResourceFile.WriteResXFile(projectPathname);
            var resources            = CreateItemGroup(parent: project);

            CreateEmbeddedResourceFile(resourceFilePathName, resources);

            CreateImport(@"$(MSBuildBinPath)\Microsoft.CSharp.Targets", false, project);

            var xmlWriterSettings = new System.Xml.XmlWriterSettings();

            xmlWriterSettings.Indent             = true;
            xmlWriterSettings.CloseOutput        = true;
            xmlWriterSettings.OmitXmlDeclaration = false;
            using (var writer = System.Xml.XmlWriter.Create(projectPathname, xmlWriterSettings))
            {
                Document.WriteTo(writer);
            }

            Core.Log.Info("Successfully created debug project for package '{0}'", masterPackage.FullName);
            Core.Log.Info("\t{0}", projectPathname);
        }
Пример #17
0
		protected virtual void WriteToStream(System.IO.Stream stream, PersistenceFlags flags)
		{
//			System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(stream, System.Text.Encoding.UTF8);
//			
//			writer.Formatting = System.Xml.Formatting.Indented;
//			writer.WriteStartDocument();
//			writer.WriteStartElement("settings");
//
//			writer.WriteStartElement("items");
//			writer.WriteAttributeString("schemaversion", "1");
//			
//			foreach (PersistableItem item in m_Dictionary.Values)
//			{
//				if ( (flags & PersistenceFlags.OnlyChanges) == PersistenceFlags.OnlyChanges &&
//					item.IsChanged == false)
//					continue;
//
//				writer.WriteStartElement("item");
//				writer.WriteAttributeString("name", item.Name);
//				writer.WriteAttributeString("type", item.Type.FullName);
//				writer.WriteAttributeString("schemaversion", "1");
//				writer.WriteString(item.Validator.ValueToString(item.Value));
//				writer.WriteEndElement();
//			}
//
//			writer.WriteEndElement();
//
//			writer.WriteEndElement();
//			writer.WriteEndDocument();
//			writer.Flush();


			System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
			doc.AppendChild(doc.CreateElement("settings"));
			WriteToXmlElement(doc.DocumentElement, flags);

			System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(stream, System.Text.Encoding.UTF8);
			writer.Formatting = System.Xml.Formatting.Indented;
			doc.WriteTo(writer);
			writer.Flush();
		}
Пример #18
0
        /// <summary>
        /// Write the latest version of the XML definition file.
        /// Always refer to the schema location as a relative path to the bam executable.
        /// Always reference the default namespace in the first element.
        /// Don't use a namespace prefix on child elements, as the default namespace covers them.
        /// </summary>
        public void Write()
        {
            if (System.IO.File.Exists(this.XMLFilename))
            {
                var attributes = System.IO.File.GetAttributes(this.XMLFilename);
                if (0 != (attributes & System.IO.FileAttributes.ReadOnly))
                {
                    throw new Exception("File '{0}' cannot be written to as it is read only", this.XMLFilename);
                }
            }

            this.Dependents.Sort();

            var document = new System.Xml.XmlDocument();
            var namespaceURI = "http://www.buildamation.com";
            var packageDefinition = document.CreateElement("PackageDefinition", namespaceURI);
            {
                var xmlns = "http://www.w3.org/2001/XMLSchema-instance";
                var schemaAttribute = document.CreateAttribute("xsi", "schemaLocation", xmlns);
                var mostRecentSchemaRelativePath = "./Schema/BamPackageDefinitionV1.xsd";
                schemaAttribute.Value = System.String.Format("{0} {1}", namespaceURI, mostRecentSchemaRelativePath);
                packageDefinition.Attributes.Append(schemaAttribute);
                packageDefinition.SetAttribute("name", this.Name);
                if (null != this.Version)
                {
                    packageDefinition.SetAttribute("version", this.Version);
                }
            }
            document.AppendChild(packageDefinition);

            // package description
            if (!string.IsNullOrEmpty(this.Description))
            {
                var descriptionElement = document.CreateElement("Description", namespaceURI);
                descriptionElement.InnerText = this.Description;
                packageDefinition.AppendChild(descriptionElement);
            }

            // package repositories
            var packageRepos = new StringArray(this.PackageRepositories);
            // TODO: could these be marked as transient?
            // don't write out the repo that this package resides in
            packageRepos.Remove(this.GetPackageRepository());
            // nor an associated repo for tests
            var associatedRepo = this.GetAssociatedPackageDirectoryForTests();
            if (null != associatedRepo)
            {
                packageRepos.Remove(associatedRepo);
            }
            if (packageRepos.Count > 0)
            {
                var packageRootsElement = document.CreateElement("PackageRepositories", namespaceURI);
                var bamDir = this.GetBamDirectory() + System.IO.Path.DirectorySeparatorChar; // slash added to make it look like a directory
                foreach (string repo in packageRepos)
                {
                    var relativePackageRepo = RelativePathUtilities.GetPath(repo, bamDir);
                    if (OSUtilities.IsWindowsHosting)
                    {
                        // standardize on non-Windows directory separators
                        relativePackageRepo = relativePackageRepo.Replace(System.IO.Path.DirectorySeparatorChar, System.IO.Path.AltDirectorySeparatorChar);
                    }

                    var rootElement = document.CreateElement("Repo", namespaceURI);
                    rootElement.SetAttribute("dir", relativePackageRepo);
                    packageRootsElement.AppendChild(rootElement);
                }

                packageDefinition.AppendChild(packageRootsElement);
            }

            if (this.Dependents.Count > 0)
            {
                var dependentsEl = document.CreateElement("Dependents", namespaceURI);
                foreach (var package in this.Dependents)
                {
                    var packageName = package.Item1;
                    var packageVersion = package.Item2;
                    var packageIsDefault = package.Item3;
                    System.Xml.XmlElement packageElement = null;

                    {
                        var node = dependentsEl.FirstChild;
                        while (node != null)
                        {
                            var attributes = node.Attributes;
                            var nameAttribute = attributes["Name"];
                            if ((null != nameAttribute) && (nameAttribute.Value == packageName))
                            {
                                packageElement = node as System.Xml.XmlElement;
                                break;
                            }

                            node = node.NextSibling;
                        }
                    }

                    if (null == packageElement)
                    {
                        packageElement = document.CreateElement("Package", namespaceURI);
                        packageElement.SetAttribute("name", packageName);
                        if (null != packageVersion)
                        {
                            packageElement.SetAttribute("version", packageVersion);
                        }
                        if (packageIsDefault.HasValue)
                        {
                            packageElement.SetAttribute("default", packageIsDefault.Value.ToString().ToLower());
                        }
                        dependentsEl.AppendChild(packageElement);
                    }
                }
                packageDefinition.AppendChild(dependentsEl);
            }

            if (this.BamAssemblies.Count > 0)
            {
                var requiredAssemblies = document.CreateElement("BamAssemblies", namespaceURI);
                foreach (var assembly in this.BamAssemblies)
                {
                    var assemblyElement = document.CreateElement("BamAssembly", namespaceURI);
                    assemblyElement.SetAttribute("name", assembly.Name);
                    if (assembly.MajorVersion.HasValue)
                    {
                        assemblyElement.SetAttribute("major", assembly.MajorVersion.ToString());
                        if (assembly.MinorVersion.HasValue)
                        {
                            assemblyElement.SetAttribute("minor", assembly.MinorVersion.ToString());
                            if (assembly.PatchVersion.HasValue)
                            {
                                // honour any existing BamAssembly with a specific patch version
                                assemblyElement.SetAttribute("patch", assembly.PatchVersion.ToString());
                            }
                        }
                    }
                    requiredAssemblies.AppendChild(assemblyElement);
                }
                packageDefinition.AppendChild(requiredAssemblies);
            }

            if (this.DotNetAssemblies.Count > 0)
            {
                var requiredDotNetAssemblies = document.CreateElement("DotNetAssemblies", namespaceURI);
                foreach (var desc in this.DotNetAssemblies)
                {
                    var assemblyElement = document.CreateElement("DotNetAssembly", namespaceURI);
                    assemblyElement.SetAttribute("name", desc.Name);
                    if (null != desc.RequiredTargetFramework)
                    {
                        assemblyElement.SetAttribute("requiredTargetFramework", desc.RequiredTargetFramework);
                    }
                    requiredDotNetAssemblies.AppendChild(assemblyElement);
                }
                packageDefinition.AppendChild(requiredDotNetAssemblies);
            }

            // supported platforms
            {
                var supportedPlatformsElement = document.CreateElement("SupportedPlatforms", namespaceURI);

                if (EPlatform.Windows == (this.SupportedPlatforms & EPlatform.Windows))
                {
                    var platformElement = document.CreateElement("Platform", namespaceURI);
                    platformElement.SetAttribute("name", "Windows");
                    supportedPlatformsElement.AppendChild(platformElement);
                }
                if (EPlatform.Linux == (this.SupportedPlatforms & EPlatform.Linux))
                {
                    var platformElement = document.CreateElement("Platform", namespaceURI);
                    platformElement.SetAttribute("name", "Linux");
                    supportedPlatformsElement.AppendChild(platformElement);
                }
                if (EPlatform.OSX == (this.SupportedPlatforms & EPlatform.OSX))
                {
                    var platformElement = document.CreateElement("Platform", namespaceURI);
                    platformElement.SetAttribute("name", "OSX");
                    supportedPlatformsElement.AppendChild(platformElement);
                }

                packageDefinition.AppendChild(supportedPlatformsElement);
            }

            // definitions
            this.Definitions.Remove(this.GetPackageDefinitionName());
            if (this.Definitions.Count > 0)
            {
                var definitionsElement = document.CreateElement("Definitions", namespaceURI);

                foreach (string define in this.Definitions)
                {
                    var defineElement = document.CreateElement("Definition", namespaceURI);
                    defineElement.SetAttribute("name", define);
                    definitionsElement.AppendChild(defineElement);
                }

                packageDefinition.AppendChild(definitionsElement);
            }

            var xmlWriterSettings = new System.Xml.XmlWriterSettings();
            xmlWriterSettings.Indent = true;
            xmlWriterSettings.CloseOutput = true;
            xmlWriterSettings.OmitXmlDeclaration = false;
            xmlWriterSettings.NewLineOnAttributes = false;
            xmlWriterSettings.NewLineChars = "\n";
            xmlWriterSettings.ConformanceLevel = System.Xml.ConformanceLevel.Document;
            xmlWriterSettings.Encoding = new System.Text.UTF8Encoding(false);

            using (var xmlWriter = System.Xml.XmlWriter.Create(this.XMLFilename, xmlWriterSettings))
            {
                document.WriteTo(xmlWriter);
                xmlWriter.WriteWhitespace(xmlWriterSettings.NewLineChars);
            }

            if (this.validate)
            {
                this.Validate();
            }
        }
 private static string GetFormattedXmlString(string xml)
 {
     if (!string.IsNullOrEmpty(xml))
     {
         var xmlDoc = new System.Xml.XmlDocument();
         xmlDoc.LoadXml(xml);
         using (var writer = new System.IO.StringWriter())
         using (var xmlW = new System.Xml.XmlTextWriter(writer))
         {
             xmlW.Formatting = System.Xml.Formatting.Indented;
             xmlDoc.WriteTo(xmlW);
             xmlW.Flush();
             return writer.ToString();
         }
     }
     return null;
 }
Пример #20
0
 /// <summary>
 /// hack tip:通过更新web.config文件方式来重启IIS进程池(注:iis中web园数量须大于1,且为非虚拟主机用户才可调用该方法)
 /// </summary>
 public static void RestartIISProcess() {
     try {
         System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
         xmldoc.Load("~/web.config".GetMapPath());
         System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter("~/web.config".GetMapPath(), null);
         writer.Formatting = System.Xml.Formatting.Indented;
         xmldoc.WriteTo(writer);
         writer.Flush();
         writer.Close();
     } catch { ; }
 }
Пример #21
0
        private void saveConfigurationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var xml = Brain.KB.ToXML();
            var doc = new System.Xml.XmlDocument();
            doc.LoadXml(xml);
            var sw = new System.IO.StringWriter();
            var xtw = new System.Xml.XmlTextWriter(sw);
            xtw.Formatting = System.Xml.Formatting.Indented;
            doc.WriteTo(xtw);

            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Filter = "KickBrain File|*.kickb";
            saveFileDialog1.Title = "Save Configuration";
            saveFileDialog1.RestoreDirectory = true;
            saveFileDialog1.ShowDialog();

            if (saveFileDialog1.FileName == "")
                return;

            System.IO.File.WriteAllText(saveFileDialog1.FileName, sw.ToString());
        }
Пример #22
0
        public string Serialize()
        {
            var workspaceDoc = new System.Xml.XmlDocument();
            var workspaceEl = workspaceDoc.CreateElement("Workspace");
            workspaceEl.SetAttribute("version", "1.0");
            workspaceDoc.AppendChild(workspaceEl);

            var generateProjectSchemes = Bam.Core.CommandLineProcessor.Evaluate(new Options.GenerateXcodeSchemes());
            foreach (var project in this.ProjectMap.Values)
            {
                project.FixupPerConfigurationData();

                var text = new System.Text.StringBuilder();
                text.AppendLine("// !$*UTF8*$!");
                text.AppendLine("{");
                var indentLevel = 1;
                var indent = new string('\t', indentLevel);
                text.AppendFormat("{0}archiveVersion = 1;", indent);
                text.AppendLine();
                text.AppendFormat("{0}classes = {{", indent);
                text.AppendLine();
                text.AppendFormat("{0}}};", indent);
                text.AppendLine();
                text.AppendFormat("{0}objectVersion = 46;", indent);
                text.AppendLine();
                text.AppendFormat("{0}objects = {{", indent);
                text.AppendLine();
                project.Serialize(text, indentLevel + 1);
                text.AppendFormat("{0}}};", indent);
                text.AppendLine();
                text.AppendFormat("{0}rootObject = {1} /* Project object */;", indent, project.GUID);
                text.AppendLine();
                text.AppendLine("}");

                var projectDir = project.ProjectDir;
                if (!System.IO.Directory.Exists(projectDir.Parse()))
                {
                    System.IO.Directory.CreateDirectory(projectDir.Parse());
                }

                //Bam.Core.Log.DebugMessage(text.ToString());
                using (var writer = new System.IO.StreamWriter(project.ProjectPath))
                {
                    writer.Write(text.ToString());
                }

                if (generateProjectSchemes)
                {
                    var projectSchemeCache = new ProjectSchemeCache(project);
                    projectSchemeCache.Serialize();
                }

                var workspaceFileRef = workspaceDoc.CreateElement("FileRef");
                workspaceFileRef.SetAttribute("location", System.String.Format("group:{0}", projectDir));
                workspaceEl.AppendChild(workspaceFileRef);
            }

            var workspacePath = Bam.Core.TokenizedString.Create("$(buildroot)/$(masterpackagename).xcworkspace/contents.xcworkspacedata", null);
            var workspaceDir = Bam.Core.TokenizedString.Create("@dir($(0))", null, positionalTokens: new Bam.Core.TokenizedStringArray(workspacePath));
            var workspaceDirectory = workspaceDir.Parse();
            if (!System.IO.Directory.Exists(workspaceDirectory))
            {
                System.IO.Directory.CreateDirectory(workspaceDirectory);
            }

            var settings = new System.Xml.XmlWriterSettings();
            settings.OmitXmlDeclaration = false;
            settings.Encoding = new System.Text.UTF8Encoding(false); // no BOM
            settings.NewLineChars = System.Environment.NewLine;
            settings.Indent = true;
            settings.ConformanceLevel = System.Xml.ConformanceLevel.Document;

            using (var xmlwriter = System.Xml.XmlWriter.Create(workspacePath.Parse(), settings))
            {
                workspaceDoc.WriteTo(xmlwriter);
            }

            return workspaceDirectory;
        }
Пример #23
0
        Serialize()
        {
            var workspaceDoc = new System.Xml.XmlDocument();
            var workspaceEl  = workspaceDoc.CreateElement("Workspace");

            workspaceEl.SetAttribute("version", "1.0");
            workspaceDoc.AppendChild(workspaceEl);

            var generateProjectSchemes = Bam.Core.CommandLineProcessor.Evaluate(new Options.GenerateXcodeSchemes());

            foreach (var project in this.ProjectMap.Values)
            {
                project.FixupPerConfigurationData();

                var text = new System.Text.StringBuilder();
                text.AppendLine("// !$*UTF8*$!");
                text.AppendLine("{");
                var indentLevel = 1;
                var indent      = new string('\t', indentLevel);
                text.AppendFormat("{0}archiveVersion = 1;", indent);
                text.AppendLine();
                text.AppendFormat("{0}classes = {{", indent);
                text.AppendLine();
                text.AppendFormat("{0}}};", indent);
                text.AppendLine();
                text.AppendFormat("{0}objectVersion = 46;", indent);
                text.AppendLine();
                text.AppendFormat("{0}objects = {{", indent);
                text.AppendLine();
                project.Serialize(text, indentLevel + 1);
                text.AppendFormat("{0}}};", indent);
                text.AppendLine();
                text.AppendFormat("{0}rootObject = {1} /* Project object */;", indent, project.GUID);
                text.AppendLine();
                text.AppendLine("}");

                var projectDir = project.ProjectDir;
                if (!System.IO.Directory.Exists(projectDir.Parse()))
                {
                    System.IO.Directory.CreateDirectory(projectDir.Parse());
                }

                //Bam.Core.Log.DebugMessage(text.ToString());
                using (var writer = new System.IO.StreamWriter(project.ProjectPath))
                {
                    writer.Write(text.ToString());
                }

                if (generateProjectSchemes)
                {
                    var projectSchemeCache = new ProjectSchemeCache(project);
                    projectSchemeCache.Serialize();
                }

                var workspaceFileRef = workspaceDoc.CreateElement("FileRef");
                workspaceFileRef.SetAttribute("location", System.String.Format("group:{0}", projectDir));
                workspaceEl.AppendChild(workspaceFileRef);
            }

            var workspacePath      = Bam.Core.TokenizedString.Create("$(buildroot)/$(masterpackagename).xcworkspace/contents.xcworkspacedata", null);
            var workspaceDir       = Bam.Core.TokenizedString.Create("@dir($(0))", null, positionalTokens: new Bam.Core.TokenizedStringArray(workspacePath));
            var workspaceDirectory = workspaceDir.Parse();

            if (!System.IO.Directory.Exists(workspaceDirectory))
            {
                System.IO.Directory.CreateDirectory(workspaceDirectory);
            }

            var settings = new System.Xml.XmlWriterSettings();

            settings.OmitXmlDeclaration = false;
            settings.Encoding           = new System.Text.UTF8Encoding(false); // no BOM
            settings.NewLineChars       = System.Environment.NewLine;
            settings.Indent             = true;
            settings.ConformanceLevel   = System.Xml.ConformanceLevel.Document;

            using (var xmlwriter = System.Xml.XmlWriter.Create(workspacePath.Parse(), settings))
            {
                workspaceDoc.WriteTo(xmlwriter);
            }

            return(workspaceDirectory);
        }
Пример #24
0
        public static void  Main(System.String[] args)
        {
            if (args.Length != 1)
            {
                System.Console.Out.WriteLine("Usage: XMLParser pipe_encoded_file");
                System.Environment.Exit(1);
            }

            //read and parse message from file
            try
            {
                PipeParser         parser      = new PipeParser();
                System.IO.FileInfo messageFile = new System.IO.FileInfo(args[0]);
                long fileLength = SupportClass.FileLength(messageFile);
                //UPGRADE_TODO: Constructor 'java.io.FileReader.FileReader' was converted to 'System.IO.StreamReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
                System.IO.StreamReader r = new System.IO.StreamReader(messageFile.FullName, System.Text.Encoding.Default);
                char[] cbuf = new char[(int)fileLength];
                //UPGRADE_TODO: Method 'java.io.Reader.read' was converted to 'System.IO.StreamReader.Read' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioReaderread_char[]'"
                System.Console.Out.WriteLine("Reading message file ... " + r.Read((System.Char[])cbuf, 0, cbuf.Length) + " of " + fileLength + " chars");
                r.Close();
                System.String messString = System.Convert.ToString(cbuf);
                Message       mess       = parser.parse(messString);
                System.Console.Out.WriteLine("Got message of type " + mess.GetType().FullName);

                ca.uhn.hl7v2.parser.XMLParser xp = new AnonymousClassXMLParser();

                //loop through segment children of message, encode, print to console
                System.String[] structNames = mess.Names;
                for (int i = 0; i < structNames.Length; i++)
                {
                    Structure[] reps = mess.getAll(structNames[i]);
                    for (int j = 0; j < reps.Length; j++)
                    {
                        if (typeof(Segment).IsAssignableFrom(reps[j].GetType()))
                        {
                            //ignore groups
                            //UPGRADE_TODO: Class 'javax.xml.parsers.DocumentBuilder' was converted to 'System.Xml.XmlDocument' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaxxmlparsersDocumentBuilder'"
                            //UPGRADE_ISSUE: Method 'javax.xml.parsers.DocumentBuilderFactory.newInstance' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaxxmlparsersDocumentBuilderFactory'"
                            //DocumentBuilderFactory.newInstance();

                            System.Xml.XmlDocument docBuilder = new System.Xml.XmlDocument();
                            //UPGRADE_TODO: Class 'javax.xml.parsers.DocumentBuilder' was converted to 'System.Xml.XmlDocument' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaxxmlparsersDocumentBuilder'"
                            System.Xml.XmlDocument doc  = new System.Xml.XmlDocument();                            //new doc for each segment
                            System.Xml.XmlElement  root = doc.CreateElement(reps[j].GetType().FullName);
                            doc.AppendChild(root);
                            xp.encode((Segment)reps[j], root);
                            System.IO.StringWriter out_Renamed = new System.IO.StringWriter();
                            System.Console.Out.WriteLine("Segment " + reps[j].GetType().FullName + ": \r\n" + doc.OuterXml);

                            System.Type[]   segmentConstructTypes = new System.Type[] { typeof(Message) };
                            System.Object[] segmentConstructArgs  = new System.Object[] { null };
                            Segment         s = (Segment)reps[j].GetType().GetConstructor(segmentConstructTypes).Invoke(segmentConstructArgs);
                            xp.parse(s, root);
                            //UPGRADE_TODO: Class 'javax.xml.parsers.DocumentBuilder' was converted to 'System.Xml.XmlDocument' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaxxmlparsersDocumentBuilder'"
                            System.Xml.XmlDocument doc2  = new System.Xml.XmlDocument();
                            System.Xml.XmlElement  root2 = doc2.CreateElement(s.GetType().FullName);
                            doc2.AppendChild(root2);
                            xp.encode(s, root2);
                            System.IO.StringWriter   out2 = new System.IO.StringWriter();
                            System.Xml.XmlTextWriter ser  = new System.Xml.XmlTextWriter(out2);

                            //System.Xml.XmlWriter ser = System.Xml.XmlWriter.Create(out2);
                            doc.WriteTo(ser);
                            if (out2.ToString().Equals(out_Renamed.ToString()))
                            {
                                System.Console.Out.WriteLine("Re-encode OK");
                            }
                            else
                            {
                                System.Console.Out.WriteLine("Warning: XML different after parse and re-encode: \r\n" + out2.ToString());
                            }
                        }
                    }
                }
            }
            catch (System.Exception e)
            {
                SupportClass.WriteStackTrace(e, Console.Error);
            }
        }
Пример #25
0
        WriteResXFile(
            string projectPath)
        {
            if (0 == Graph.Instance.Packages.Count())
            {
                throw new Exception("Package has not been specified. Run 'bam' from the package directory.");
            }

            var masterPackage = Graph.Instance.MasterPackage;

            var projectDirectory = System.IO.Path.GetDirectoryName(projectPath);
            if (!System.IO.Directory.Exists(projectDirectory))
            {
                System.IO.Directory.CreateDirectory(projectDirectory);
            }

            var resourceFilePathName = System.IO.Path.Combine(projectDirectory, "PackageInfoResources.resx");

            var resourceFile = new System.Xml.XmlDocument();
            var root = resourceFile.CreateElement("root");
            resourceFile.AppendChild(root);

            AddResHeader(resourceFile, "resmimetype", "text/microsoft-resx", root);
            AddResHeader(resourceFile, "version", "2.0", root);
            // TODO: this looks like the System.Windows.Forms.dll assembly
            AddResHeader(resourceFile, "reader", "System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", root);
            AddResHeader(resourceFile, "writer", "System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", root);

            AddData(resourceFile, "BamInstallDir", Core.Graph.Instance.ProcessState.ExecutableDirectory, root);
            // TODO: could be Core.Graph.Instance.ProcessState.WorkingDirectory?
            AddData(resourceFile, "WorkingDir", masterPackage.GetPackageDirectory(), root);

            var xmlWriterSettings = new System.Xml.XmlWriterSettings();
            xmlWriterSettings.Indent = true;
            xmlWriterSettings.CloseOutput = true;
            xmlWriterSettings.OmitXmlDeclaration = true;
            using (var xmlWriter = System.Xml.XmlWriter.Create(resourceFilePathName, xmlWriterSettings))
            {
                resourceFile.WriteTo(xmlWriter);
                xmlWriter.WriteWhitespace(xmlWriterSettings.NewLineChars);
            }

            return resourceFilePathName;
        }
Пример #26
0
        public static void Main(System.String[] args)
        {
            if (args.Length != 1)
            {
                System.Console.Out.WriteLine("Usage: XMLParser pipe_encoded_file");
                System.Environment.Exit(1);
            }

            //read and parse message from file
            try
            {
                PipeParser         parser      = new PipeParser();
                System.IO.FileInfo messageFile = new System.IO.FileInfo(args[0]);
                long fileLength          = SupportClass.FileLength(messageFile);
                System.IO.StreamReader r = new System.IO.StreamReader(
                    messageFile.FullName,
                    System.Text.Encoding.Default);
                char[] cbuf = new char[(int)fileLength];
                System.Console.Out.WriteLine(
                    "Reading message file ... " + r.Read(cbuf, 0, cbuf.Length) + " of " + fileLength + " chars");
                r.Close();
                System.String messString = System.Convert.ToString(cbuf);
                IMessage      mess       = parser.Parse(messString);
                System.Console.Out.WriteLine("Got message of type " + mess.GetType().FullName);

                NHapi.Base.Parser.XMLParser xp = new AnonymousClassXMLParser();

                //loop through segment children of message, encode, print to console
                System.String[] structNames = mess.Names;
                for (int i = 0; i < structNames.Length; i++)
                {
                    IStructure[] reps = mess.GetAll(structNames[i]);
                    for (int j = 0; j < reps.Length; j++)
                    {
                        if (typeof(ISegment).IsAssignableFrom(reps[j].GetType()))
                        {
                            //ignore groups
                            System.Xml.XmlDocument docBuilder = new System.Xml.XmlDocument();
                            System.Xml.XmlDocument doc        = new System.Xml.XmlDocument(); //new doc for each segment
                            System.Xml.XmlElement  root       = doc.CreateElement(reps[j].GetType().FullName);
                            doc.AppendChild(root);
                            xp.Encode((ISegment)reps[j], root);
                            System.IO.StringWriter out_Renamed = new System.IO.StringWriter();
                            System.Console.Out.WriteLine(
                                "Segment " + reps[j].GetType().FullName + ": \r\n" + doc.OuterXml);

                            System.Type[]   segmentConstructTypes = { typeof(IMessage) };
                            System.Object[] segmentConstructArgs  = { null };
                            ISegment        s =
                                (ISegment)
                                reps[j].GetType().GetConstructor(segmentConstructTypes).Invoke(segmentConstructArgs);
                            xp.Parse(s, root);
                            System.Xml.XmlDocument doc2  = new System.Xml.XmlDocument();
                            System.Xml.XmlElement  root2 = doc2.CreateElement(s.GetType().FullName);
                            doc2.AppendChild(root2);
                            xp.Encode(s, root2);
                            System.IO.StringWriter out2 = new System.IO.StringWriter();
                            System.Xml.XmlWriter   ser  = System.Xml.XmlWriter.Create(out2);
                            doc.WriteTo(ser);
                            if (out2.ToString().Equals(out_Renamed.ToString()))
                            {
                                System.Console.Out.WriteLine("Re-encode OK");
                            }
                            else
                            {
                                System.Console.Out.WriteLine(
                                    "Warning: XML different after parse and re-encode: \r\n" + out2);
                            }
                        }
                    }
                }
            }
            catch (System.Exception e)
            {
                SupportClass.WriteStackTrace(e, Console.Error);
            }
        }
Пример #27
0
        public static void Main(System.String[] args)
        {
            if (args.Length != 1)
            {
                System.Console.Out.WriteLine("Usage: XMLParser pipe_encoded_file");
                System.Environment.Exit(1);
            }

            //read and parse message from file
            try
            {
                PipeParser parser = new PipeParser();
                System.IO.FileInfo messageFile = new System.IO.FileInfo(args[0]);
                long fileLength = SupportClass.FileLength(messageFile);
                //UPGRADE_TODO: Constructor 'java.io.FileReader.FileReader' was converted to 'System.IO.StreamReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
                System.IO.StreamReader r = new System.IO.StreamReader(messageFile.FullName, System.Text.Encoding.Default);
                char[] cbuf = new char[(int) fileLength];
                //UPGRADE_TODO: Method 'java.io.Reader.read' was converted to 'System.IO.StreamReader.Read' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioReaderread_char[]'"
                System.Console.Out.WriteLine("Reading message file ... " + r.Read((System.Char[]) cbuf, 0, cbuf.Length) + " of " + fileLength + " chars");
                r.Close();
                System.String messString = System.Convert.ToString(cbuf);
                Message mess = parser.parse(messString);
                System.Console.Out.WriteLine("Got message of type " + mess.GetType().FullName);

                ca.uhn.hl7v2.parser.XMLParser xp = new AnonymousClassXMLParser();

                //loop through segment children of message, encode, print to console
                System.String[] structNames = mess.Names;
                for (int i = 0; i < structNames.Length; i++)
                {
                    Structure[] reps = mess.getAll(structNames[i]);
                    for (int j = 0; j < reps.Length; j++)
                    {
                        if (typeof(Segment).IsAssignableFrom(reps[j].GetType()))
                        {
                            //ignore groups
                            //UPGRADE_TODO: Class 'javax.xml.parsers.DocumentBuilder' was converted to 'System.Xml.XmlDocument' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaxxmlparsersDocumentBuilder'"
                            //UPGRADE_ISSUE: Method 'javax.xml.parsers.DocumentBuilderFactory.newInstance' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaxxmlparsersDocumentBuilderFactory'"
                            //DocumentBuilderFactory.newInstance();

                            System.Xml.XmlDocument docBuilder = new System.Xml.XmlDocument();
                            //UPGRADE_TODO: Class 'javax.xml.parsers.DocumentBuilder' was converted to 'System.Xml.XmlDocument' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaxxmlparsersDocumentBuilder'"
                            System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); //new doc for each segment
                            System.Xml.XmlElement root = doc.CreateElement(reps[j].GetType().FullName);
                            doc.AppendChild(root);
                            xp.encode((Segment) reps[j], root);
                            System.IO.StringWriter out_Renamed = new System.IO.StringWriter();
                            System.Console.Out.WriteLine("Segment " + reps[j].GetType().FullName + ": \r\n" + doc.OuterXml);

                            System.Type[] segmentConstructTypes = new System.Type[]{typeof(Message)};
                            System.Object[] segmentConstructArgs = new System.Object[]{null};
                            Segment s = (Segment) reps[j].GetType().GetConstructor(segmentConstructTypes).Invoke(segmentConstructArgs);
                            xp.parse(s, root);
                            //UPGRADE_TODO: Class 'javax.xml.parsers.DocumentBuilder' was converted to 'System.Xml.XmlDocument' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaxxmlparsersDocumentBuilder'"
                            System.Xml.XmlDocument doc2 = new System.Xml.XmlDocument();
                            System.Xml.XmlElement root2 = doc2.CreateElement(s.GetType().FullName);
                            doc2.AppendChild(root2);
                            xp.encode(s, root2);
                            System.IO.StringWriter out2 = new System.IO.StringWriter();
                            System.Xml.XmlTextWriter ser = new System.Xml.XmlTextWriter(out2);

                            //System.Xml.XmlWriter ser = System.Xml.XmlWriter.Create(out2);
                            doc.WriteTo(ser);
                            if (out2.ToString().Equals(out_Renamed.ToString()))
                            {
                                System.Console.Out.WriteLine("Re-encode OK");
                            }
                            else
                            {
                                System.Console.Out.WriteLine("Warning: XML different after parse and re-encode: \r\n" + out2.ToString());
                            }
                        }
                    }
                }
            }
            catch (System.Exception e)
            {
                SupportClass.WriteStackTrace(e, Console.Error);
            }
        }
Пример #28
0
        public void SaveDocument(string filename)
        {
            if (Document.Editor.My.Computer.FileSystem.FileExists(filename))
            {
                Document.Editor.My.Computer.FileSystem.DeleteFile(filename);
            }
            System.IO.FileInfo   file = new System.IO.FileInfo(filename);
            System.IO.FileStream fs   = System.IO.File.Open(filename, System.IO.FileMode.OpenOrCreate);
            TextRange            tr   = new TextRange(Document.ContentStart, Document.ContentEnd);

            if (file.Extension.ToLower() == ".xamlpackage")
            {
                fs.Close();
                fs = null;
                TextRange            range   = null;
                System.IO.FileStream fStream = null;
                range   = new TextRange(Document.ContentStart, Document.ContentEnd);
                fStream = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                range.Save(fStream, DataFormats.XamlPackage, true);
                fStream.Close();
            }
            else if (file.Extension.ToLower() == ".xaml")
            {
                System.Windows.Markup.XamlWriter.Save(Document, fs);
                fs.Close();
                fs = null;
                System.Xml.XmlDocument xd = new System.Xml.XmlDocument();
                xd.LoadXml(Document.Editor.My.Computer.FileSystem.ReadAllText(filename));
                System.Text.StringBuilder sb  = new System.Text.StringBuilder();
                System.IO.StringWriter    sw  = new System.IO.StringWriter(sb);
                System.Xml.XmlTextWriter  xtw = null;
                try {
                    xtw            = new System.Xml.XmlTextWriter(sw);
                    xtw.Formatting = System.Xml.Formatting.Indented;
                    xd.WriteTo(xtw);
                } finally {
                    if (xtw != null)
                    {
                        xtw.Close();
                    }
                }
                string tex = sb.ToString();
                //Dim final As String
                //Try
                //    final = tex.Remove(tex.IndexOf("</FlowDocument>"), tex.Length)
                //Catch ex As Exception
                //End Try
                Document.Editor.My.Computer.FileSystem.WriteAllText(filename, tex, false);
            }
            else if (file.Extension.ToLower() == ".docx")
            {
                fs.Close();
                fs = null;
                FlowDocumenttoOpenXML converter = new FlowDocumenttoOpenXML();
                converter.Convert(Document, filename);
                converter.Close();
                //ElseIf file.Extension.ToLower = ".odt" Then
                //    fs.Close()
                //    fs = Nothing
                //    Dim converter As New FlowDocumenttoOpenDocument
                //    Dim opendoc As AODL.Document.TextDocuments.TextDocument = converter.Convert(Document)
                //    opendoc.SaveTo(filename)
            }
            else if (file.Extension.ToLower() == ".html" || file.Extension.ToLower() == ".htm")
            {
                fs.Close();
                fs = null;
                string s = System.Windows.Markup.XamlWriter.Save(Document);
                try {
                    Document.Editor.My.Computer.FileSystem.WriteAllText(filename, HTMLConverter.HtmlFromXamlConverter.ConvertXamlToHtml(s), false);
                } catch (Exception ex) {
                    MessageBoxDialog m = new MessageBoxDialog("Error saving document", "Error", null, null);
                    m.MessageImage.Source = new BitmapImage(new Uri("pack://application:,,,/Images/Common/error32.png"));
                    m.Owner = Document.Editor.My.Windows.MainWindow;
                    m.ShowDialog();
                }
            }
            else if (file.Extension.ToLower() == ".rtf")
            {
                tr.Save(fs, System.Windows.DataFormats.Rtf);
            }
            else
            {
                tr.Save(fs, System.Windows.DataFormats.Text);
            }
            if (fs != null)
            {
                fs.Close();
                fs = null;
            }
            //doctab.SetDocumentTitle(file.Name)
            DocumentName = filename;
            FileChanged  = false;
        }
Пример #29
0
        /// <summary>
        /// Generates a WMS 1.3.0 compliant response based on a <see cref="SharpMap.Map"/> and the current HttpRequest.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The Web Map Server implementation in SharpMap requires v1.3.0 compatible clients,
        /// and support the basic operations "GetCapabilities" and "GetMap"
        /// as required by the WMS v1.3.0 specification. SharpMap does not support the optional
        /// GetFeatureInfo operation for querying.
        /// </para>
        /// <example>
        /// Creating a WMS server in ASP.NET is very simple using the classes in the SharpMap.Web.Wms namespace.
        /// <code lang="C#">
        /// void page_load(object o, EventArgs e)
        /// {
        ///		//Get the path of this page
        ///		string url = (Request.Url.Query.Length>0?Request.Url.AbsoluteUri.Replace(Request.Url.Query,""):Request.Url.AbsoluteUri);
        ///		SharpMap.Web.Wms.Capabilities.WmsServiceDescription description =
        ///			new SharpMap.Web.Wms.Capabilities.WmsServiceDescription("Acme Corp. Map Server", url);
        ///
        ///		// The following service descriptions below are not strictly required by the WMS specification.
        ///
        ///		// Narrative description and keywords providing additional information
        ///		description.Abstract = "Map Server maintained by Acme Corporation. Contact: [email protected]. High-quality maps showing roadrunner nests and possible ambush locations.";
        ///		description.Keywords.Add("bird");
        ///		description.Keywords.Add("roadrunner");
        ///		description.Keywords.Add("ambush");
        ///
        ///		//Contact information
        ///		description.ContactInformation.PersonPrimary.Person = "John Doe";
        ///		description.ContactInformation.PersonPrimary.Organisation = "Acme Inc";
        ///		description.ContactInformation.Address.AddressType = "postal";
        ///		description.ContactInformation.Address.Country = "Neverland";
        ///		description.ContactInformation.VoiceTelephone = "1-800-WE DO MAPS";
        ///		//Impose WMS constraints
        ///		description.MaxWidth = 1000; //Set image request size width
        ///		description.MaxHeight = 500; //Set image request size height
        ///
        ///		//Call method that sets up the map
        ///		//We just add a dummy-size, since the wms requests will set the image-size
        ///		SharpMap.Map myMap = MapHelper.InitializeMap(new System.Drawing.Size(1,1));
        ///
        ///		//Parse the request and create a response
        ///		SharpMap.Web.Wms.WmsServer.ParseQueryString(myMap,description);
        /// }
        /// </code>
        /// </example>
        /// </remarks>
        /// <param name="map">Map to serve on WMS</param>
        /// <param name="description">Description of map service</param>
        public static void ParseQueryString(SharpMap.Map map, Capabilities.WmsServiceDescription description)
        {
            if (map == null)
            {
                throw (new ArgumentException("Map for WMS is null"));
            }
            if (map.Layers.Count == 0)
            {
                throw (new ArgumentException("Map doesn't contain any layers for WMS service"));
            }

            if (System.Web.HttpContext.Current == null)
            {
                throw (new ApplicationException("An attempt was made to access the WMS server outside a valid HttpContext"));
            }

            System.Web.HttpContext context = System.Web.HttpContext.Current;

            //IgnoreCase value should be set according to the VERSION parameter
            //v1.3.0 is case sensitive, but since it causes a lot of problems with several WMS clients, we ignore casing anyway.
            bool ignorecase = true;

            //Check for required parameters
            //Request parameter is mandatory
            if (context.Request.Params["REQUEST"] == null)
            {
                WmsException.ThrowWmsException("Required parameter REQUEST not specified"); return;
            }
            //Check if version is supported
            if (context.Request.Params["VERSION"] != null)
            {
                if (String.Compare(context.Request.Params["VERSION"], "1.3.0", ignorecase) != 0)
                {
                    WmsException.ThrowWmsException("Only version 1.3.0 supported"); return;
                }
            }
            else             //Version is mandatory if REQUEST!=GetCapabilities. Check if this is a capabilities request, since VERSION is null
            {
                if (String.Compare(context.Request.Params["REQUEST"], "GetCapabilities", ignorecase) != 0)
                {
                    WmsException.ThrowWmsException("VERSION parameter not supplied"); return;
                }
            }

            //If Capabilities was requested
            if (String.Compare(context.Request.Params["REQUEST"], "GetCapabilities", ignorecase) == 0)
            {
                //Service parameter is mandatory for GetCapabilities request
                if (context.Request.Params["SERVICE"] == null)
                {
                    WmsException.ThrowWmsException("Required parameter SERVICE not specified"); return;
                }

                if (String.Compare(context.Request.Params["SERVICE"], "WMS") != 0)
                {
                    WmsException.ThrowWmsException("Invalid service for GetCapabilities Request. Service parameter must be 'WMS'");
                }

                System.Xml.XmlDocument capabilities = Wms.Capabilities.GetCapabilities(map, description);
                context.Response.Clear();
                context.Response.ContentType = "text/xml";
                System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(context.Response.OutputStream);
                capabilities.WriteTo(writer);
                writer.Close();
                context.Response.End();
            }
            else if (String.Compare(context.Request.Params["REQUEST"], "GetMap", ignorecase) == 0)             //Map requested
            {
                //Check for required parameters
                if (context.Request.Params["LAYERS"] == null)
                {
                    WmsException.ThrowWmsException("Required parameter LAYERS not specified"); return;
                }
                if (context.Request.Params["STYLES"] == null)
                {
                    WmsException.ThrowWmsException("Required parameter STYLES not specified"); return;
                }
                if (context.Request.Params["CRS"] == null)
                {
                    WmsException.ThrowWmsException("Required parameter CRS not specified"); return;
                }
                else if (context.Request.Params["CRS"] != "EPSG:" + map.Layers[0].SRID.ToString())
                {
                    WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidCRS, "CRS not supported"); return;
                }
                if (context.Request.Params["BBOX"] == null)
                {
                    WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter BBOX not specified"); return;
                }
                if (context.Request.Params["WIDTH"] == null)
                {
                    WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter WIDTH not specified"); return;
                }
                if (context.Request.Params["HEIGHT"] == null)
                {
                    WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter HEIGHT not specified"); return;
                }
                if (context.Request.Params["FORMAT"] == null)
                {
                    WmsException.ThrowWmsException("Required parameter FORMAT not specified"); return;
                }

                //Set background color of map
                if (String.Compare(context.Request.Params["TRANSPARENT"], "TRUE", ignorecase) == 0)
                {
                    map.BackColor = System.Drawing.Color.Transparent;
                }
                else if (context.Request.Params["BGCOLOR"] != null)
                {
                    try { map.BackColor = System.Drawing.ColorTranslator.FromHtml(context.Request.Params["BGCOLOR"]); }
                    catch { WmsException.ThrowWmsException("Invalid parameter BGCOLOR"); return; };
                }
                else
                {
                    map.BackColor = System.Drawing.Color.White;
                }

                //Get the image format requested
                System.Drawing.Imaging.ImageCodecInfo imageEncoder = GetEncoderInfo(context.Request.Params["FORMAT"]);
                if (imageEncoder == null)
                {
                    WmsException.ThrowWmsException("Invalid MimeType specified in FORMAT parameter");
                    return;
                }

                //Parse map size
                int width  = 0;
                int height = 0;
                if (!int.TryParse(context.Request.Params["WIDTH"], out width))
                {
                    WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Invalid parameter WIDTH");
                    return;
                }
                else if (description.MaxWidth > 0 && width > description.MaxWidth)
                {
                    WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Parameter WIDTH too large");
                    return;
                }
                if (!int.TryParse(context.Request.Params["HEIGHT"], out height))
                {
                    WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Invalid parameter HEIGHT");
                    return;
                }
                else if (description.MaxHeight > 0 && height > description.MaxHeight)
                {
                    WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Parameter HEIGHT too large");
                    return;
                }
                map.Size = new System.Drawing.Size(width, height);

                IEnvelope bbox = ParseBBOX(context.Request.Params["bbox"]);
                if (bbox == null)
                {
                    WmsException.ThrowWmsException("Invalid parameter BBOX");
                    return;
                }
                map.PixelAspectRatio = ((double)width / (double)height) / (bbox.Width / bbox.Height);
                map.Center           = bbox.Centre;
                map.Zoom             = bbox.Width;

                //Set layers on/off
                if (!String.IsNullOrEmpty(context.Request.Params["LAYERS"]))                 //If LAYERS is empty, use default layer on/off settings
                {
                    string[] layers = context.Request.Params["LAYERS"].Split(new char[] { ',' });
                    if (description.LayerLimit > 0)
                    {
                        if (layers.Length == 0 && map.Layers.Count > description.LayerLimit ||
                            layers.Length > description.LayerLimit)
                        {
                            WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Too many layers requested");
                            return;
                        }
                    }
                    foreach (SharpMap.Layers.ILayer layer in map.Layers)
                    {
                        layer.Enabled = false;
                    }
                    foreach (string layer in layers)
                    {
                        //SharpMap.Layers.ILayer lay = map.Layers.Find(delegate(SharpMap.Layers.ILayer findlay) { return findlay.LayerName == layer; });
                        SharpMap.Layers.ILayer lay = null;
                        for (int i = 0; i < map.Layers.Count; i++)
                        {
                            if (String.Equals(map.Layers[i].Name, layer, StringComparison.InvariantCultureIgnoreCase))
                            {
                                lay = map.Layers[i];
                            }
                        }

                        if (lay == null)
                        {
                            WmsException.ThrowWmsException(WmsException.WmsExceptionCode.LayerNotDefined, "Unknown layer '" + layer + "'");
                            return;
                        }
                        else
                        {
                            lay.Enabled = true;
                        }
                    }
                }

                //Render map
                System.Drawing.Image img = map.Render();

                //Png can't stream directy. Going through a memorystream instead
                System.IO.MemoryStream MS = new System.IO.MemoryStream();
                img.Save(MS, imageEncoder, null);
                img.Dispose();
                byte[] buffer = MS.ToArray();
                context.Response.Clear();
                context.Response.ContentType = imageEncoder.MimeType;
                context.Response.OutputStream.Write(buffer, 0, buffer.Length);
                context.Response.End();
            }
            else
            {
                WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Invalid request");
            }
        }
Пример #30
0
        public static void Main(System.String[] args)
        {
            if (args.Length != 1)
            {
                System.Console.Out.WriteLine("Usage: XMLParser pipe_encoded_file");
                System.Environment.Exit(1);
            }

            //read and parse message from file
            try
            {
                PipeParser parser = new PipeParser();
                System.IO.FileInfo messageFile = new System.IO.FileInfo(args[0]);
                long fileLength = SupportClass.FileLength(messageFile);
                System.IO.StreamReader r = new System.IO.StreamReader(messageFile.FullName, System.Text.Encoding.Default);
                char[] cbuf = new char[(int)fileLength];
                System.Console.Out.WriteLine("Reading message file ... " + r.Read((System.Char[])cbuf, 0, cbuf.Length) + " of " + fileLength + " chars");
                r.Close();
                System.String messString = System.Convert.ToString(cbuf);
                IMessage mess = parser.Parse(messString);
                System.Console.Out.WriteLine("Got message of type " + mess.GetType().FullName);

                NHapi.Base.Parser.XMLParser xp = new AnonymousClassXMLParser();

                //loop through segment children of message, encode, print to console
                System.String[] structNames = mess.Names;
                for (int i = 0; i < structNames.Length; i++)
                {
                    IStructure[] reps = mess.GetAll(structNames[i]);
                    for (int j = 0; j < reps.Length; j++)
                    {
                        if (typeof(ISegment).IsAssignableFrom(reps[j].GetType()))
                        {
                            //ignore groups
                            System.Xml.XmlDocument docBuilder = new System.Xml.XmlDocument();
                            System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); //new doc for each segment
                            System.Xml.XmlElement root = doc.CreateElement(reps[j].GetType().FullName);
                            doc.AppendChild(root);
                            xp.Encode((ISegment)reps[j], root);
                            System.IO.StringWriter out_Renamed = new System.IO.StringWriter();
                            System.Console.Out.WriteLine("Segment " + reps[j].GetType().FullName + ": \r\n" + doc.OuterXml);

                            System.Type[] segmentConstructTypes = new System.Type[] { typeof(IMessage) };
                            System.Object[] segmentConstructArgs = new System.Object[] { null };
                            ISegment s = (ISegment)reps[j].GetType().GetConstructor(segmentConstructTypes).Invoke(segmentConstructArgs);
                            xp.Parse(s, root);
                            System.Xml.XmlDocument doc2 = new System.Xml.XmlDocument();
                            System.Xml.XmlElement root2 = doc2.CreateElement(s.GetType().FullName);
                            doc2.AppendChild(root2);
                            xp.Encode(s, root2);
                            System.IO.StringWriter out2 = new System.IO.StringWriter();
                            System.Xml.XmlWriter ser = System.Xml.XmlWriter.Create(out2);
                            doc.WriteTo(ser);
                            if (out2.ToString().Equals(out_Renamed.ToString()))
                            {
                                System.Console.Out.WriteLine("Re-encode OK");
                            }
                            else
                            {
                                System.Console.Out.WriteLine("Warning: XML different after parse and re-encode: \r\n" + out2.ToString());
                            }
                        }
                    }
                }
            }
            catch (System.Exception e)
            {
                SupportClass.WriteStackTrace(e, Console.Error);
            }
        }