public void Close() { if (_writer == null) { throw new InvalidOperationException("Already closed."); } _writer.Close(); _writer = null; }
protected internal void CloseXmlFile() { try { // write closing elements and close XMLWriter _xw.WriteEndElement(); _xw.WriteEndDocument(); } finally { _xw.Flush(); _xw.Close(); } }
// *************************************************************************** // Beendet an zu schreiben public static void EndXML(XmlWriter writer) { writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); writer.Close(); }
/// <summary> /// 序列化对象为xml字符串 /// </summary> /// <param name="obj">要序列化的对象</param> /// <returns>xml格式字符串</returns> public static string Serialize(this object obj) { if (obj == null) { return(""); } Type type = obj.GetType(); if (type.IsSerializable) { try { System.Text.StringBuilder sb = new System.Text.StringBuilder(); System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(type); XmlWriterSettings xset = new XmlWriterSettings(); xset.CloseOutput = true; xset.Encoding = Encoding.UTF8; xset.Indent = true; xset.CheckCharacters = false; System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(sb, xset); xs.Serialize(xw, obj); xw.Flush(); xw.Close(); return(sb.ToString()); } catch { return(""); } } else { return(""); } }
/// <summary> /// Writes a GML feature into a generic <c>Stream</c>, such a <c>FileStream</c> or other streams. /// </summary> /// <param name="geometry"></param> /// <param name="stream"></param> public void Write(IGeometry geometry, Stream stream) { XmlTextWriter writer; #if SILVERLIGHT XmlWriterSettings settings = null; settings = new XmlWriterSettings() { NamespaceHandling = NamespaceHandling.OmitDuplicates, Indent = true }; writer = (XmlTextWriter)XmlWriter.Create(stream, settings); #else writer = new XmlTextWriter(stream, null) { Namespaces = true }; #endif writer.WriteStartElement(GMLElements.gmlPrefix, "GML", GMLElements.gmlNS); #if !SILVERLIGHT //writer.Formatting = Formatting.Indented; #endif Write(geometry, writer); writer.WriteEndElement(); writer.Close(); }
public static void Write(ProjectManager projects, string path, IdTable ids) { foreach ( var p in projects ) { if ( p == Project.Empty ) continue; var f = new XmlWriter(path + p.Name + ".xml"); f.Begin(p, ids); f.Begin("Assignments"); var faclist = new FlatAssignmentCollection[p.Assignments.Count]; lock ( p.Assignments ) p.Assignments.CopyTo(faclist, 0); foreach ( var fac in faclist ) { f.Begin(fac, ids); var falist = new FlatAssignment[fac.Count]; lock ( fac ) fac.CopyTo(falist, 0); foreach ( var fa in falist ) f.Write(fa, ids); f.End(fac); } f.End("Assignments"); f.Begin("Costs"); var costlist = new Cost[p.Costs.Count]; lock ( p.Costs ) p.Costs.CopyTo(costlist, 0); foreach ( var c in costlist ) { f.Begin(c, ids); f.Begin("Options"); var optionslist = new CostOptions[c.Options.Count]; lock ( c.Options ) c.Options.CopyTo(optionslist, 0); foreach ( var o in optionslist ) f.Write(o, ids); f.End("Options"); f.End(c); } f.End("Costs"); f.End(p); f.Close(); } }
public static void SaveRecentExperimentListToXML(RecentExperimentList pList, string pFilepath) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.CloseOutput = true; settings.CheckCharacters = true; // Create file using (System.Xml.XmlWriter writer = XmlWriter.Create(pFilepath, settings)) { writer.WriteStartDocument(); writer.WriteStartElement("RecentExperiments"); foreach (var item in pList) { writer.WriteStartElement("RecentExperimentItem"); writer.WriteAttributeString("FullPath", item.FullPath); //writer.WriteAttributeString("Filename", item.Filename); writer.WriteAttributeString("LastAccessTime", item.LastAccessTime.ToString()); writer.WriteEndElement(); // RecentExperimentItem } writer.WriteEndElement(); // RecentExperiments writer.WriteEndDocument(); writer.Close(); } }
//---------------------------------------------------------------------------------------------------- public ApiResponse <T> WriteXml <T>(string fileName, T obj) { var response = new ApiResponse <T>(); string fileSysName = fileName; FileStream fs = null; System.Xml.XmlWriter writer = null; //--------------------------------------------------------------------- try { System.IO.File.Delete(fileSysName); fs = new FileStream(fileSysName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write); writer = XmlWriter.Create(fs); var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T)); serializer.Serialize(writer, obj); } catch (Exception e) { response.Status.SetError(-1, "Xml error writting/serializing file: " + fileSysName, e); } finally { writer?.Close(); fs?.Close(); } return(response); }
public void Write() { XmlWriterSettings xmlSetting = new XmlWriterSettings(); xmlSetting.CloseOutput = true; xmlSetting.Encoding = Encoding.UTF8; xmlSetting.Indent = true; xmlSetting.NewLineChars = "\r\n"; wr = XmlWriter.Create(GeneralConfig.AppDataPath + "Questionaries\\" + questionary.Category + ".xml", xmlSetting); wr.WriteStartDocument(); wr.WriteStartElement("Questionary"); wr.WriteStartAttribute("category"); wr.WriteValue(questionary.Category); wr.WriteEndAttribute(); wr.WriteStartAttribute("created"); wr.WriteValue(questionary.Created.ToString()); wr.WriteEndAttribute(); wr.WriteStartAttribute("updated"); wr.WriteValue(questionary.Updated.ToString()); wr.WriteEndAttribute(); wr.WriteStartAttribute("template"); wr.WriteValue(questionary.TemplateId); wr.WriteEndAttribute(); wr.WriteStartElement("Questions"); WriteQuestions(); wr.WriteEndElement(); wr.WriteEndElement(); wr.WriteEndDocument(); wr.Close(); }
// ---------------------------------------------------------- public void Minimize(Options aOptions, Def aDef) { // reader _reader = new XmlDocument(); _reader.Load(aOptions.inFile); // writter with write settings var writterSettings = new XmlWriterSettings(); if (aOptions.prettyPrint) { writterSettings.Indent = true; writterSettings.IndentChars = " "; } _writer = XmlWriter.Create(aOptions.outFile, writterSettings); _writer.WriteStartDocument(); ProcessElement(_reader.DocumentElement, aDef); _writer.WriteEndDocument(); _writer.Close(); // print warnings foreach(string warning in _warnings) { Console.WriteLine(warning); } }
// Use this for initialization void Start() { if (System.IO.File.Exists(configPath) == false) { Xml.XmlWriterSettings settings = new Xml.XmlWriterSettings(); settings.Indent = true; string levelsPath = "Assets/scenes/"; string[] loaderPath = System.IO.Directory.GetFiles(levelsPath); ConfigWriter cfgFile = ConfigWriter.Create(configPath, settings); cfgFile.WriteStartDocument(); cfgFile.WriteStartElement("Config"); cfgFile.WriteStartElement("Levels"); cfgFile.WriteAttributeString("LevelsPath", levelsPath.ToString()); foreach (string file in loaderPath) { if (file.EndsWith(".meta") == false) { cfgFile.WriteElementString("Map", file.Remove(0, levelsPath.Length).Remove(file.Length - (levelsPath.Length + 6)).ToString()); } } cfgFile.WriteEndElement(); cfgFile.WriteEndElement(); cfgFile.WriteEndDocument(); cfgFile.Flush(); cfgFile.Close(); } }
public void Write(XmlWriter writer, TestRunType testRun) { try { _serializer.Serialize(writer, testRun, new XmlSerializerNamespaces(new XmlQualifiedName[] { new XmlQualifiedName(string.Empty, "http://microsoft.com/schemas/VisualStudio/TeamTest/2010") })); } catch (Exception) { throw; } finally { if (writer != null) { try { writer.Close(); } catch { } } } }
private void SaveGameDescriptor(Stream stream) { ISerializationService service = Services.GetService <ISerializationService>(); if (service != null) { XmlWriterSettings settings = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true, IndentChars = " ", NewLineChars = "\r\n", NewLineHandling = NewLineHandling.Replace, OmitXmlDeclaration = true }; using (System.Xml.XmlWriter xmlWriter = System.Xml.XmlWriter.Create(stream, settings)) { xmlWriter.WriteStartDocument(); XmlSerializer xmlSerializer = service.GetXmlSerializer <GameSaveDescriptor>(); xmlSerializer.Serialize(xmlWriter, this.GameSaveDescriptor); xmlWriter.WriteEndDocument(); xmlWriter.Flush(); xmlWriter.Close(); } } }
private void Click_Save(object sender, RoutedEventArgs e) { System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(Environment.CurrentDirectory + @"\" + FileName); writer.WriteStartDocument(); if (cvs.Children.Count != 0) { writer.WriteStartElement("Icons"); foreach (var i in cvs.Children) { var im = (Image)i; writer.WriteStartElement("Icon"); writer.WriteElementString("Source", im.Source + ""); writer.WriteElementString("Width", im.Width + ""); writer.WriteElementString("Height", im.Height + ""); writer.WriteElementString("Left", im.GetValue(Canvas.LeftProperty) + ""); writer.WriteElementString("Top", im.GetValue(Canvas.TopProperty) + ""); writer.WriteEndElement(); writer.Flush(); } writer.WriteEndElement(); writer.WriteEndDocument(); } else { writer.WriteStartElement("Null"); writer.WriteEndElement(); writer.WriteEndDocument(); } writer.Close(); MessageBox.Show("Позиции иконок сохранены!", "Perfect", MessageBoxButton.OK, MessageBoxImage.Information); }
protected override void DoClose() { writer.Flush(); if (!Settings.KeepOpen) { writer.Close(); } }
public void DbmlToFile(Database db, string filename, Encoding encoding) { var settings = new XmlWriterSettings {Indent = true, Encoding = encoding}; writer = XmlWriter.Create(filename, settings); VisitDatabase(db); writer.Flush(); writer.Close(); }
public static string Beautify(System.Xml.XmlDocument doc) { string strRetValue = null; System.Text.Encoding enc = System.Text.Encoding.UTF8; // enc = new System.Text.UTF8Encoding(false); System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings(); xmlWriterSettings.Encoding = enc; xmlWriterSettings.Indent = true; xmlWriterSettings.IndentChars = " "; xmlWriterSettings.NewLineChars = "\r\n"; xmlWriterSettings.NewLineOnAttributes = true; xmlWriterSettings.NewLineHandling = System.Xml.NewLineHandling.Replace; //xmlWriterSettings.OmitXmlDeclaration = true; xmlWriterSettings.ConformanceLevel = System.Xml.ConformanceLevel.Document; using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(ms, xmlWriterSettings)) { doc.Save(writer); writer.Flush(); ms.Flush(); writer.Close(); } // End Using writer ms.Position = 0; using (System.IO.StreamReader sr = new System.IO.StreamReader(ms, enc)) { // Extract the text from the StreamReader. strRetValue = sr.ReadToEnd(); sr.Close(); } // End Using sr ms.Close(); } // End Using ms /* * System.Text.StringBuilder sb = new System.Text.StringBuilder(); // Always yields UTF-16, no matter the set encoding * using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sb, settings)) * { * doc.Save(writer); * writer.Close(); * } // End Using writer * strRetValue = sb.ToString(); * sb.Length = 0; * sb = null; */ xmlWriterSettings = null; return(strRetValue); } // End Function Beautify
private XDocument Serialize <T>(T source) { XDocument target = new XDocument(); XmlSerializer s = new XmlSerializer(typeof(T)); System.Xml.XmlWriter writer = target.CreateWriter(); s.Serialize(writer, source); writer.Close(); return(target); }
public static void SerializeParams <T>(XDocument doc, List <T> paramList) { System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(paramList.GetType()); System.Xml.XmlWriter writer = doc.CreateWriter(); serializer.Serialize(writer, paramList); writer.Close(); }
/// <summary> /// Finishes off writing the debug XML. /// </summary> protected void WriteDebugXmlFinish() { if (_xmlDebugging) { _debugXmlWriter.WriteRaw(Environment.NewLine); _debugXmlWriter.WriteEndElement(); _debugXmlWriter.WriteEndDocument(); _debugXmlWriter.Flush(); _debugXmlWriter.Close(); } }
private void btnSave_Click(object sender, EventArgs e) { string OptionFile = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\SmartWeb\SmartWebOption.xml"; try { //Directory가 존재 하지 않은 경우 Directory를 생성 한다. if (System.IO.Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\SmartWeb") == false) { System.IO.Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\SmartWeb"); } System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(OptionFile, settings); writer.WriteStartElement("configuration"); writer.WriteStartElement("appSettings"); writer.WriteStartElement("add"); writer.WriteAttributeString("key", "Language"); writer.WriteAttributeString("value", Convert.ToString(cboLanguage.SelectedIndex + 1)); writer.WriteEndElement(); writer.WriteStartElement("add"); writer.WriteAttributeString("key", "AutoLogOutTime"); if (txtAutoLotoutTime.Text.Trim() == "") { writer.WriteAttributeString("value", "0"); } else { writer.WriteAttributeString("value", txtAutoLotoutTime.Text); } writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndElement(); writer.Flush(); writer.Close(); // 2020-01-31-김미경 : 언어 변경에 따른 메시지 출력. //CmnFunction.ShowMsgBox(RptMessages.GetMessage("STD035", GlobalVariable.gcLanguage)); } catch (Exception ex) { MessageBox.Show(ex.Message); } GlobalVariable.gcLanguage = Convert.ToChar(cboLanguage.SelectedIndex + 1); GlobalVariable.giLogOutTime = txtAutoLotoutTime.Text.Trim() == "" ? 0 : Convert.ToInt32(txtAutoLotoutTime.Text); this.Close(); }
private void SaveValues(Excel.Worksheet thisSheet, Boolean thisYN, string propname) { System.Text.StringBuilder strvals = new System.Text.StringBuilder(); System.Xml.XmlWriter xvals = System.Xml.XmlWriter.Create(strvals); xvals.WriteStartElement(propname); xvals.WriteAttributeString("Checked", thisYN.ToString()); xvals.WriteEndElement(); xvals.Close(); Utilities.ExcelHelpers.addWorksheetCustomProperty(thisSheet, propname, strvals.ToString()); }
public void Write_EDC(string save_file_path) { // ----------- Define xml header ------------- stringwriterUTF8 sw = new stringwriterUTF8(); System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; settings.NewLineChars = "\r\n"; settings.Encoding = Encoding.UTF8; settings.IndentChars = " "; // next line indent 2 space settings.OmitXmlDeclaration = false; // write header xml version and encode XmlSerializerNamespaces names = new XmlSerializerNamespaces(); names.Add(string.Empty, string.Empty); System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sw, settings); XmlSerializer EDC_serialize = new XmlSerializer(this.GetType()); // typeof(EDC_Report)); EDC_serialize.Serialize(writer, this, names); writer.Close(); if (!Directory.Exists(Path.GetDirectoryName(save_file_path))) { Directory.CreateDirectory(Path.GetDirectoryName(save_file_path)); } try { string temp_name = save_file_path + ".tmp"; using (FileStream fs = System.IO.File.Open(temp_name, FileMode.Create)) { using (StreamWriter EDCWriter = new StreamWriter(fs, Encoding.UTF8)) { EDCWriter.Write(sw.ToString()); EDCWriter.Flush(); fs.Flush(); } } if (System.IO.File.Exists(save_file_path)) { System.IO.File.Delete(save_file_path); } while (System.IO.File.Exists(save_file_path)) { Thread.Sleep(1); } System.IO.File.Move(temp_name, save_file_path); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
// Use this for initialization void Start() { if (System.IO.File.Exists(configPath) == false) { Xml.XmlWriterSettings settings = new Xml.XmlWriterSettings(); settings.Indent = true; string levelsPath = "Assets/scenes/"; string[] loaderPath = System.IO.Directory.GetFiles(levelsPath); ConfigWriter cfgFile = ConfigWriter.Create(configPath, settings); cfgFile.WriteStartElement("Config"); cfgFile.WriteStartElement("Levels"); cfgFile.WriteAttributeString("LevelsPath", levelsPath.ToString()); foreach (string file in loaderPath) { if (file.EndsWith(".meta") == false) { cfgFile.WriteElementString("Map", file.Remove(0, levelsPath.Length).Remove(file.Length - (levelsPath.Length + 6)).ToString()); } } cfgFile.WriteEndElement(); cfgFile.WriteEndElement(); cfgFile.WriteEndDocument(); cfgFile.Flush(); cfgFile.Close(); } else { if (colorsDictionary.Count > 0) { return; } //load colors ConfigReader cfgFile = new ConfigReader(); cfgFile.Load(configPath); Xml.XmlNodeList colorNodes = cfgFile.GetElementsByTagName("Color"); foreach (Xml.XmlElement nodes in colorNodes) { colorsDictionary.Add(nodes.GetAttribute("colorName"), new string[] { nodes.GetAttribute("one"), nodes.GetAttribute("two"), nodes.GetAttribute("three"), nodes.GetAttribute("four") }); } } //Debug.Log ( "config says hello"); }
/// <summary> /// Logs the request or response /// </summary> /// <param name="buffer"></param> /// <param name="message"></param> private void LogRequestResponse(MessageBuffer buffer, string message) { Message msg = buffer.CreateMessage(); StringBuilder sb = new StringBuilder(); using (System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(sb)) { msg.WriteMessage(xw); xw.Close(); } _logger.Debug(message, sb.ToString()); }
public void SaveAs(string fileName, Encoding encoding) { System.Xml.XmlWriterSettings setting = new System.Xml.XmlWriterSettings(); setting.Encoding = encoding; setting.Indent = true; setting.IndentChars = " "; setting.NewLineChars = "\r\n"; System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(fileName, setting); this.XmlDoc.WriteTo(writer); writer.Close(); }
public PhpValue flush(bool empty = true) { if (!CheckedCall(_writer.Flush)) { return(false); } PhpValue result; if (_memoryStream != null) { if (empty) { // TODO: Handle situation with writing after flushing _writer.Close(); } result = _memoryStream.ToArray(); } else { try { result = _uriPhpStream.RawStream.Position; } catch (NotSupportedException) { PhpException.Throw(PhpError.Warning, Resources.XmlWritterNumberOfBytesUnsupported); result = 0; } if (empty) { // TODO: Handle situation with writing after flushing _writer.Close(); } } return(result); }
private void OnChanged(object sender, FileSystemEventArgs e) { Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType); Thread.Sleep(500); Byte[] bytes = File.ReadAllBytes(e.FullPath); file1 = Convert.ToBase64String(bytes); string date_year = DateTime.Now.ToString("yyyy"); string date_month = DateTime.Now.ToString("MM"); string date_day = DateTime.Now.ToString("dd"); string current_date = date_year + date_month + date_day + "-"; StringBuilder sb = new StringBuilder(); System.Xml.XmlWriter xw = XmlWriter.Create(sb); xw.WriteStartElement("date"); xw.WriteAttributeString("xml_date", "yyyy-mm-dd", null, current_date); xw.WriteStartElement("log"); xw.WriteValue(file1); xw.WriteEndElement(); xw.WriteEndElement(); xw.Close(); try { // wrstream.WriteLine(file1); wrstream.WriteLine(sb.ToString()); wrstream.Flush(); } catch (Exception ecp) { ecp.GetBaseException(); } try { //ns.Flush(); wrstream.Flush(); //wrstream.Close(); //если я закрываю поток происходит передача данных и клиент теряет связь //Я бы не говорил что это очень плохо } catch (Exception ex2) { ex2.GetBaseException(); } }
/// <summary> /// 序列化目标对象为Xml /// </summary> /// <param name="targetObject"></param> /// <returns></returns> public string XmlSerialize(object targetObject) { System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(targetObject.GetType()); StringBuilder sb = new StringBuilder(); System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(sb, new XmlWriterSettings() { Encoding = Encoding.UTF8 }); serializer.Serialize(xw, targetObject); xw.Flush(); xw.Close(); return(sb.ToString()); }
public void SaveXml(CompilationUnit cu) { try { this.cu = cu; is_assembly = cu.SyntaxTree is SyntaxTree.program_module || Compiler.is_dll(cu.SyntaxTree); XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; settings.Indent = true; xtw = XmlTextWriter.Create(Path.ChangeExtension(cu.UnitName, ".xml"), settings); unit_name = Path.GetFileNameWithoutExtension(cu.UnitName); xtw.WriteStartDocument(); xtw.WriteStartElement("doc"); if (is_assembly) { xtw.WriteStartElement("assembly"); xtw.WriteStartElement("name"); xtw.WriteString(Path.GetFileNameWithoutExtension(cu.UnitName)); xtw.WriteEndElement(); xtw.WriteEndElement(); } else { xtw.WriteStartElement("unit"); xtw.WriteStartAttribute("name"); //xtw.WriteString((cu.SemanticTree as common_unit_node).unit_name); xtw.WriteString(Path.GetFileNameWithoutExtension(cu.UnitName)); xtw.WriteEndAttribute(); xtw.WriteString(cu.SemanticTree.documentation); xtw.WriteEndElement(); } SaveMembers(); xtw.WriteEndElement(); xtw.Flush(); } catch (Exception e) { } try { if (xtw != null) xtw.Close(); } catch { } }
static void Main(string[] args) { //Write XML 1.1 file StringBuilder sb = new StringBuilder(); XmlWriterSettings xws = new XmlWriterSettings(); xws.Encoding = Encoding.UTF8; xws.Indent = true; //Disable character checking xws.CheckCharacters = false; System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(sb, xws); //write your own header xw.WriteProcessingInstruction("xml", "version='1.1'"); XElement doc = new XElement("root"); doc.Add( new XElement("test", new XAttribute("val", "\x03"))); //use WriteTo instead of Save doc.WriteTo(xw); xw.Close(); //Print XML contents to console Console.WriteLine(sb.ToString()); //Read XML 1.1 file TextReader tr = new StringReader(sb.ToString()); tr.ReadLine(); //skip Version number '1.1' is invalid. exception XmlReaderSettings xrs = new XmlReaderSettings(); xrs.CheckCharacters = false; XmlReader xr = XmlReader.Create(tr, xrs); var xmldoc = XElement.Load(xr); foreach (var e in xmldoc.Elements()) { Console.Write("Element: {0}", e.Name); foreach (var a in e.Attributes()) { Console.Write(" Attribute: {0}={1}", a.Name, a.Value); } Console.WriteLine(); } }
public virtual string Serialize() { System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(); System.Xml.XmlWriter xmlWriter = System.Xml.XmlWriter.Create(stringBuilder, Microsoft.Rapid.Client.Core.RapidClientSchemas.XmlFragmentWriterSettings); try { System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Collated)); serializer.Serialize(xmlWriter, this); return(stringBuilder.ToString()); } finally { xmlWriter.Close(); stringBuilder = null; xmlWriter = null; } }
/// <summary> /// xml序列化 /// </summary> /// <param name="obj">obj类</param> /// <returns>string字符串</returns> public static string _XMLSerialize(object obj) { XmlSerializer xs = new XmlSerializer(obj.GetType()); StringBuilder strBuidler = new StringBuilder(); XmlWriterSettings setting = new XmlWriterSettings(); setting.OmitXmlDeclaration = true;//去掉xml版本声明 System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(strBuidler, setting); XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces(); xmlns.Add(string.Empty, string.Empty); xs.Serialize(xw, obj, xmlns); xw.Close(); return(strBuidler.ToString()); }
public void generate(CommonTree ast, XmlWriter writer) { try { writer.WriteStartDocument(); writeXMLNode(ast, writer); writer.WriteEndDocument(); writer.Close(); } catch (Exception e) { Console.WriteLine("Error while translating AST: " + e.Message); } }
/// <summary> /// Saves links to an XML file. /// </summary> /// <param name="filepath">The path of the XML file.</param> private static void SaveLinksToXML(string filepath, List <WebsiteLink> pVideos, List <WebsiteLink> pLinks) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.CloseOutput = true; settings.CheckCharacters = true; // Create file using (System.Xml.XmlWriter writer = XmlWriter.Create(filepath, settings)) { writer.WriteStartDocument(); writer.WriteStartElement("OnlineContent"); writer.WriteStartElement("Videos"); if (pVideos != null) { foreach (var item in pVideos) { writer.WriteStartElement("VideoItem"); writer.WriteAttributeString("Title", item.Title); writer.WriteAttributeString("Description", item.Description); writer.WriteAttributeString("URL", item.LinkURL); writer.WriteEndElement(); // VideoItem } } writer.WriteEndElement(); // Videos writer.WriteStartElement("Links"); if (pLinks != null) { foreach (var item in pLinks) { writer.WriteStartElement("LinkItem"); writer.WriteAttributeString("Title", item.Title); writer.WriteAttributeString("Description", item.Description); writer.WriteAttributeString("URL", item.LinkURL); writer.WriteEndElement(); // LinkItem } } writer.WriteEndElement(); // Links writer.WriteEndElement(); // StartPage writer.WriteEndDocument(); writer.Close(); } }
public static void Write(LesseeManager lessees, string filepath, IdTable ids) { var f = new XmlWriter(filepath); f.Begin("Lessees"); var list = new Lessee[lessees.Count]; lock ( lessees ) lessees.CopyTo(list, 0); foreach ( var l in list ) { f.Begin(l, ids); f.Begin("Payments"); var paymentlist = new AdvancePayment[l.Payments.Count]; lock ( l.Payments ) l.Payments.CopyTo(paymentlist, 0); foreach ( var p in paymentlist ) f.Write(p, ids); f.End("Payments"); f.End(l); } f.End("Lessees"); f.Close(); }
public static void Write(PropertyManager properties, string filepath, IdTable ids) { var f = new XmlWriter(filepath); f.Begin("Properties"); var list = new Olivia2.Model.Property[properties.Count]; lock ( properties ) properties.CopyTo(list, 0); foreach (var p in list) { f.Begin(p, ids); f.Begin("Flats"); var flatlist = new Flat[p.Flats.Count]; lock ( p.Flats ) p.Flats.CopyTo(flatlist, 0); foreach ( var flat in flatlist ) f.Write(flat, ids); f.End("Flats"); f.End(p); } f.End("Properties"); f.Close(); }
public void WriteLevel(XmlWriter writer) { writer.WriteStartDocument(); foreach (Level level in this.lstLevel.Items) level.ToXML(writer); writer.WriteStartElement("physics"); foreach (Item p in this.lstPhysics.Items) p.ToXML(writer); writer.WriteEndElement(); writer.WriteStartElement("actors"); foreach (Item p in this.lstActors.Items) p.ToXML(writer); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); }
public string DbmlToString(Database db, Encoding encoding) { string str; using (var stream = new MemoryStream()) using (var streamWriter = new StreamWriter(stream, encoding)) { var settings = new XmlWriterSettings {Indent = true, Encoding = encoding}; writer = XmlWriter.Create(streamWriter, settings); VisitDatabase(db); writer.Flush(); writer.Close(); using (var reader = new StreamReader(stream, encoding)) { stream.Position = 0L; str = reader.ReadToEnd(); } } return str; }
public static string Serialize(Collated input) { if ((input == null)) { throw new System.ArgumentNullException("input"); } System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(); System.Xml.XmlWriter xmlWriter = System.Xml.XmlWriter.Create(stringBuilder, Microsoft.Rapid.Client.Core.RapidClientSchemas.XmlFragmentWriterSettings); try { System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Collated)); serializer.Serialize(xmlWriter, input); return(stringBuilder.ToString()); } finally { xmlWriter.Close(); stringBuilder = null; xmlWriter = null; } }
private void Serialize <T>(T obj, string sConfigFilePath) { try { System.Xml.Serialization.XmlSerializer XmlBuddy = new System.Xml.Serialization.XmlSerializer(typeof(T)); System.Xml.XmlWriterSettings MySettings = new System.Xml.XmlWriterSettings(); MySettings.Indent = true; MySettings.CloseOutput = true; MySettings.OmitXmlDeclaration = true; System.Xml.XmlWriter MyWriter = System.Xml.XmlWriter.Create(sConfigFilePath, MySettings); XmlBuddy.Serialize(MyWriter, obj); MyWriter.Flush(); MyWriter.Close(); } catch (Exception ex) { account.Log(new ErrorTextInformation(ex.Message + ex.StackTrace), 0); } }
private void SaveValues(Excel.Worksheet thisSheet, CheckedListBox thisList, string propname) { if (thisList.CheckedItems.Count == 0) { return; } System.Text.StringBuilder strvals = new System.Text.StringBuilder(); System.Xml.XmlWriter xvals = System.Xml.XmlWriter.Create(strvals); xvals.WriteStartElement(propname); foreach (var s in thisList.CheckedItems) { xvals.WriteElementString("Item", thisList.GetItemText(s)); } xvals.WriteEndElement(); xvals.Close(); Utilities.ExcelHelpers.addWorksheetCustomProperty(thisSheet, propname, strvals.ToString()); }
public void CreateXMLDoc(String filePath) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = "\t"; settings.NewLineChars = "\n"; //settings.OmitXmlDeclaration = true; // "<?xml version="1.0" encoding="utf-8"?>" //writer = new XmlTextWriter(filePath, Encoding.Unicode); writer = XmlWriter.Create(filePath,settings); writer.WriteStartDocument(); writer.WriteStartElement("map"); // //writer.WriteStartElement("name"); //Writing name of the mode writer.WriteStartElement("mode"); writer.WriteAttributeString("name", mode.mode.ToString()); //writer.WriteAttributeString("name", mode.getName()); writer.WriteEndElement(); //Writing map structure block writer.WriteStartElement("structure"); // //MapObject[][] tempMapObject = map.GetInternalForm(); foreach (MapObject[] m in map.MapInstance) { for (int j = 0; j < m.Length; j++) { writer.WriteStartElement("element"); writer.WriteAttributeString("x", m[j].X.ToString()); writer.WriteAttributeString("y", m[j].Y.ToString()); writer.WriteAttributeString("type", m[j].Type.ToString()); writer.WriteEndElement(); } } writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); }
private void WriteClientBinXml(XmlWriter writer) { // Setup initial conditions. writer.WriteStartDocument(); writer.WriteStartElement("ClientBin"); // Enumerate the collection of XAP files. var folder = new DirectoryInfo(Server.MapPath("ClientBin")); foreach (var file in folder.GetFiles("*.xap")) { var kb = Math.Round(Decimal.Divide(file.Length, 1000), 2); writer.WriteStartElement("File"); writer.WriteAttributeString("Extension", "xap"); writer.WriteAttributeString("Kb", kb.ToString()); writer.WriteString(file.Name.TrimEnd(".xap".ToCharArray())); writer.WriteEndElement(); // File. } // Finish up. writer.WriteEndElement(); // ClientBin. writer.WriteEndDocument(); writer.Close(); }
private void CloseWriter(XmlWriter xmlWriter) { xmlWriter.WriteEndElement(); // APML xmlWriter.WriteEndDocument(); xmlWriter.Close(); }
private void btnConvert_Click(object sender, EventArgs e) { scale = float.Parse(txtScale.Text, NumberFormatInfo); worldsize = float.Parse(txtWorldSize.Text, NumberFormatInfo); x = float.Parse(txtX.Text, NumberFormatInfo); z = float.Parse(txtZ.Text, NumberFormatInfo); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = " "; Log("Creating nodes.xml"); writer = XmlWriter.Create("nodes.xml", settings); // write writer.WriteStartDocument(); writer.WriteStartElement("nodes"); writer.WriteAttributeString("count", "0"); // process grass Log("Reading " + txtGrassFilename.Text); reader = XmlReader.Create(txtGrassFilename.Text); int grassnodes = ConvertGrass(reader, writer); reader.Close(); Log("Exported " + grassnodes + " grassnodes."); // process trees Log("Reading " + txtTreeFilename.Text); reader = XmlReader.Create(txtTreeFilename.Text); int treenodes = ConvertTrees(reader, writer); reader.Close(); Log("Exported " + treenodes + " treenodes."); // end writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); int sum = grassnodes + treenodes; Log("Sum: " + sum.ToString() + " nodes."); // replace count Log("Replacing count in nodes.xml"); string s = System.IO.File.ReadAllText("nodes.xml"); System.IO.File.WriteAllText("nodes.xml", s.Replace("count=\"0\"", "count=\"" + sum + "\"")); Log("Export finished."); }
/// <summary> /// Method which generates the Sparql Query Results XML Format serialization of the Result Set /// </summary> /// <returns></returns> protected void GenerateOutput(SparqlResultSet resultSet, XmlWriter writer) { //XML Declaration writer.WriteStartDocument(); //<sparql> element writer.WriteStartElement("sparql", SparqlSpecsHelper.SparqlNamespace); //<head> element writer.WriteStartElement("head"); //Variables in the Header? if (resultSet.ResultsType == SparqlResultsType.VariableBindings) { foreach (String var in resultSet.Variables) { //<variable> element writer.WriteStartElement("variable"); writer.WriteAttributeString("name", var); writer.WriteEndElement(); } //</head> Element writer.WriteEndElement(); //<results> Element writer.WriteStartElement("results"); foreach (SparqlResult r in resultSet.Results) { //<result> Element writer.WriteStartElement("result"); foreach (String var in resultSet.Variables) { if (r.HasValue(var)) { INode n = r.Value(var); if (n == null) continue; //NULLs don't get serialized in the XML Format //<binding> Element writer.WriteStartElement("binding"); writer.WriteAttributeString("name", var); switch (n.NodeType) { case NodeType.Blank: //<bnode> element writer.WriteStartElement("bnode"); writer.WriteRaw(((IBlankNode)n).InternalID); writer.WriteEndElement(); break; case NodeType.GraphLiteral: //Error! throw new RdfOutputException("Result Sets which contain Graph Literal Nodes cannot be serialized in the SPARQL Query Results XML Format"); case NodeType.Literal: //<literal> element writer.WriteStartElement("literal"); ILiteralNode l = (ILiteralNode)n; if (!l.Language.Equals(String.Empty)) { writer.WriteStartAttribute("xml", "lang", XmlSpecsHelper.NamespaceXml); writer.WriteRaw(l.Language); writer.WriteEndAttribute(); } else if (l.DataType != null) { writer.WriteStartAttribute("datatype"); writer.WriteRaw(WriterHelper.EncodeForXml(l.DataType.ToString())); writer.WriteEndAttribute(); } //Write the Value and the </literal> writer.WriteRaw(WriterHelper.EncodeForXml(l.Value)); writer.WriteEndElement(); break; case NodeType.Uri: //<uri> element writer.WriteStartElement("uri"); writer.WriteRaw(WriterHelper.EncodeForXml(((IUriNode)n).Uri.ToString())); writer.WriteEndElement(); break; default: throw new RdfOutputException("Result Sets which contain Nodes of unknown Type cannot be serialized in the SPARQL Query Results XML Format"); } //</binding> element writer.WriteEndElement(); } } //</result> element writer.WriteEndElement(); } //</results> writer.WriteEndElement(); } else { //</head> writer.WriteEndElement(); //<boolean> element writer.WriteStartElement("boolean"); writer.WriteRaw(resultSet.Result.ToString().ToLower()); writer.WriteEndElement(); } //</sparql> element writer.WriteEndElement(); //End Document writer.WriteEndDocument(); writer.Close(); }
public void Generate(XmlWriter writer) { ValidatePodcastProperties(); string itunesUri = "http://www.itunes.com/dtds/podcast-1.0.dtd"; // Start document writer.WriteStartDocument(); // Start rss writer.WriteStartElement("rss"); writer.WriteAttributeString("xmlns", "itunes", null, itunesUri); writer.WriteAttributeString("version", "2.0"); // Start channel writer.WriteStartElement("channel"); writer.WriteElementString("title", this.Title); writer.WriteElementString("description", this.Description); writer.WriteElementString("link", this.HomepageUrl); writer.WriteElementString("language", this.Language); writer.WriteElementString("copyright", this.Copyright); writer.WriteElementString("lastBuildDate", DateTime.UtcNow.ToString("r")); writer.WriteElementString("pubDate", DateTime.UtcNow.ToString("r")); writer.WriteElementString("webMaster", this.AuthorEmail); // Start image writer.WriteStartElement("image"); writer.WriteElementString("url", this.ImageUrl); writer.WriteElementString("title", this.Title); writer.WriteElementString("link", this.HomepageUrl); writer.WriteElementString("width", this.ImageWidth.ToString()); writer.WriteElementString("height", this.ImageHeight.ToString()); writer.WriteElementString("description", this.Description); // End image writer.WriteEndElement(); // Categories if (this.Categories != null) foreach (string category in this.Categories) { writer.WriteElementString("Category", category); } writer.WriteElementString("author", itunesUri, this.AuthorName); writer.WriteElementString("subtitle", itunesUri, this.SubTitle); writer.WriteElementString("summary", itunesUri, this.Description); // Start itunes:owner writer.WriteStartElement("owner", itunesUri); writer.WriteElementString("name", itunesUri, this.AuthorName); writer.WriteElementString("email", itunesUri, this.AuthorEmail); // End itunes:owner writer.WriteEndElement(); writer.WriteElementString("explicit", itunesUri, (this.IsExplicit ? "Yes" : "No")); // Start itunes:image writer.WriteStartElement("image", itunesUri); writer.WriteAttributeString("href", this.ImageUrl); // End itunes:image writer.WriteEndElement(); // iTunes category // Start itunes:category writer.WriteStartElement("category", itunesUri); writer.WriteAttributeString("text", this.iTunesCategory); // Start itunes:category writer.WriteStartElement("category", itunesUri); writer.WriteAttributeString("text", this.iTunesSubCategory); // End itunes:category writer.WriteEndElement(); // End itunes:category writer.WriteEndElement(); if (this.Episodes != null) foreach (Episode episode in this.Episodes) { ValidateEpisodeProperties(episode); // Start podcast item writer.WriteStartElement("item"); writer.WriteElementString("title", episode.Title); writer.WriteElementString("link", episode.Permalink); writer.WriteElementString("guid", episode.Permalink); writer.WriteElementString("description", episode.Summary); // Start enclosure writer.WriteStartElement("enclosure"); writer.WriteAttributeString("url", episode.FileUrl); writer.WriteAttributeString("length", episode.FileLength.ToString()); writer.WriteAttributeString("type", episode.FileType); // End enclosure writer.WriteEndElement(); writer.WriteElementString("pubDate", episode.PublicationDate.ToString("r")); writer.WriteElementString("author", itunesUri, this.AuthorName); writer.WriteElementString("explicit", itunesUri, (episode.IsExplicit ? "Yes" : "No")); writer.WriteElementString("subtitle", itunesUri, episode.SubTitle); writer.WriteElementString("summary", itunesUri, episode.Summary); writer.WriteElementString("duration", itunesUri, episode.Duration); if (!string.IsNullOrEmpty(episode.Keywords)) writer.WriteElementString("keywords", itunesUri, episode.Keywords); // End podcast item writer.WriteEndElement(); } // End channel writer.WriteEndElement(); // End rss writer.WriteEndElement(); // End document writer.WriteEndDocument(); writer.Flush(); writer.Close(); }
/// <summary> /// Replay all cached events to an XmlWriter. /// </summary> public void EventsToWriter(XmlWriter writer) { XmlEvent[] page; int idxPage, idxEvent; byte[] bytes; char[] chars; XmlRawWriter rawWriter; // Special-case single text node at the top-level if (this.singleText.Count != 0) { writer.WriteString(this.singleText.GetResult()); return; } rawWriter = writer as XmlRawWriter; // Loop over set of pages for (idxPage = 0; idxPage < this.pages.Count; idxPage++) { page = this.pages[idxPage]; // Loop over events in each page for (idxEvent = 0; idxEvent < page.Length; idxEvent++) { switch (page[idxEvent].EventType) { case XmlEventType.Unknown: // No more events Debug.Assert(idxPage + 1 == this.pages.Count); return; case XmlEventType.DocType: writer.WriteDocType(page[idxEvent].String1, page[idxEvent].String2, page[idxEvent].String3, (string) page[idxEvent].Object); break; case XmlEventType.StartElem: writer.WriteStartElement(page[idxEvent].String1, page[idxEvent].String2, page[idxEvent].String3); break; case XmlEventType.StartAttr: writer.WriteStartAttribute(page[idxEvent].String1, page[idxEvent].String2, page[idxEvent].String3); break; case XmlEventType.EndAttr: writer.WriteEndAttribute(); break; case XmlEventType.CData: writer.WriteCData(page[idxEvent].String1); break; case XmlEventType.Comment: writer.WriteComment(page[idxEvent].String1); break; case XmlEventType.PI: writer.WriteProcessingInstruction(page[idxEvent].String1, page[idxEvent].String2); break; case XmlEventType.Whitespace: writer.WriteWhitespace(page[idxEvent].String1); break; case XmlEventType.String: writer.WriteString(page[idxEvent].String1); break; case XmlEventType.Raw: writer.WriteRaw(page[idxEvent].String1); break; case XmlEventType.EntRef: writer.WriteEntityRef(page[idxEvent].String1); break; case XmlEventType.CharEnt: writer.WriteCharEntity((char) page[idxEvent].Object); break; case XmlEventType.SurrCharEnt: chars = (char[]) page[idxEvent].Object; writer.WriteSurrogateCharEntity(chars[0], chars[1]); break; case XmlEventType.Base64: bytes = (byte[]) page[idxEvent].Object; writer.WriteBase64(bytes, 0, bytes.Length); break; case XmlEventType.BinHex: bytes = (byte[]) page[idxEvent].Object; writer.WriteBinHex(bytes, 0, bytes.Length); break; case XmlEventType.XmlDecl1: if (rawWriter != null) rawWriter.WriteXmlDeclaration((XmlStandalone) page[idxEvent].Object); break; case XmlEventType.XmlDecl2: if (rawWriter != null) rawWriter.WriteXmlDeclaration(page[idxEvent].String1); break; case XmlEventType.StartContent: if (rawWriter != null) rawWriter.StartElementContent(); break; case XmlEventType.EndElem: if (rawWriter != null) rawWriter.WriteEndElement(page[idxEvent].String1, page[idxEvent].String2, page[idxEvent].String3); else writer.WriteEndElement(); break; case XmlEventType.FullEndElem: if (rawWriter != null) rawWriter.WriteFullEndElement(page[idxEvent].String1, page[idxEvent].String2, page[idxEvent].String3); else writer.WriteFullEndElement(); break; case XmlEventType.Nmsp: if (rawWriter != null) rawWriter.WriteNamespaceDeclaration(page[idxEvent].String1, page[idxEvent].String2); else writer.WriteAttributeString("xmlns", page[idxEvent].String1, XmlReservedNs.NsXmlNs, page[idxEvent].String2); break; case XmlEventType.EndBase64: if (rawWriter != null) rawWriter.WriteEndBase64(); break; case XmlEventType.Close: writer.Close(); break; case XmlEventType.Flush: writer.Flush(); break; case XmlEventType.Dispose: ((IDisposable)writer).Dispose(); break; default: Debug.Assert(false, "Unknown event: " + page[idxEvent].EventType); break; } } } Debug.Assert(false, "Unknown event should be added to end of event sequence."); }
public void Serialize(World world, Stream stream) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.NewLineOnAttributes = false; settings.OmitXmlDeclaration = true; _writer = XmlWriter.Create(stream, settings); _writer.WriteStartElement("World"); _writer.WriteAttributeString("Version", "2"); WriteElement("Gravity", world.Gravity); _writer.WriteStartElement("Shapes"); for (int i = 0; i < world.BodyList.Count; i++) { Body body = world.BodyList[i]; for (int j = 0; j < body.FixtureList.Count; j++) { Fixture fixture = body.FixtureList[j]; bool alreadyThere = false; for (int k = 0; k < _serializedShapes.Count; k++) { Shape s2 = _serializedShapes[k]; if (fixture.Shape.CompareTo(s2)) { alreadyThere = true; break; } } if (!alreadyThere) { SerializeShape(fixture.Shape); _serializedShapes.Add(fixture.Shape); } } } _writer.WriteEndElement(); _writer.WriteStartElement("Fixtures"); for (int i = 0; i < world.BodyList.Count; i++) { Body body = world.BodyList[i]; for (int j = 0; j < body.FixtureList.Count; j++) { Fixture fixture = body.FixtureList[j]; bool alreadyThere = false; for (int k = 0; k < _serializedFixtures.Count; k++) { Fixture f2 = _serializedFixtures[k]; if (fixture.CompareTo(f2)) { alreadyThere = true; break; } } if (!alreadyThere) { SerializeFixture(fixture); _serializedFixtures.Add(fixture); } } } _writer.WriteEndElement(); _writer.WriteStartElement("Bodies"); for (int i = 0; i < world.BodyList.Count; i++) { Body body = world.BodyList[i]; _bodies.Add(body); SerializeBody(body); } _writer.WriteEndElement(); _writer.WriteStartElement("Joints"); for (int i = 0; i < world.JointList.Count; i++) { Joint joint = world.JointList[i]; SerializeJoint(joint); } _writer.WriteEndElement(); _writer.WriteEndElement(); _writer.Flush(); _writer.Close(); }
public static void WriteSoapEnvelopeEndAndClose(XmlWriter writer) { writer.WriteEndElement(); // s:Body writer.WriteEndElement(); // s:Envelope writer.Close(); }
private static void GenerateQRDACatOne(List<QualityMeasure> listQMs,DateTime dateStart,DateTime dateEnd,string folderRoot) { //create a list of all unique patients who belong to the initial patient population for any of the 9 CQMs List<EhrCqmPatient> listAllEhrPats=new List<EhrCqmPatient>(); //create a dictionary linking a patient to the measures to which they belong Dictionary<long,List<QualityMeasure>> dictPatNumListQMs=new Dictionary<long,List<QualityMeasure>>(); for(int i=0;i<listQMs.Count;i++) { for(int j=0;j<listQMs[i].ListEhrPats.Count;j++) { if(!dictPatNumListQMs.ContainsKey(listQMs[i].ListEhrPats[j].EhrCqmPat.PatNum)) { dictPatNumListQMs.Add(listQMs[i].ListEhrPats[j].EhrCqmPat.PatNum,new List<QualityMeasure>() { listQMs[i] }); listAllEhrPats.Add(listQMs[i].ListEhrPats[j]); } else { dictPatNumListQMs[listQMs[i].ListEhrPats[j].EhrCqmPat.PatNum].Add(listQMs[i]); } } } //listAllPats contains every unique patient who belongs to one of the initial patient population for any of the 9 CQMs //dictPatNumListQMs is a dictionary linking a patient to a list of measure for which they are in the initial patient population StringBuilder strBuilder=new StringBuilder(); StringBuilder strBuilderPatDataEntries=new StringBuilder(); //this dictionary links a PatNum key to the patient's Cat I xml dictionary value Dictionary<long,string> dictPatNumXml=new Dictionary<long,string>(); #region Cateogry I QRDA Documents for(int i=0;i<listAllEhrPats.Count;i++) { strBuilder=new StringBuilder(); strBuilderPatDataEntries=new StringBuilder(); EhrCqmPatient ehrPatCur=listAllEhrPats[i]; Patient patCur=ehrPatCur.EhrCqmPat;//just to make referencing easier long patNumCur=ehrPatCur.EhrCqmPat.PatNum;//just to make referencing easier XmlWriterSettings xmlSettings=new XmlWriterSettings(); xmlSettings.Encoding=Encoding.UTF8; xmlSettings.OmitXmlDeclaration=true; xmlSettings.Indent=true; xmlSettings.IndentChars=" "; xmlSettings.ConformanceLevel=ConformanceLevel.Fragment; using(_w=XmlWriter.Create(strBuilder,xmlSettings)) { //Begin Clinical Document _w.WriteRaw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"); _w.WriteProcessingInstruction("xml-stylesheet","type=\"text/xsl\" href=\"cda.xsl\""); _w.WriteWhitespace("\r\n"); _w.WriteStartElement("ClinicalDocument","urn:hl7-org:v3"); _w.WriteAttributeString("xmlns","xsi",null,"http://www.w3.org/2001/XMLSchema-instance"); _w.WriteAttributeString("xsi","schemaLocation",null,"urn:./CDA.xsd"); _w.WriteAttributeString("xmlns","voc",null,"urn:hl7-org:v3/voc"); _w.WriteAttributeString("xmlns","sdtc",null,"urn:hl7-org:sdtc"); #region QRDA I Header _w.WriteComment("QRDA Header"); StartAndEnd("realmCode","code","US"); StartAndEnd("typeId","root","2.16.840.1.113883.1.3","extension","POCD_HD000040");//template id to assert use of the CDA standard _w.WriteComment("US General Header Template"); TemplateId("2.16.840.1.113883.10.20.22.1.1"); _w.WriteComment("QRDA Template"); TemplateId("2.16.840.1.113883.10.20.24.1.1"); _w.WriteComment("QDM-based QRDA Template"); TemplateId("2.16.840.1.113883.10.20.24.1.2"); _w.WriteComment("This is the globally unique identifier for this QRDA document"); Guid(); _w.WriteComment("QRDA document type code"); StartAndEnd("code","code","55182-0","codeSystem",strCodeSystemLoinc,"codeSystemName",strCodeSystemNameLoinc,"displayName","Quality Measure Report"); _w.WriteElementString("title","QRDA Incidence Report"); _w.WriteComment("This is the document creation time"); TimeElement("effectiveTime",DateTime.Now); StartAndEnd("confidentialityCode","code","N","codeSystem","2.16.840.1.113883.5.25");//Fixed value. Confidentiality Code System. Codes: N=(Normal), R=(Restricted),V=(Very Restricted) StartAndEnd("languageCode","code","en-US"); #region recordTarget _w.WriteComment("Reported patient"); Start("recordTarget"); #region patientRole Start("patientRole"); string strHICNum=ValidateMedicaidID(patCur.MedicaidID); if(strHICNum!="") { _w.WriteComment("This is the patient's Medicare HIC (Health Insurance Claim) number"); StartAndEnd("id","root","2.16.840.1.113883.4.572","extension",strHICNum); } //_w.WriteComment("The extension is the patient's Open Dental number, the root is the assigning authority"); //StartAndEnd("id","root",_strOIDInternalPatRoot,"extension",patNumCur.ToString()); if(patCur.SSN.Trim().Length==9) { _w.WriteComment("This is the patient's SSN using the HL7 SSN OID"); StartAndEnd("id","root","2.16.840.1.113883.4.1","extension",patCur.SSN.Trim());//HL7 SSN OID root with patient's SSN if they have a valid one } AddressUnitedStates(patCur.Address,patCur.Address2,patCur.City,patCur.State,patCur.Zip,"HP");//Validated if(patCur.WirelessPhone.Trim()!="") {//There is at least one phone, due to validation. StartAndEnd("telecom","use","MC","value","tel:"+patCur.WirelessPhone.Trim()); _w.WriteComment("MC is \"mobile contact\" from codeSystem 2.16.840.1.113883.5.1119"); } else if(patCur.HmPhone.Trim()!="") { StartAndEnd("telecom","use","HP","value","tel:"+patCur.HmPhone.Trim()); _w.WriteComment("HP is \"primary home\" from codeSystem 2.16.840.1.113883.5.1119"); } else if(patCur.WkPhone.Trim()!="") { StartAndEnd("telecom","use","WP","value","tel:"+patCur.WkPhone.Trim()); _w.WriteComment("WP is \"work place\" from codeSystem 2.16.840.1.113883.5.1119"); } #region patient Start("patient"); #region name Start("name","use","L"); _w.WriteComment("L is \"Legal\" from codeSystem 2.16.840.1.113883.5.45"); _w.WriteElementString("given",patCur.FName);//Validated if(patCur.MiddleI!="") { _w.WriteElementString("given",patCur.MiddleI); } _w.WriteElementString("family",patCur.LName);//Validated if(patCur.Title!="") { Start("suffix","qualifier","TITLE"); _w.WriteString(patCur.Title); End("suffix"); } End("name"); #endregion name //Will always be present, because there are only 3 options and the user is forced to make a choice in the UI. if(patCur.Gender==PatientGender.Female) { StartAndEnd("administrativeGenderCode","code","F","codeSystem","2.16.840.1.113883.5.1","displayName","Female","codeSystemName","HL7 AdministrativeGender"); } else if(patCur.Gender==PatientGender.Male) { StartAndEnd("administrativeGenderCode","code","M","codeSystem","2.16.840.1.113883.5.1","displayName","Male","codeSystemName","HL7 AdministrativeGender"); } else { StartAndEnd("administrativeGenderCode","code","UN","codeSystem","2.16.840.1.113883.5.1","displayName","Undifferentiated","codeSystemName","HL7 AdministrativeGender"); } DateElement("birthTime",patCur.Birthdate);//Validated if(patCur.Position==PatientPosition.Divorced) { StartAndEnd("maritalStatusCode","code","D","displayName","Divorced","codeSystem","2.16.840.1.113883.5.2","codeSystemName","MaritalStatusCode"); } else if(patCur.Position==PatientPosition.Married) { StartAndEnd("maritalStatusCode","code","M","displayName","Married","codeSystem","2.16.840.1.113883.5.2","codeSystemName","MaritalStatusCode"); } else if(patCur.Position==PatientPosition.Widowed) { StartAndEnd("maritalStatusCode","code","W","displayName","Widowed","codeSystem","2.16.840.1.113883.5.2","codeSystemName","MaritalStatusCode"); } else {//Single and child StartAndEnd("maritalStatusCode","code","S","displayName","Never Married","codeSystem","2.16.840.1.113883.5.2","codeSystemName","MaritalStatusCode"); } #region raceCode string strRaceDescript=""; string strRaceCode="2131-1";//default will be "Other Race" //if declined to specify race, null flavor is "ASKU" - Asked, but not known. Information was sought, but not found //if race is not present, null flavor is "UNK" - Unknown. A proper value is applicable, but is not known. //These will appear as <raceCode nullFlavor=”ASKU”/> or <raceCode nullFlavor=”UNK”/> respectively bool isRaceNull=false; if(ehrPatCur.ListPatientRaces.Count==0) { isRaceNull=true; strRaceDescript="UNK"; } else if(ehrPatCur.ListPatientRaces.Count==1) {//if only one race is entered (already separated out the ethnicities) then we can construct the raceCode element with selected race switch(ehrPatCur.ListPatientRaces[0].Race) { case PatRace.AfricanAmerican: strRaceDescript="Black or African American"; strRaceCode=ehrPatCur.ListPatientRaces[0].CdcrecCode; break; case PatRace.AmericanIndian: strRaceDescript="American Indian or Alaska Native"; strRaceCode=ehrPatCur.ListPatientRaces[0].CdcrecCode; break; case PatRace.Asian: case PatRace.White: strRaceDescript=ehrPatCur.ListPatientRaces[0].Race.ToString(); strRaceCode=ehrPatCur.ListPatientRaces[0].CdcrecCode; break; case PatRace.HawaiiOrPacIsland: strRaceDescript="Native Hawaiian or Other Pacific Islander"; strRaceCode=ehrPatCur.ListPatientRaces[0].CdcrecCode; break; case PatRace.DeclinedToSpecifyRace: isRaceNull=true; strRaceDescript="ASKU"; break; default://any other race will be reported as "Other race" strRaceDescript="Other Race"; break; } } //"If there are multiple race values reported for a patient, count as ‘Other Race’ value" from downloaded implementation guide found: //\\SERVERFILES\storage\EHR\Quality Measures\QRDA\QRDAIII_CMS_EP_2014_ImplementationGuide_Vol1\QRDA_III_CMS_EP_2014_IG_Vol 2.pdf page 49 else { strRaceDescript="Other Race"; } if(isRaceNull) {//either declined to specify (flavor "ASKU") or no race recorded (flavor "UNK") StartAndEnd("raceCode","nullFlavor",strRaceDescript); } else { StartAndEnd("raceCode","code",strRaceCode,"displayName",strRaceDescript,"codeSystem","2.16.840.1.113883.6.238","codeSystemName","CDC Race and Ethnicity"); } #endregion raceCode #region ethnicityGroupCode string strEthnicityCode=""; string strEthnicityDescript=""; bool isDeclinedEthnicity=false; if(ehrPatCur.Ethnicity!=null) { if(ehrPatCur.Ethnicity.Race==PatRace.Hispanic) { strEthnicityDescript="Hispanic"; strEthnicityCode=ehrPatCur.Ethnicity.CdcrecCode; } else if(ehrPatCur.Ethnicity.Race==PatRace.NotHispanic) { strEthnicityDescript="Not Hispanic or Latino"; strEthnicityCode=ehrPatCur.Ethnicity.CdcrecCode; } else { isDeclinedEthnicity=true; } } if(ehrPatCur.Ethnicity==null) { StartAndEnd("ethnicGroupCode","nullFlavor","UNK"); } else if(isDeclinedEthnicity) { StartAndEnd("ethnicGroupCode","nullFlavor","ASKU"); } else if(strEthnicityCode!="" && strEthnicityDescript!=""){ StartAndEnd("ethnicGroupCode","code",strEthnicityCode,"displayName",strEthnicityDescript,"codeSystem","2.16.840.1.113883.6.238","codeSystemName","CDC Race and Ethnicity"); } #endregion ethnicityGroupCode End("patient"); #endregion patient End("patientRole"); #endregion patientRole End("recordTarget"); #endregion recordTarget #region comments //The author element represents the creator of the clinical document. The author may be a device, or a person. Section 4.1.2, page 69. //Participant Scenarios in a QRDA Category I Document (section 5.1.5.3, page 94) //Three possible scenarios given, the first sounds like it applies to us //1.) QRDA is wholly constructed automatically by device //Author - Device //Custodian - Organization that owns and reports the data (e.g. hospital, dental practice) //Informant - N/A //Legal Authenticator - A designated person in the organization (may be assigned to the report automatically) //2.) QRDA is partially constructed automatically by device, partially constructed by quality manager //3.) QRDA is constructed manually (e.g. by an organization that doesn't have an EHR) //We will generate a device author element, a practice custodian element, no informant element, and a Legal Authenticator element using the practice default provider #endregion #region author Start("author"); TimeElement("time",DateTime.Now); Start("assignedAuthor"); StartAndEnd("id","root","2.16.840.1.113883.3.4337","assigningAuthorityName","HL7 OID Registry"); AddressUnitedStates("3995 Fairview Industrial Dr. SE","Suite 110","Salem","OR","97302","WP"); StartAndEnd("telecom","use","WP","value","tel:(503)363-5432"); Start("assignedAuthoringDevice"); _w.WriteElementString("manufacturerModelName","Open Dental version "+PrefC.GetString(PrefName.ProgramVersion)); _w.WriteElementString("softwareName","Open Dental Software Inc."); End("assignedAuthoringDevice"); End("assignedAuthor"); End("author"); #endregion author #region custodian //"Represents the organization in charge of maintaining the document." Section 4.1.5, page 77 //The custodian is the steward that is entrusted with the care of the document. Every CDA document has exactly one custodian. Start("custodian"); Start("assignedCustodian"); Start("representedCustodianOrganization"); StartAndEnd("id","root",_strOIDInternalRoot);//This is the root assigned to the practice, based on the OD root 2.16.840.1.113883.3.4337 _w.WriteElementString("name",PrefC.GetString(PrefName.PracticeTitle));//Validated string strPracticePhone=PrefC.GetString(PrefName.PracticePhone);//Validated strPracticePhone="("+strPracticePhone.Substring(0,3)+")"+strPracticePhone.Substring(3,3)+"-"+strPracticePhone.Substring(6); StartAndEnd("telecom","use","WP","value","tel:"+strPracticePhone);//Validated AddressUnitedStates(PrefC.GetString(PrefName.PracticeAddress),PrefC.GetString(PrefName.PracticeAddress2),PrefC.GetString(PrefName.PracticeCity),PrefC.GetString(PrefName.PracticeST),PrefC.GetString(PrefName.PracticeZip),"WP");//Validated End("representedCustodianOrganization"); End("assignedCustodian"); End("custodian"); #endregion custodian #region legalAuthenticator //This element identifies the single person legally responsible for the document and must be present if the document has been legally authenticated. Start("legalAuthenticator"); TimeElement("time",DateTime.Now); StartAndEnd("signatureCode","code","S"); Start("assignedEntity"); Provider provLegal=Providers.GetProv(PrefC.GetLong(PrefName.PracticeDefaultProv)); StartAndEnd("id","root","2.16.840.1.113883.4.6","extension",provLegal.NationalProvID,"assigningAuthorityName","NPI");//Validated NPI AddressUnitedStates(PrefC.GetString(PrefName.PracticeAddress),PrefC.GetString(PrefName.PracticeAddress2),PrefC.GetString(PrefName.PracticeCity),PrefC.GetString(PrefName.PracticeST),PrefC.GetString(PrefName.PracticeZip),"WP");//Validated StartAndEnd("telecom","use","WP","value","tel:"+strPracticePhone);//Validated Start("assignedPerson"); Start("name"); _w.WriteElementString("given",provLegal.FName);//Validated _w.WriteElementString("family",provLegal.LName);//Validated End("name"); End("assignedPerson"); End("assignedEntity"); End("legalAuthenticator"); #endregion legalAuthenticator #region documentationOf Start("documentationOf","typeCode","DOC"); _w.WriteComment("care provision"); Start("serviceEvent","classCode","PCPR"); Start("effectiveTime"); DateElement("low",dateStart); DateElement("high",dateEnd); End("effectiveTime"); #region performer Start("performer","typeCode","PRF"); Start("assignedEntity"); if(_provOutQrda.NationalProvID!="") { _w.WriteComment("This is the provider NPI"); StartAndEnd("id","root","2.16.840.1.113883.4.6","extension",_provOutQrda.NationalProvID); } if(_provOutQrda.UsingTIN && _provOutQrda.SSN!="") { _w.WriteComment("This is the provider TIN"); StartAndEnd("id","root","2.16.840.1.113883.4.2","extension",_provOutQrda.SSN); } _w.WriteComment("This is the practice OID provider root and Open Dental assigned ProvNum extension"); StartAndEnd("id","root",_strOIDInternalProvRoot,"extension",_provOutQrda.ProvNum.ToString()); Start("representedOrganization"); //we don't currently have an organization level TIN or an organization Facility CMS Certification Number (CCN) //both id's are identified as "SHOULD" elements. We will include the practice name //_w.WriteComment("This is the organization TIN"); //_w.WriteComment("This is the organization CCN"); _w.WriteElementString("name",PrefC.GetString(PrefName.PracticeTitle));//Validated End("representedOrganization"); End("assignedEntity"); End("performer"); #endregion performer End("serviceEvent"); End("documentationOf"); #endregion documentationOf #endregion QRDA I Header #region QRDA I Body _w.WriteComment("QRDA Body"); Start("component"); Start("structuredBody"); #region Reporting Parameters Start("component"); Start("section"); _w.WriteComment(@" ***************************************************************** Reporting Parameters Section ***************************************************************** "); _w.WriteComment("Reporting Parameters Section Template"); TemplateId("2.16.840.1.113883.10.20.17.2.1"); StartAndEnd("code","code","55187-9","codeSystem",strCodeSystemLoinc,"codeSystemName",strCodeSystemNameLoinc,"displayName","Reporting Parameters"); _w.WriteElementString("title","Reporting Parameters"); Start("text"); Start("list"); _w.WriteElementString("item","Reporting period: "+dateStart.ToString("MMMM dd, yyyy")+" 00:00 - "+dateEnd.ToString("MMMM dd, yyyy")+" 23:59"); End("list"); End("text"); Start("entry","typeCode","DRIV"); Start("act","classCode","ACT","moodCode","EVN"); _w.WriteComment("Reporting Parameteres Act Template"); TemplateId("2.16.840.1.113883.10.20.17.3.8"); StartAndEnd("code","code","252116004","codeSystem",strCodeSystemSnomed,"codeSystemName",strCodeSystemNameSnomed,"displayName","Observation Parameters"); Start("effectiveTime"); StartAndEnd("low","value",dateStart.ToString("yyyyMMdd")+"000000"); StartAndEnd("high","value",dateEnd.ToString("yyyyMMdd")+"235959"); End("effectiveTime"); End("act"); End("entry"); End("section"); End("component"); #endregion Reporting Parameters #region Measure Section Start("component"); Start("section"); _w.WriteComment(@" ***************************************************************** Measure Section ***************************************************************** "); _w.WriteComment("Measure Section Template"); TemplateId("2.16.840.1.113883.10.20.24.2.2"); _w.WriteComment("Measure Section QDM Template"); TemplateId("2.16.840.1.113883.10.20.24.2.3"); _w.WriteComment("This is the LOINC code for \"Measure document\". This stays the same for all measure sections required by QRDA standard"); StartAndEnd("code","code","55186-1","codeSystem",strCodeSystemLoinc,"codeSystemName",strCodeSystemNameLoinc,"displayName","Measure Document"); _w.WriteElementString("title","Measure Section"); #region text version of eMeasures as table Start("text"); Start("table","border","1","width","100%"); Start("thead"); Start("tr"); _w.WriteElementString("th","eMeasure Identifier (MAT)"); _w.WriteElementString("th","eMeasure Title"); _w.WriteElementString("th","Version neutral identifier"); _w.WriteElementString("th","eMeasure Version Number"); _w.WriteElementString("th","Version specific identifier"); End("tr"); End("thead"); Start("tbody"); for(int j=0;j<listQMs.Count;j++) { //_listExtraPopIndxs will contain all of the Type2014 enum types that are stratifications or extra populations of other measures, so skip them here if(_listExtraPopIndxs.Contains(i)) { continue; } MeasureTextTableRow(listQMs[j].eMeasureTitle,listQMs[j].eMeasureNum,listQMs[j].eMeasureVNeutralId,listQMs[j].eMeasureVersion,listQMs[j].eMeasureVSpecificId); } End("tbody"); End("table"); End("text"); #endregion text version of eMeasures as table #region eMeasure entries _w.WriteComment("1..* Organizers, each containing a reference to an eMeasure"); for(int j=0;j<listQMs.Count;j++) { //_listExtraPopIndxs will contain all of the Type2014 enum types that are stratifications or extra populations of other measures, so skip them here if(_listExtraPopIndxs.Contains(i)) { continue; } MeasureEntry(listQMs[j].eMeasureVSpecificId,listQMs[j].eMeasureTitle,listQMs[j].eMeasureVNeutralId,listQMs[j].eMeasureVersion); } #endregion eMeasure entries End("section"); End("component"); #endregion Measure Section #region Patient Data Start("component"); Start("section"); _w.WriteComment(@" ***************************************************************** Patient Data Section ***************************************************************** "); _w.WriteComment("Patient Data Section Template"); TemplateId("2.16.840.1.113883.10.20.17.2.4"); _w.WriteComment("Patient Data QDM Section Template"); TemplateId("2.16.840.1.113883.10.20.24.2.1"); StartAndEnd("code","code","55188-7","codeSystem",strCodeSystemLoinc,"codeSystemName",strCodeSystemNameLoinc,"displayName","Patient Data"); _w.WriteElementString("title","Patient Data"); Start("text"); Start("table","border","1","width","100%"); Start("thead"); Start("tr"); _w.WriteElementString("th","Description"); _w.WriteElementString("th","Value Set"); _w.WriteElementString("th","Code"); _w.WriteElementString("th","Date/Time"); _w.WriteElementString("th","Results"); End("tr"); End("thead"); Start("tbody"); using(_x=XmlWriter.Create(strBuilderPatDataEntries,xmlSettings)) { _x.WriteStartElement("ClinicalDocument","urn:hl7-org:v3"); _x.WriteAttributeString("xmlns","xsi",null,"http://www.w3.org/2001/XMLSchema-instance"); _x.WriteAttributeString("xsi","schemaLocation",null,"urn:./CDA.xsd"); _x.WriteAttributeString("xmlns","voc",null,"urn:hl7-org:v3/voc"); _x.WriteAttributeString("xmlns","sdtc",null,"urn:hl7-org:sdtc"); List<QualityMeasure> listQMsCur=dictPatNumListQMs[patNumCur]; //this list of unique item ids is used when building the plain text version so that the encounter/procedure/item will only be in the plain text version once //we will add the item to the entries multiple times since the item can belong to different value sets //and must have the value set specific to the measure for which it qualifies the patient List<string> listUniqueItemExtensionsWithValueSetOIDs=new List<string>(); List<string> listUniqueItemExtensions=new List<string>(); //create encounter entries for each measure for this patient #region encounters for(int j=0;j<listQMsCur.Count;j++) { if(!listQMsCur[j].DictPatNumListEncounters.ContainsKey(patNumCur)) { continue; } for(int k=0;k<listQMsCur[j].DictPatNumListEncounters[patNumCur].Count;k++) { EhrCqmEncounter encCur=listQMsCur[j].DictPatNumListEncounters[patNumCur][k]; //if in this list with ValueSetOID, then it must be in the non-ValueSetOID list, so just continue string extensCur=CqmItemAbbreviation.Enc.ToString()+encCur.ValueSetOID+"Num"+encCur.EhrCqmEncounterNum.ToString(); if(!listUniqueItemExtensionsWithValueSetOIDs.Contains(extensCur)) { listUniqueItemExtensionsWithValueSetOIDs.Add(extensCur); GenerateEncounterEntry(encCur); } extensCur=CqmItemAbbreviation.Enc.ToString()+encCur.EhrCqmEncounterNum.ToString(); if(listUniqueItemExtensions.Contains(extensCur)) { continue; } listUniqueItemExtensions.Add(extensCur); #region BuildPlainTextVersion string descript="Encounter, Performed: "+encCur.ValueSetName; PatientDataTextTableRow(descript,encCur.ValueSetOID,encCur.CodeSystemName,encCur.CodeValue,encCur.DateEncounter,encCur.DateEncounter,""); #endregion BuildPlainTextVersion } } #endregion encounters //create intervention entries for each measure for this patient #region interventions for(int j=0;j<listQMsCur.Count;j++) { if(!listQMsCur[j].DictPatNumListInterventions.ContainsKey(patNumCur)) { continue; } for(int k=0;k<listQMsCur[j].DictPatNumListInterventions[patNumCur].Count;k++) { EhrCqmIntervention iCur=listQMsCur[j].DictPatNumListInterventions[patNumCur][k]; string extensCur=CqmItemAbbreviation.Ivn.ToString()+iCur.ValueSetOID+"Num"+iCur.EhrCqmInterventionNum.ToString(); if(!listUniqueItemExtensionsWithValueSetOIDs.Contains(extensCur)) { listUniqueItemExtensionsWithValueSetOIDs.Add(extensCur); GenerateInterventionEntry(iCur); } extensCur=CqmItemAbbreviation.Ivn.ToString()+iCur.EhrCqmInterventionNum.ToString(); if(listUniqueItemExtensions.Contains(extensCur)) { continue; } listUniqueItemExtensions.Add(extensCur); #region BuildPlainTextVersion string descript=""; if(listQMsCur[j].Type2014==QualityType2014.WeightAdult || listQMsCur[j].Type2014==QualityType2014.WeightOver65) {//interventions in these two measures are ordered descript="Intervention, Order: "; } else { descript="Intervention, Performed: "; } descript+=iCur.ValueSetName; PatientDataTextTableRow(descript,iCur.ValueSetOID,iCur.CodeSystemName,iCur.CodeValue,iCur.DateEntry,iCur.DateEntry,""); #endregion BuildPlainTextVersion } } #endregion interventions //create ehrmeasureevents for each measure for this patient #region ehrmeasureevents for(int j=0;j<listQMsCur.Count;j++) { if(!listQMsCur[j].DictPatNumListMeasureEvents.ContainsKey(patNumCur)) { continue; } for(int k=0;k<listQMsCur[j].DictPatNumListMeasureEvents[patNumCur].Count;k++) { EhrCqmMeasEvent mCur=listQMsCur[j].DictPatNumListMeasureEvents[patNumCur][k]; string extensCur=CqmItemAbbreviation.MeasEvn.ToString()+mCur.ValueSetOID+"Num"+mCur.EhrCqmMeasEventNum.ToString(); if(!listUniqueItemExtensionsWithValueSetOIDs.Contains(extensCur)) { listUniqueItemExtensionsWithValueSetOIDs.Add(extensCur); GenerateMeasEventEntry(mCur); } extensCur=CqmItemAbbreviation.MeasEvn.ToString()+mCur.EhrCqmMeasEventNum.ToString(); if(listUniqueItemExtensions.Contains(extensCur)) { continue; } listUniqueItemExtensions.Add(extensCur); #region BuildPlainTextVersion string descript=""; if(mCur.EventType==EhrMeasureEventType.TobaccoUseAssessed) { descript="Patient Characteristic: "; } else if(mCur.EventType==EhrMeasureEventType.CurrentMedsDocumented) { descript="Procedure, Performed: "; } descript+=mCur.ValueSetName+" - "+mCur.Description; PatientDataTextTableRow(descript,mCur.ValueSetOID,mCur.CodeSystemName,mCur.CodeValue,mCur.DateTEvent,mCur.DateTEvent,""); #endregion BuildPlainTextVersion } } #endregion ehrmeasureevents //create medicationpats for each measure for this patient #region medicationpats for(int j=0;j<listQMsCur.Count;j++) { //have to check for CompletionStatus=NotAdministered if vaccine, vaccines given are procedures performed, not given are medication allergy or intolerance if(!listQMsCur[j].DictPatNumListMedPats.ContainsKey(patNumCur)) { continue; } for(int k=0;k<listQMsCur[j].DictPatNumListMedPats[patNumCur].Count;k++) { EhrCqmMedicationPat mPatCur=listQMsCur[j].DictPatNumListMedPats[patNumCur][k]; string extensCur=CqmItemAbbreviation.MedPat.ToString()+mPatCur.ValueSetOID+"Num"; if(mPatCur.EhrCqmMedicationPatNum!=0) { extensCur+=mPatCur.EhrCqmMedicationPatNum.ToString(); } else { extensCur+=mPatCur.EhrCqmVaccinePatNum.ToString(); } if(!listUniqueItemExtensionsWithValueSetOIDs.Contains(extensCur)) { listUniqueItemExtensionsWithValueSetOIDs.Add(extensCur); GenerateMedPatsEntry(mPatCur); } extensCur=CqmItemAbbreviation.MedPat.ToString(); if(mPatCur.EhrCqmMedicationPatNum!=0) { extensCur+=mPatCur.EhrCqmMedicationPatNum.ToString(); } else { extensCur+=mPatCur.EhrCqmVaccinePatNum.ToString(); } if(listUniqueItemExtensions.Contains(extensCur)) { continue; } listUniqueItemExtensions.Add(extensCur); #region BuildPlainTextVersion string descript=""; string codeValue=""; //represents a medication. Used by tobacco cessation or above/below normal weight meds if(mPatCur.EhrCqmMedicationPatNum!=0) { codeValue=mPatCur.RxCui.ToString(); //Will be Medication, Active/Order if(mPatCur.PatNote!="") {//PatNote means an order descript="Medication, Ordered: "; } else { descript="Medication, Active: "; } } //EhrCqmVaccinePatNum will only be set if pneumonia or influenza measure and it represents a vaccine else { codeValue=mPatCur.CVXCode; if(mPatCur.CompletionStatus==VaccineCompletionStatus.NotAdministered) {//NotAdministered is due to an allergy or intolerance descript="Medication, Allergy: "; } else {//only getting CompletionStatus=Complete or NotAdministered, the else is for Complete descript="Medication, Administered: "; } } descript+=mPatCur.ValueSetName+" - "+mPatCur.Description; PatientDataTextTableRow(descript,mPatCur.ValueSetOID,mPatCur.CodeSystemName,codeValue,mPatCur.DateStart,mPatCur.DateStop,""); #endregion BuildPlainTextVersion } } #endregion medicationpats //create ehrnotperformeds for each measure for this patient #region ehrnotperformeds for(int j=0;j<listQMsCur.Count;j++) { //have to determine what is not being performed, Procedure (flu vaccine, current meds documented), Medication (flu vaccine), Physical Exam, Tobacco screening //if ValueSetOID=2.16.840.1.113883.3.526.3.1254, then Medication, Administered not done: Medical/Patient/System Reason (flu vaccine med) //if ValueSetOID=2.16.840.1.113883.3.526.3.402, then Procedure, Performed not done: Medical/Patient/System Reason (flu vaccine proc) //if ValueSetOID=2.16.840.1.113883.3.600.1.462, then Procedure, Performed not done: Medical or Other reason not done (current meds documented proc) //if ValueSetOID=2.16.840.1.113883.3.600.1.681, then Physical Exam, Performed not done: Medical or Other reason not done/Patient Reason Refused (vitalsign exam) //if ValueSetOID=2.16.840.1.113883.3.526.3.1278, then Risk Category Assessment not done: Medical Reason (tobacco assessment) //Then use the negationInd="true" attribute to indicate that it was not performed if(!listQMsCur[j].DictPatNumListNotPerfs.ContainsKey(patNumCur)) { continue; } for(int k=0;k<listQMsCur[j].DictPatNumListNotPerfs[patNumCur].Count;k++) { EhrCqmNotPerf npCur=listQMsCur[j].DictPatNumListNotPerfs[patNumCur][k]; string extensCur=CqmItemAbbreviation.NotPerf.ToString()+npCur.ValueSetOID+"Num"+npCur.EhrCqmNotPerfNum.ToString(); if(!listUniqueItemExtensionsWithValueSetOIDs.Contains(extensCur)) { listUniqueItemExtensionsWithValueSetOIDs.Add(extensCur); GenerateNotPerfEntry(npCur); } extensCur=CqmItemAbbreviation.NotPerf.ToString()+npCur.EhrCqmNotPerfNum.ToString(); if(listUniqueItemExtensions.Contains(extensCur)) { continue; } listUniqueItemExtensionsWithValueSetOIDs.Add(extensCur); #region BuildPlainTextVersion string descript=""; if(npCur.ValueSetOID=="2.16.840.1.113883.3.526.3.1254") { descript="Medication, Administered not done: "; } else if(npCur.ValueSetOID=="2.16.840.1.113883.3.526.3.402" || npCur.ValueSetOID=="2.16.840.1.113883.3.600.1.462") { descript="Procedure, Performed not done: "; } else if(npCur.ValueSetOID=="2.16.840.1.113883.3.600.1.681") { descript="Physical Exam, Performed not done: "; } else {//must be a 2.16.840.1.113883.3.526.3.1278, not performed items restricted to one of these 5 value sets descript="Risk Category Assessment not done: "; } descript+=npCur.ValueSetName+" - "+npCur.DescriptionReason; PatientDataTextTableRow(descript,npCur.ValueSetOID,npCur.CodeSystemName,npCur.CodeValue,npCur.DateEntry,npCur.DateEntry,""); #endregion BuildPlainTextVersion } } #endregion ehrnotperformeds //create problems for each measure for this patient #region problems for(int j=0;j<listQMsCur.Count;j++) { //if ValueSetOID = 2.16.840.1.113883.3.526.3.1255, SNOMEDCT - 315640000 - Influenza vaccination declined (situation), then it is a Communication, From patient to provider: //if ValueSetOID = 2.16.840.1.113883.3.464.1003.110.12.1028, SNOMEDCT - 310578008 - Pneumococcal vaccination given (finding), then it is a Risk Category Assessment: //if ValueSetOID = 2.16.840.1.113883.3.600.1.1579 - Palliative Care, then it is a Procedure, Order: //Otherwise it is a Diagnosis, Active: if(!listQMsCur[j].DictPatNumListProblems.ContainsKey(patNumCur)) { continue; } for(int k=0;k<listQMsCur[j].DictPatNumListProblems[patNumCur].Count;k++) { EhrCqmProblem probCur=listQMsCur[j].DictPatNumListProblems[patNumCur][k]; string extensCur=CqmItemAbbreviation.Prob.ToString()+probCur.ValueSetOID+"Num"+probCur.EhrCqmProblemNum.ToString(); if(!listUniqueItemExtensionsWithValueSetOIDs.Contains(extensCur)) { listUniqueItemExtensionsWithValueSetOIDs.Add(extensCur); switch(probCur.ValueSetOID) { case "2.16.840.1.113883.3.526.3.1255": GenerateCommunicationEntry(probCur); break; case "2.16.840.1.113883.3.464.1003.110.12.1028": GenerateRiskAssessEntry(probCur); break; case "2.16.840.1.113883.3.600.1.1579": GenerateProcedureEntry(null,probCur); break; default: GenerateDiagnosisEntry(probCur); break; } } extensCur=CqmItemAbbreviation.Prob.ToString()+probCur.EhrCqmProblemNum.ToString(); if(listUniqueItemExtensions.Contains(extensCur)) { continue; } listUniqueItemExtensions.Add(extensCur); #region BuildPlainTextVersion string descript=""; switch(probCur.ValueSetOID) { case "2.16.840.1.113883.3.526.3.1255": descript="Communication, From patient to provider: "; break; case "2.16.840.1.113883.3.464.1003.110.12.1028": descript="Risk Category Assessment: "; break; case "2.16.840.1.113883.3.600.1.1579": descript="Procedure, Order: "; break; default: descript="Diagnosis, Active: "; break; } descript+=probCur.ValueSetName+" - "+probCur.Description; PatientDataTextTableRow(descript,probCur.ValueSetOID,probCur.CodeSystemName,probCur.CodeValue,probCur.DateStart,probCur.DateStop,""); #endregion BuildPlainTextVersion } } #endregion problems //create procs for each measure for this patient #region procs for(int j=0;j<listQMsCur.Count;j++) { if(!listQMsCur[j].DictPatNumListProcs.ContainsKey(patNumCur)) { continue; } for(int k=0;k<listQMsCur[j].DictPatNumListProcs[patNumCur].Count;k++) { EhrCqmProc procCur=listQMsCur[j].DictPatNumListProcs[patNumCur][k]; string extensCur=CqmItemAbbreviation.Proc.ToString()+procCur.ValueSetOID+"Num"+procCur.EhrCqmProcNum.ToString(); if(!listUniqueItemExtensionsWithValueSetOIDs.Contains(extensCur)) { listUniqueItemExtensionsWithValueSetOIDs.Add(extensCur); GenerateProcedureEntry(procCur,null); } extensCur=CqmItemAbbreviation.Proc.ToString()+procCur.EhrCqmProcNum.ToString(); if(listUniqueItemExtensions.Contains(extensCur)) { continue; } listUniqueItemExtensions.Add(extensCur); #region BuildPlainTextVersion string descript="Procedure, Performed: "+procCur.ValueSetName+" - "+procCur.Description; PatientDataTextTableRow(descript,procCur.ValueSetOID,procCur.CodeSystemName,procCur.ProcCode,procCur.ProcDate,procCur.ProcDate,""); #endregion BuildPlainTextVersion } } #endregion procs //create vitalsigns for each measure for this patient #region vitalsigns for(int j=0;j<listQMsCur.Count;j++) { if(!listQMsCur[j].DictPatNumListVitalsigns.ContainsKey(patNumCur)) { continue; } for(int k=0;k<listQMsCur[j].DictPatNumListVitalsigns[patNumCur].Count;k++) { EhrCqmVitalsign vCur=listQMsCur[j].DictPatNumListVitalsigns[patNumCur][k]; string extensCur=""; if(vCur.BpDiastolic>0) { extensCur=CqmItemAbbreviation.Vital.ToString()+"2.16.840.1.113883.3.526.3.1033"+"Num"+vCur.EhrCqmVitalsignNum.ToString(); if(!listUniqueItemExtensionsWithValueSetOIDs.Contains(extensCur)) { listUniqueItemExtensionsWithValueSetOIDs.Add(extensCur); GenerateVitalsignEntry(vCur,"BPd"); } } if(vCur.BpSystolic>0) { extensCur=CqmItemAbbreviation.Vital.ToString()+"2.16.840.1.113883.3.526.3.1032"+"Num"+vCur.EhrCqmVitalsignNum.ToString(); if(!listUniqueItemExtensionsWithValueSetOIDs.Contains(extensCur)) { listUniqueItemExtensionsWithValueSetOIDs.Add(extensCur); GenerateVitalsignEntry(vCur,"BPs"); } } if(vCur.BMI>0) { extensCur=CqmItemAbbreviation.Vital.ToString()+"2.16.840.1.113883.3.464.1003.121.12.1014"+"Num"+vCur.EhrCqmVitalsignNum.ToString(); if(!listUniqueItemExtensionsWithValueSetOIDs.Contains(extensCur)) { listUniqueItemExtensionsWithValueSetOIDs.Add(extensCur); GenerateVitalsignEntry(vCur,"Ht"); } extensCur=CqmItemAbbreviation.Vital.ToString()+"2.16.840.1.113883.3.464.1003.121.12.1015"+"Num"+vCur.EhrCqmVitalsignNum.ToString(); if(!listUniqueItemExtensionsWithValueSetOIDs.Contains(extensCur)) { listUniqueItemExtensionsWithValueSetOIDs.Add(extensCur); GenerateVitalsignEntry(vCur,"Wt"); } extensCur=CqmItemAbbreviation.Vital.ToString()+"2.16.840.1.113883.3.600.1.681"+vCur.EhrCqmVitalsignNum.ToString(); if(!listUniqueItemExtensionsWithValueSetOIDs.Contains(extensCur)) { listUniqueItemExtensionsWithValueSetOIDs.Add(extensCur); GenerateVitalsignEntry(vCur,"BMI"); } } //if(vCur.BMIPercentile>-1) { // GenerateVitalsignEntry(vCur,"BMIp"); //} extensCur=CqmItemAbbreviation.Vital.ToString()+vCur.EhrCqmVitalsignNum.ToString(); if(listUniqueItemExtensions.Contains(extensCur)) { continue; } listUniqueItemExtensions.Add(extensCur); #region BuildPlainTextVersion string descript=""; if(vCur.BpDiastolic>0) { descript="Physical Exam, Finding: Diastolic Blood Pressure"; PatientDataTextTableRow(descript,"2.16.840.1.113883.3.526.3.1033","LOINC","8462-4",vCur.DateTaken,vCur.DateTaken,vCur.BpDiastolic.ToString()+" mmHg"); } if(vCur.BpSystolic>0) { descript="Physical Exam, Finding: Systolic Blood Pressure"; PatientDataTextTableRow(descript,"2.16.840.1.113883.3.526.3.1032","LOINC","8480-6",vCur.DateTaken,vCur.DateTaken,vCur.BpSystolic.ToString()+" mmHg"); } if(vCur.BMI>0) { descript="Physical Exam, Finding: Height"; PatientDataTextTableRow(descript,"2.16.840.1.113883.3.464.1003.121.12.1014","LOINC",vCur.HeightExamCode,vCur.DateTaken,vCur.DateTaken,vCur.Height.ToString()+" in"); descript="Physical Exam, Finding: Weight"; PatientDataTextTableRow(descript,"2.16.840.1.113883.3.464.1003.121.12.1015","LOINC",vCur.WeightExamCode,vCur.DateTaken,vCur.DateTaken,vCur.Weight.ToString()+" lb"); descript="Physical Exam, Finding: BMI LOINC Value"; PatientDataTextTableRow(descript,"2.16.840.1.113883.3.600.1.681","LOINC","39156-5",vCur.DateTaken,vCur.DateTaken,vCur.BMI.ToString("0.00")+" kg/m2"); } //if(vCur.BMIPercentile>-1) { // descript="Physical Exam, Finding: BMI Percentile"; // PatientDataTextTableRow(descript,"2.16.840.1.113883.3.464.1003.121.12.1012","LOINC",vCur.BMIExamCode,vCur.DateTaken,vCur.DateTaken,vCur.BMIPercentile.ToString()); //} #endregion BuildPlainTextVersion } } #endregion vitalsigns _x.WriteEndElement(); } End("tbody"); End("table"); End("text"); XmlDocument doc=new XmlDocument(); doc.LoadXml(strBuilderPatDataEntries.ToString()); XmlElement elementClinicalDocument=doc.DocumentElement; for(int n=0;n<elementClinicalDocument.ChildNodes.Count;n++) { elementClinicalDocument.ChildNodes[n].WriteTo(_w); } Start("entry"); Start("observation","classCode","OBS","moodCode","EVN"); _w.WriteComment("Patient Characteristic Payer Template"); TemplateId("2.16.840.1.113883.10.20.24.3.55"); StartAndEnd("id","root",_strOIDInternalCQMRoot,"extension",CqmItemAbbreviation.Payer.ToString()+patCur.PatNum.ToString()); StartAndEnd("code","code","48768-6","displayName","Payment source","codeSystem",strCodeSystemLoinc,"codeSystemName",strCodeSystemNameLoinc); StartAndEnd("statusCode","code","completed"); Start("value"); _w.WriteAttributeString("xsi","type",null,"CD"); Attribs("code",ehrPatCur.PayorSopCode,"displayName",ehrPatCur.PayorDescription,"codeSystem","2.16.840.1.113883.3.221.5","codeSystemName","Source of Payment Typology"); _w.WriteAttributeString("sdtc","valueSet",null,ehrPatCur.PayorValueSetOID); End("value"); End("observation"); End("entry"); End("section"); End("component"); #endregion Patient Data End("structuredBody"); #endregion QRDA I Body End("component"); End("ClinicalDocument"); } string xmlResult=strBuilder.ToString(); dictPatNumXml.Add(patNumCur,xmlResult); SecurityLogs.MakeLogEntry(Permissions.Copy,patNumCur,"QRDA Category I generated");//Create audit log entry. } for(int i=0;i<listAllEhrPats.Count;i++) { Patient patCur=listAllEhrPats[i].EhrCqmPat; if(!dictPatNumXml.ContainsKey(patCur.PatNum)) {//every patient will be in the dictionary, this is just in case continue; } List<QualityMeasure> listPatQMs=dictPatNumListQMs[patCur.PatNum]; for(int j=0;j<listPatQMs.Count;j++) { System.IO.File.WriteAllText(folderRoot+"\\Measure_"+listPatQMs[j].eMeasureNum+"\\"+patCur.PatNum+"_"+patCur.LName+"_"+patCur.FName+".xml",dictPatNumXml[patCur.PatNum]); } } try { string[] allMeasDirs=System.IO.Directory.GetDirectories(folderRoot); for(int i=0;i<allMeasDirs.Length;i++) { using(ZipFile zipCur=new ZipFile()) { string[] allPatFiles=System.IO.Directory.GetFiles(allMeasDirs[i]); zipCur.AddFiles(allPatFiles,""); zipCur.Save(allMeasDirs[i]+".zip"); System.IO.Directory.Delete(allMeasDirs[i],true); } } } catch(Exception ex){ throw new ApplicationException("Zipfile creation error: "+ex.Message); } _w.Flush(); _w.Close(); #endregion Cateogry I QRDA Documents }
///<summary>This method generates the entire Category III aggregate information document and places it in the path supplied in folderRoot\QRDA_Category_III.xml.</summary> private static void GenerateQRDACatThree(List<QualityMeasure> listQMs,DateTime dateStart,DateTime dateEnd,string folderRoot) { XmlWriterSettings xmlSettings=new XmlWriterSettings(); xmlSettings.Encoding=Encoding.UTF8; xmlSettings.OmitXmlDeclaration=true; xmlSettings.Indent=true; xmlSettings.IndentChars="\t"; using(_w=XmlWriter.Create(folderRoot+"\\QRDA_Category_III.xml",xmlSettings)) { //Begin Clinical Document _w.WriteProcessingInstruction("xml-stylesheet","type=\"text/xsl\" href=\"qrda.xsl\""); _w.WriteWhitespace("\r\n"); _w.WriteStartElement("ClinicalDocument","urn:hl7-org:v3"); _w.WriteAttributeString("xmlns","xsi",null,"http://www.w3.org/2001/XMLSchema-instance"); _w.WriteAttributeString("xsi","schemaLocation",null,"urn:./CDA.xsd"); _w.WriteAttributeString("xmlns","voc",null,"urn:hl7-org:v3/voc"); #region QRDA III Header _w.WriteComment("QRDA III Header"); StartAndEnd("realmCode","code","US"); StartAndEnd("typeId","root","2.16.840.1.113883.1.3","extension","POCD_HD000040");//template id to assert use of the CDA standard _w.WriteComment("QRDA Category III Release 1 Template"); TemplateId("2.16.840.1.113883.10.20.27.1.1"); _w.WriteComment("This is the globally unique identifier for this QRDA III document"); Guid(); _w.WriteComment("QRDA III document type code"); StartAndEnd("code","code","55184-6","codeSystem",strCodeSystemLoinc,"codeSystemName",strCodeSystemNameLoinc,"displayName","Quality Reporting Document Architecture Calculated Summary Report"); _w.WriteElementString("title","QRDA Calculated Summary Report for CMS Measures 68, 69, 74, 75, 127, 138, 147, 155, and 165"); _w.WriteComment("This is the document creation time"); TimeElement("effectiveTime",DateTime.Now); StartAndEnd("confidentialityCode","code","N","codeSystem","2.16.840.1.113883.5.25");//Fixed value. Confidentiality Code System. Codes: N=(Normal), R=(Restricted),V=(Very Restricted) StartAndEnd("languageCode","code","en-US"); #region recordTarget _w.WriteComment("Record Target and ID - but ID is nulled to NA. This is an aggregate summary report. Therefore CDA's required patient identifier is nulled."); Start("recordTarget"); Start("patientRole"); StartAndEnd("id","nullFlavor","NA"); End("patientRole"); End("recordTarget"); #endregion recordTarget #region comments //The author element represents the creator of the clinical document. The author may be a device, or a person. //Participant Scenarios in a QRDA Category III Document (section 2.3, page 29) //Several possible scenarios given, the first sounds like it applies to us //Scenario - QRDA is wholly constructed automatically by device //Author - Device //Custodian - Organization that owns and reports the data (e.g. hospital, dental practice) //Legal Authenticator - A designated person in the organization (may be assigned to the report automatically) //We will generate a device author element, a practice custodian element, and a Legal Authenticator element using the practice default provider #endregion comments #region author Start("author"); TimeElement("time",DateTime.Now); Start("assignedAuthor"); StartAndEnd("id","root","2.16.840.1.113883.3.4337","assigningAuthorityName","HL7 OID Registry"); Start("assignedAuthoringDevice"); _w.WriteElementString("softwareName","Open Dental version "+PrefC.GetString(PrefName.ProgramVersion)); End("assignedAuthoringDevice"); Start("representedOrganization"); _w.WriteElementString("name",PrefC.GetString(PrefName.PracticeTitle));//Validated End("representedOrganizaion"); End("assignedAuthor"); End("author"); #endregion author #region custodian //Represents the organization in charge of maintaining the document. //The custodian is the steward that is entrusted with the care of the document. Every CDA document has exactly one custodian. Start("custodian"); Start("assignedCustodian"); Start("representedCustodianOrganization"); StartAndEnd("id","root",_strOIDInternalRoot);//This is the root assigned to the practice, based on the OD root 2.16.840.1.113883.3.4337 _w.WriteElementString("name",PrefC.GetString(PrefName.PracticeTitle));//Validated End("representedCustodianOrganization"); End("assignedCustodian"); End("custodian"); #endregion custodian #region legalAuthenticator //This element identifies the single person legally responsible for the document and must be present if the document has been legally authenticated. Start("legalAuthenticator"); TimeElement("time",DateTime.Now); StartAndEnd("signatureCode","code","S"); Start("assignedEntity"); Provider provLegal=Providers.GetProv(PrefC.GetLong(PrefName.PracticeDefaultProv)); StartAndEnd("id","root","2.16.840.1.113883.4.6","extension",provLegal.NationalProvID,"assigningAuthorityName","NPI");//Validated NPI Start("representedOrganization"); StartAndEnd("id","root",_strOIDInternalRoot);//This is the root assigned to the practice, based on the OD root 2.16.840.1.113883.3.4337 _w.WriteElementString("name",PrefC.GetString(PrefName.PracticeTitle));//Validated End("representedOrganization"); End("assignedEntity"); End("legalAuthenticator"); #endregion legalAuthenticator #region documentationOf //The documentationOf service event can contain identifiers for all of the (one or more) providers involved, using the serviceEvent/performer elements. //A serviceEvent/performer element must be present for each performer reporting data to a quality organization. Start("documentationOf","typeCode","DOC"); Start("serviceEvent","classCode","PCPR");//PCPR is HL7ActClass code for Care Provision _w.WriteComment("Care Provision"); Start("effectiveTime"); DateElement("low",dateStart); DateElement("high",dateEnd); End("effectiveTime"); Start("performer","typeCode","PRF"); Start("time"); StartAndEnd("low","value",dateStart.ToString("yyyyMMdd")+"000000"); StartAndEnd("high","value",dateEnd.ToString("yyyyMMdd")+"235959"); End("time"); Start("assignedEntity"); if(_provOutQrda.NationalProvID!="") { _w.WriteComment("This is the provider NPI"); StartAndEnd("id","root","2.16.840.1.113883.4.6","extension",_provOutQrda.NationalProvID); } if(_provOutQrda.UsingTIN && _provOutQrda.SSN!="") { _w.WriteComment("This is the provider TIN"); StartAndEnd("id","root","2.16.840.1.113883.4.2","extension",_provOutQrda.SSN); } _w.WriteComment("This is the practice OID provider root and Open Dental assigned ProvNum extension"); StartAndEnd("id","root",_strOIDInternalProvRoot,"extension",_provOutQrda.ProvNum.ToString()); Start("representedOrganization"); //we don't currently have an organization level TIN or an organization Facility CMS Certification Number (CCN) //both id's are identified as "SHOULD" elements. We will include the practice name _w.WriteElementString("name",PrefC.GetString(PrefName.PracticeTitle));//Validated End("representedOrganization"); End("assignedEntity"); End("performer"); End("serviceEvent"); End("documentationOf"); #endregion participant #endregion QRDA III Header #region QRDA III Body Start("component"); Start("structuredBody"); #region reportingParameters component _w.WriteComment("Reporting Parameters Component"); Start("component"); Start("section"); _w.WriteComment("Reporting Parameters Section Template"); TemplateId("2.16.840.1.113883.10.20.17.2.1"); _w.WriteComment("QRDA Category III Reporting Parameters Section Template"); TemplateId("2.16.840.1.113883.10.20.27.2.2"); StartAndEnd("code","code","55187-9","displayName","Reporting Parameters","codeSystem",strCodeSystemLoinc,"codeSystemName",strCodeSystemNameLoinc); _w.WriteElementString("title","Reporting Parameters"); Start("text"); Start("list"); _w.WriteElementString("item","Reporting period: "+dateStart.ToString("MMMM dd, yyyy")+" 00:00 - "+dateEnd.ToString("MMMM dd, yyyy")+" 23:59"); End("list"); End("text"); Start("entry","typeCode","DRIV"); Start("act","classCode","ACT","moodCode","EVN"); _w.WriteComment("Reporting Parameters Act Template"); TemplateId("2.16.840.1.113883.10.20.17.3.8"); StartAndEnd("code","code","252116004","displayName","Observation Parameters","codeSystem",strCodeSystemSnomed,"codeSystemName",strCodeSystemNameSnomed); Start("effectiveTime"); _w.WriteComment("The first day of the reporting period"); DateElement("low",dateStart); _w.WriteComment("The last day of the reporting period"); DateElement("high",dateEnd); End("effectiveTime"); End("act"); End("entry"); End("section"); End("component"); #endregion reportingParameters component #region measure component _w.WriteComment("Measures Component"); Start("component"); Start("section"); //structuredBody[component[section(reportingParameters)]][component2[section(measureSection)]]] _w.WriteComment("Measure Section Template"); TemplateId("2.16.840.1.113883.10.20.24.2.2"); _w.WriteComment("QRDA Category III Measure Section Template"); TemplateId("2.16.840.1.113883.10.20.27.2.1"); StartAndEnd("code","code","55186-1","displayName","Measure Section","codeSystem",strCodeSystemLoinc,"codeSystemName",strCodeSystemNameLoinc); _w.WriteElementString("title","Measure Section"); #region TEXT SECTION Start("text"); List<Dictionary<string,int>> listPopCountDicts=new List<Dictionary<string,int>>(); //get the indexes of the three stratifications int s1Indx=(int)QualityType2014.CariesPrevent_1; int s2Indx=(int)QualityType2014.CariesPrevent_2; int s3Indx=(int)QualityType2014.CariesPrevent_3; //get the index of the WeightAdult (population 2) int pop2Indx=(int)QualityType2014.WeightAdult; //get the indexes of the additional two numerators and 2 stratifications int numer2=(int)QualityType2014.WeightChild_1_2; int numer3=(int)QualityType2014.WeightChild_1_3; int s1numer1Indx=(int)QualityType2014.WeightChild_2_1; int s1numer2Indx=(int)QualityType2014.WeightChild_2_2; int s1numer3Indx=(int)QualityType2014.WeightChild_2_3; int s2numer1Indx=(int)QualityType2014.WeightChild_3_1; int s2numer2Indx=(int)QualityType2014.WeightChild_3_2; int s2numer3Indx=(int)QualityType2014.WeightChild_3_3; int numPops=1;//if set to two or three, this will generate additional sets of population data (measure 69 has two populations, measure 155 has 3 numerators) for(int i=0;i<listQMs.Count;i++) { //_listExtraPopIndxs will contain all of the Type2014 enum types that are stratifications or extra populations of other measures, so skip them here if(_listExtraPopIndxs.Contains(i)) { continue; } switch(i) { case (int)QualityType2014.WeightOver65: //this wil create 2 populations, one for weight ages 18-64 and one for weight 65+ numPops=2; break; case (int)QualityType2014.WeightChild_1_1: //this will create 3 data sections, one for each numerator //We will have Numerator 1 with ipp,denom,except,exclus,numer data, Numerator 2 data, and Numerator 3 data, each with their own stratifications numPops=3; break; } if(listQMs[i].Type2014==QualityType2014.MedicationsEntered) { listPopCountDicts=FillDictPopCounts(listQMs[i].ListEhrPats,listQMs[i].DictPatNumListEncounters); } else { listPopCountDicts=FillDictPopCounts(listQMs[i].ListEhrPats,null); } Start("table","border","1","width","100%"); Start("thead"); Start("tr"); _w.WriteElementString("th","eMeasure Identifier (MAT)"); _w.WriteElementString("th","eMeasure Title"); _w.WriteElementString("th","Version neutral identifier"); _w.WriteElementString("th","eMeasure Version Number"); _w.WriteElementString("th","Version specific identifier"); End("tr"); End("thead"); Start("tbody"); MeasureTextTableRow(listQMs[i].eMeasureTitle,listQMs[i].eMeasureNum,listQMs[i].eMeasureVNeutralId,listQMs[i].eMeasureVersion,listQMs[i].eMeasureVSpecificId); End("tbody"); End("table"); for(int p=0;p<numPops;p++) {//usually only runs 1 loop, measure 69 has two populations, and measure 155 has 3 numerators, in which case it will run more than once int measureIndx=i; if(numPops==2) { if(p==0) { StartAndEnd("br"); } Start("content","styleCode","Bold"); _w.WriteString("Population "+(p+1).ToString()+":"); End("content"); if(p>0) {//fill stratification data with supplemental data from other population (only used by measure 69) measureIndx=pop2Indx; listPopCountDicts=FillDictPopCounts(listQMs[measureIndx].ListEhrPats,null); } } else if(numPops==3) { if(p==0) { StartAndEnd("br"); } Start("content","styleCode","Bold"); _w.WriteString("Numerator "+(p+1).ToString()+":"); End("content"); if(p==1) {//second iteration, fill dictionaries with numerator 2 data for stratifications measureIndx=numer2; listPopCountDicts=FillDictPopCounts(listQMs[measureIndx].ListEhrPats,null); } if(p==2) {//third iteration, fill dictionaries with numerator 3 data for stratifications measureIndx=numer3; listPopCountDicts=FillDictPopCounts(listQMs[measureIndx].ListEhrPats,null); } } Start("list"); #region Performeance and Reporting Rate TEXT VERSION Start("item"); Start("content","styleCode","Bold"); _w.WriteString("Performance Rate"); End("content"); if(listQMs[measureIndx].ListEhrPats.Count==0) { _w.WriteString(": NA"); } else { _w.WriteString(": "+listQMs[measureIndx].PerformanceRate.ToString("0.00")+"%"); } End("item"); Start("item"); Start("content","styleCode","Bold"); _w.WriteString("Reporting Rate"); End("content"); if(listQMs[measureIndx].ListEhrPats.Count==0) { _w.WriteString(": NA"); } else { _w.WriteString(": "+listQMs[measureIndx].ReportingRate.ToString("0.00")+"%"); } End("item"); #endregion Performeance and Reporting Rate TEXT VERSION #region IPP TEXT VERSION //Start Initial Patient Population text Start("item"); Start("content","styleCode","Bold"); _w.WriteString("Initial Patient Population"); End("content"); _w.WriteString(": "+listPopCountDicts[0]["All"].ToString()); if(listPopCountDicts[0]["All"]>0) { Start("list"); #region Stratification if(i==(int)QualityType2014.CariesPrevent || i==(int)QualityType2014.WeightChild_1_1) { Start("item"); Start("content","styleCode","Bold"); _w.WriteString("Reporting Stratum 1"); End("content"); if(p==0) { if(i==(int)QualityType2014.CariesPrevent) { _w.WriteString(": "+listQMs[s1Indx].ListEhrPats.Count.ToString()); } else { _w.WriteString(": "+listQMs[s1numer1Indx].ListEhrPats.Count.ToString()); } } else if(p==1) { _w.WriteString(": "+listQMs[s1numer2Indx].ListEhrPats.Count.ToString()); } else if(p==2) { _w.WriteString(": "+listQMs[s1numer3Indx].ListEhrPats.Count.ToString()); } End("item"); } if(i==(int)QualityType2014.CariesPrevent || i==(int)QualityType2014.WeightChild_1_1) { Start("item"); Start("content","styleCode","Bold"); _w.WriteString("Reporting Stratum 2"); End("content"); if(p==0) { if(i==(int)QualityType2014.CariesPrevent) { _w.WriteString(": "+listQMs[s2Indx].ListEhrPats.Count.ToString()); } else { _w.WriteString(": "+listQMs[s2numer1Indx].ListEhrPats.Count.ToString()); } } else if(p==1) { _w.WriteString(": "+listQMs[s2numer2Indx].ListEhrPats.Count.ToString()); } else if(p==2) { _w.WriteString(": "+listQMs[s2numer3Indx].ListEhrPats.Count.ToString()); } End("item"); } if(p==0 && i==(int)QualityType2014.CariesPrevent) { Start("item"); Start("content","styleCode","Bold"); _w.WriteString("Reporting Stratum 3"); End("content"); _w.WriteString(": "+listQMs[s3Indx].ListEhrPats.Count.ToString()); End("item"); } #endregion foreach(KeyValuePair<string,int> kvpair in listPopCountDicts[0]) { if(kvpair.Value==0 || kvpair.Key=="All") { continue; } Start("item"); Start("content","styleCode","Bold"); _w.WriteString(GetSupplementDataPrintString(kvpair.Key)); End("content"); _w.WriteString(": "+kvpair.Value.ToString()); End("item"); } End("list"); } End("item"); #endregion IPP TEXT VERSION #region DENOM TEXT VERSION //Start Denominator text Start("item"); Start("content","styleCode","Bold"); _w.WriteString("Denominator"); End("content"); _w.WriteString(": "+listPopCountDicts[1]["All"]); if(listPopCountDicts[1]["All"]>0) { Start("list"); #region Stratification if(i==(int)QualityType2014.CariesPrevent || i==(int)QualityType2014.WeightChild_1_1) { Start("item"); Start("content","styleCode","Bold"); _w.WriteString("Reporting Stratum 1"); End("content"); if(p==0) { if(i==(int)QualityType2014.CariesPrevent) { _w.WriteString(": "+listQMs[s1Indx].Denominator.ToString()); } else { _w.WriteString(": "+listQMs[s1numer1Indx].Denominator.ToString()); } } else if(p==1) { _w.WriteString(": "+listQMs[s1numer2Indx].Denominator.ToString()); } else if(p==2) { _w.WriteString(": "+listQMs[s1numer3Indx].Denominator.ToString()); } End("item"); } if(i==(int)QualityType2014.CariesPrevent || i==(int)QualityType2014.WeightChild_1_1) { Start("item"); Start("content","styleCode","Bold"); _w.WriteString("Reporting Stratum 2"); End("content"); if(p==0) { if(i==(int)QualityType2014.CariesPrevent) { _w.WriteString(": "+listQMs[s2Indx].Denominator.ToString()); } else { _w.WriteString(": "+listQMs[s2numer1Indx].Denominator.ToString()); } } else if(p==1) { _w.WriteString(": "+listQMs[s2numer2Indx].Denominator.ToString()); } else if(p==2) { _w.WriteString(": "+listQMs[s2numer3Indx].Denominator.ToString()); } End("item"); } if(p==0 && i==(int)QualityType2014.CariesPrevent) { Start("item"); Start("content","styleCode","Bold"); _w.WriteString("Reporting Stratum 3"); End("content"); _w.WriteString(": "+listQMs[s3Indx].Denominator.ToString()); End("item"); } #endregion foreach(KeyValuePair<string,int> kvpair in listPopCountDicts[1]) { if(kvpair.Value==0 || kvpair.Key=="All") { continue; } Start("item"); Start("content","styleCode","Bold"); _w.WriteString(GetSupplementDataPrintString(kvpair.Key)); End("content"); _w.WriteString(": "+kvpair.Value.ToString()); End("item"); } End("list"); } End("item"); #endregion DENOM TEXT VERSION #region DENEXCL TEXT VERSION //Start Denominator Exclusion text Start("item"); Start("content","styleCode","Bold"); _w.WriteString("Denominator Exclusion"); End("content"); _w.WriteString(": "+listPopCountDicts[2]["All"].ToString()); if(listPopCountDicts[2]["All"]>0) { Start("list"); #region Stratification if(i==(int)QualityType2014.CariesPrevent || i==(int)QualityType2014.WeightChild_1_1) { Start("item"); Start("content","styleCode","Bold"); _w.WriteString("Reporting Stratum 1"); End("content"); if(p==0) { if(i==(int)QualityType2014.CariesPrevent) { _w.WriteString(": "+listQMs[s1Indx].Exclusions.ToString()); } else { _w.WriteString(": "+listQMs[s1numer1Indx].Exclusions.ToString()); } } else if(p==1) { _w.WriteString(": "+listQMs[s1numer2Indx].Exclusions.ToString()); } else if(p==2) { _w.WriteString(": "+listQMs[s1numer3Indx].Exclusions.ToString()); } End("item"); } if(i==(int)QualityType2014.CariesPrevent || i==(int)QualityType2014.WeightChild_1_1) { Start("item"); Start("content","styleCode","Bold"); _w.WriteString("Reporting Stratum 2"); End("content"); if(p==0) { if(i==(int)QualityType2014.CariesPrevent) { _w.WriteString(": "+listQMs[s2Indx].Exclusions.ToString()); } else { _w.WriteString(": "+listQMs[s2numer1Indx].Exclusions.ToString()); } } else if(p==1) { _w.WriteString(": "+listQMs[s2numer2Indx].Exclusions.ToString()); } else if(p==2) { _w.WriteString(": "+listQMs[s2numer3Indx].Exclusions.ToString()); } End("item"); } if(p==0 && i==(int)QualityType2014.CariesPrevent) { Start("item"); Start("content","styleCode","Bold"); _w.WriteString("Reporting Stratum 3"); End("content"); _w.WriteString(": "+listQMs[s3Indx].Exclusions.ToString()); End("item"); } #endregion foreach(KeyValuePair<string,int> kvpair in listPopCountDicts[2]) { if(kvpair.Value==0 || kvpair.Key=="All") { continue; } Start("item"); Start("content","styleCode","Bold"); _w.WriteString(GetSupplementDataPrintString(kvpair.Key)); End("content"); _w.WriteString(": "+kvpair.Value.ToString()); End("item"); } End("list"); } End("item"); #endregion DENEXCL TEXT VERSION #region NUMER TEXT VERSION //Start Numerator text Start("item"); Start("content","styleCode","Bold"); _w.WriteString("Numerator"); End("content"); _w.WriteString(": "+listPopCountDicts[3]["All"].ToString()); if(listPopCountDicts[3]["All"]>0) { Start("list"); #region Stratification if(i==(int)QualityType2014.CariesPrevent || i==(int)QualityType2014.WeightChild_1_1) { Start("item"); Start("content","styleCode","Bold"); _w.WriteString("Reporting Stratum 1"); End("content"); if(p==0) { if(i==(int)QualityType2014.CariesPrevent) { _w.WriteString(": "+listQMs[s1Indx].Numerator.ToString()); } else { _w.WriteString(": "+listQMs[s1numer1Indx].Numerator.ToString()); } } else if(p==1) { _w.WriteString(": "+listQMs[s1numer2Indx].Numerator.ToString()); } else if(p==2) { _w.WriteString(": "+listQMs[s1numer3Indx].Numerator.ToString()); } End("item"); } if(i==(int)QualityType2014.CariesPrevent || i==(int)QualityType2014.WeightChild_1_1) { Start("item"); Start("content","styleCode","Bold"); _w.WriteString("Reporting Stratum 2"); End("content"); if(p==0) { if(i==(int)QualityType2014.CariesPrevent) { _w.WriteString(": "+listQMs[s2Indx].Numerator.ToString()); } else { _w.WriteString(": "+listQMs[s2numer1Indx].Numerator.ToString()); } } else if(p==1) { _w.WriteString(": "+listQMs[s2numer2Indx].Numerator.ToString()); } else if(p==2) { _w.WriteString(": "+listQMs[s2numer3Indx].Numerator.ToString()); } End("item"); } if(p==0 && i==(int)QualityType2014.CariesPrevent) { Start("item"); Start("content","styleCode","Bold"); _w.WriteString("Reporting Stratum 3"); End("content"); _w.WriteString(": "+listQMs[s3Indx].Numerator.ToString()); End("item"); } #endregion foreach(KeyValuePair<string,int> kvpair in listPopCountDicts[3]) { if(kvpair.Value==0 || kvpair.Key=="All") { continue; } Start("item"); Start("content","styleCode","Bold"); _w.WriteString(GetSupplementDataPrintString(kvpair.Key)); End("content"); _w.WriteString(": "+kvpair.Value.ToString()); End("item"); } End("list"); } End("item"); #endregion NUMER TEXT VERSION #region DENEXCEP TEXT VERSION //Start Denominator Exception text Start("item"); Start("content","styleCode","Bold"); _w.WriteString("Denominator Exception"); End("content"); _w.WriteString(": "+listPopCountDicts[4]["All"].ToString()); if(listPopCountDicts[4]["All"]>0) { Start("list"); #region Stratification if(i==(int)QualityType2014.CariesPrevent || i==(int)QualityType2014.WeightChild_1_1) { Start("item"); Start("content","styleCode","Bold"); _w.WriteString("Reporting Stratum 1"); End("content"); if(p==0) { if(i==(int)QualityType2014.CariesPrevent) { _w.WriteString(": "+listQMs[s1Indx].Exceptions.ToString()); } else { _w.WriteString(": "+listQMs[s1numer1Indx].Exceptions.ToString()); } } else if(p==1) { _w.WriteString(": "+listQMs[s1numer2Indx].Exceptions.ToString()); } else if(p==2) { _w.WriteString(": "+listQMs[s1numer3Indx].Exceptions.ToString()); } End("item"); } if(i==(int)QualityType2014.CariesPrevent || i==(int)QualityType2014.WeightChild_1_1) { Start("item"); Start("content","styleCode","Bold"); _w.WriteString("Reporting Stratum 2"); End("content"); if(p==0) { if(i==(int)QualityType2014.CariesPrevent) { _w.WriteString(": "+listQMs[s2Indx].Exceptions.ToString()); } else { _w.WriteString(": "+listQMs[s2numer1Indx].Exceptions.ToString()); } } else if(p==1) { _w.WriteString(": "+listQMs[s2numer2Indx].Exceptions.ToString()); } else if(p==2) { _w.WriteString(": "+listQMs[s2numer3Indx].Exceptions.ToString()); } End("item"); } if(p==0 && i==(int)QualityType2014.CariesPrevent) { Start("item"); Start("content","styleCode","Bold"); _w.WriteString("Reporting Stratum 3"); End("content"); _w.WriteString(": "+listQMs[s3Indx].Exceptions.ToString()); End("item"); } #endregion foreach(KeyValuePair<string,int> kvpair in listPopCountDicts[4]) { if(kvpair.Value==0 || kvpair.Key=="All") { continue; } Start("item"); Start("content","styleCode","Bold"); _w.WriteString(GetSupplementDataPrintString(kvpair.Key)); End("content"); _w.WriteString(": "+kvpair.Value.ToString()); End("item"); } End("list"); } End("item"); #endregion DENEXCEP TEXT VERSION End("list"); } } End("text"); #endregion TEXT SECTION #region ENTRY SECTION for(int i=0;i<listQMs.Count;i++) { //_listExtraPopIndxs will contain all of the Type2014 enum types that are stratifications or extra populations of other measures, so skip them here if(_listExtraPopIndxs.Contains(i)) { continue; } switch(i) { case (int)QualityType2014.WeightOver65: //this wil create 2 populations, one for weight ages 18-64 and one for weight 65+ numPops=2; break; case (int)QualityType2014.WeightChild_1_1: //this will create 3 data sections, one for each numerator //We will have Numerator 1 with ipp,denom,except,exclus,numer data, Numerator 2 data, and Numerator 3 data, each with their own stratifications numPops=3; break; } if(listQMs[i].Type2014==QualityType2014.MedicationsEntered) { listPopCountDicts=FillDictPopCounts(listQMs[i].ListEhrPats,listQMs[i].DictPatNumListEncounters); } else { listPopCountDicts=FillDictPopCounts(listQMs[i].ListEhrPats,null); } _w.WriteComment("***************PROPORTION MEASURE ENTRIES (1 entry per population per measure)***************"); for(int p=0;p<numPops;p++) {//usually only runs 1 loop, measure 69 has two populations, and measure 155 has 3 numerators, in which case it will run more than once int measureIndx=i; if(numPops==2 && p>0) {//fill stratification data with supplemental data from other population measureIndx=pop2Indx; listPopCountDicts=FillDictPopCounts(listQMs[measureIndx].ListEhrPats,null); } if(numPops==3 && p>0) {//only 3 populations for measure 155, Numerators 1-3 if(p==1) {//second iteration, fill dictionaries with numerator 2 data for stratifications measureIndx=numer2; listPopCountDicts=FillDictPopCounts(listQMs[measureIndx].ListEhrPats,null); } if(p==2) {//third iteration, fill dictionaries with numerator 3 data for stratifications measureIndx=numer3; listPopCountDicts=FillDictPopCounts(listQMs[measureIndx].ListEhrPats,null); } } Start("entry"); #region Measure Reference //start of Measure Reference and Results entries (measureSection)section[entry 1..*] Start("organizer","classCode","CLUSTER","moodCode","EVN"); _w.WriteComment("Measure Reference Template"); TemplateId("2.16.840.1.113883.10.20.24.3.98"); _w.WriteComment("Measure Reference and Results Template"); TemplateId("2.16.840.1.113883.10.20.27.3.1"); StartAndEnd("statusCode","code","completed"); Start("reference","typeCode","REFR"); Start("externalDocument","classCode","DOC","moodCode","EVN"); StartAndEnd("id","root",listQMs[measureIndx].eMeasureVSpecificId);//version specific id StartAndEnd("code","code","57024-2","displayName","Health Quality Measure Document","codeSystem",strCodeSystemLoinc,"codeSystemName",strCodeSystemNameLoinc); _w.WriteElementString("text",listQMs[measureIndx].eMeasureTitle); StartAndEnd("setId","root",listQMs[measureIndx].eMeasureVNeutralId);//version neutral id StartAndEnd("versionNumber","value",listQMs[measureIndx].eMeasureVersion); End("externalDocument"); End("reference"); Start("reference","typeCode","REFR"); Start("externalObservation"); StartAndEnd("id","root",listQMs[measureIndx].eMeasureSetId); StartAndEnd("code","code","55185-3","displayName","measure set","codeSystem",strCodeSystemLoinc,"codeSystemName",strCodeSystemNameLoinc); if(listQMs[measureIndx].Type2014==QualityType2014.MedicationsEntered) {//Measure 68 is the only one with a title that is not "None" or "NA" _w.WriteElementString("text","CLINICAL QUALITY MEASURE SET 2014"); } else if(listQMs[measureIndx].Type2014==QualityType2014.CariesPrevent || listQMs[measureIndx].Type2014==QualityType2014.ChildCaries) { _w.WriteElementString("text","Not Applicable"); } else { _w.WriteElementString("text","None"); } End("externalObservation"); End("reference"); #endregion Measure Reference #region Performance Rate Component _w.WriteComment("***************Performance Rate 1 per entry (entry=Measure or Population within a measure)***************"); Start("component"); //Performance rate=Numerator/(Denominator-Exclusions-Exceptions) Start("observation","classCode","OBS","moodCode","EVN"); _w.WriteComment("Performance Rate for Proportion Measure Template"); TemplateId("2.16.840.1.113883.10.20.27.3.14"); StartAndEnd("code","code","72510-1","displayName","Performance Rate","codeSystem",strCodeSystemLoinc,"codeSystemName",strCodeSystemNameLoinc); StartAndEnd("statusCode","code","completed"); Start("value"); _w.WriteAttributeString("xsi","type",null,"REAL"); if(listQMs[measureIndx].PerformanceRate==0) { Attribs("nullFlavor","NA");//if no patients in denominator, then performance rate is null } else { Attribs("value",listQMs[measureIndx].PerformanceRate.ToString("0.00")); } End("value"); End("observation"); End("component"); #endregion Performance Rate Component #region Reporting Rate Component _w.WriteComment("***************Reporting Rate 1 per entry (entry=Measure or Population within a measure)***************"); Start("component"); //Reporting rate=(Numerator+Exclusions+Exceptions)/Denominator Start("observation","classCode","OBS","moodCode","EVN"); _w.WriteComment("Reporting Rate for Proportion Measure Template"); TemplateId("2.16.840.1.113883.10.20.27.3.15"); StartAndEnd("code","code","72509-3","displayName","Reporting Rate","codeSystem",strCodeSystemLoinc,"codeSystemName",strCodeSystemNameLoinc); StartAndEnd("statusCode","code","completed"); Start("value"); _w.WriteAttributeString("xsi","type",null,"REAL"); if(listQMs[measureIndx].PerformanceRate==0) { Attribs("nullFlavor","NA");//if no patients in denominator, then reporting rate is null } else { Attribs("value",listQMs[measureIndx].ReportingRate.ToString("0.00")); } End("value"); End("observation"); End("component"); #endregion Reporting Rate Component //***************************************MEASURE DATA COMPONENTS******************************* _w.WriteComment("***************Measure Data component entries (1..*) represent aggregate counts IPP,DENOM,DENEX,DENEXCEP,NUMER***************"); #region Measure Data for(int j=0;j<listPopCountDicts.Count;j++) { switch(j) { case 0: _w.WriteComment("Initial Patient Population component"); break; case 1: _w.WriteComment("Denominator component"); break; case 2: if(listQMs[measureIndx].eMeasureDenexId=="") {//if no exclusions defined for this measure, continue continue; } _w.WriteComment("Denominator Exclusion component"); break; case 3: _w.WriteComment("Numerator component"); break; case 4: if(listQMs[measureIndx].eMeasureDenexcepId=="") {//if no exceptions defined for this measure, continue continue; } _w.WriteComment("Denominator Exception component"); break; default: throw new ApplicationException("Error in creating QRDA Category III in Measure Data Components section."); } Start("component"); Start("observation","classCode","OBS","moodCode","EVN"); _w.WriteComment("Measure Data Template"); TemplateId("2.16.840.1.113883.10.20.27.3.5"); StartAndEnd("code","code","ASSERTION","displayName","Assertion","codeSystem","2.16.840.1.113883.5.4","codeSystemName","ActCode"); StartAndEnd("statusCode","code","completed"); Start("value"); _w.WriteAttributeString("xsi","type",null,"CD"); switch(j) { case 0: Attribs("code","IPP","displayName","Initial Patient Population"); break; case 1: Attribs("code","DENOM","displayName","Denominator"); break; case 2: Attribs("code","DENEX","displayName","Denominator Exclusions"); break; case 3: Attribs("code","NUMER","displayName","Numerator"); break; case 4: Attribs("code","DENEXCEP","displayName","Denominator Exceptions"); break; default: throw new ApplicationException("Error in creating QRDA Category III in Measure Data Components section."); } Attribs("codeSystem","2.16.840.1.113883.5.1063","codeSystemName","ObservationValue"); End("value"); #region Measure Count entry //*************Aggregate count entry************** _w.WriteComment("Aggregate Count entryRelationship"); Start("entryRelationship","typeCode","SUBJ","inversionInd","true"); Start("observation","classCode","OBS","moodCode","EVN"); _w.WriteComment("Aggregate Count Template"); TemplateId("2.16.840.1.113883.10.20.27.3.3"); StartAndEnd("code","code","MSRAGG","displayName","rate aggregation","codeSystem","2.16.840.1.113883.5.4","codeSystemName","ActCode"); Start("value"); _w.WriteAttributeString("xsi","type",null,"INT"); Attribs("value",listPopCountDicts[j]["All"].ToString()); End("value"); StartAndEnd("methodCode","code","COUNT","displayName","Count","codeSystem","2.16.840.1.113883.5.84","codeSystemName","ObservationMethod"); End("observation"); End("entryRelationship"); #endregion Measure Count entry #region Stratification entries //**************Reporting Stratum entryRelationship************** //Measure 155 (wight counseling child) has two Strata, Measure 74 (primary caries prevention) has three Strata int iterations=0; if(i==(int)QualityType2014.CariesPrevent) { iterations=3; } else if(i==(int)QualityType2014.WeightChild_1_1) { iterations=2; } //most measures do not have strata, so these entryRelationships will not usually be created. Only Measure 155 and 74 have stratification items. for(int s=0;s<iterations;s++) { _w.WriteComment("***************Reporting Stratum entry***************"); Start("entryRelationship","typeCode","COMP"); Start("observation","classCode","OBS","moodCode","EVN"); _w.WriteComment("Reporting Stratum Template"); TemplateId("2.16.840.1.113883.10.20.27.3.4"); StartAndEnd("code","code","ASSERTION","displayName","Assertion","codeSystem","2.16.840.1.113883.5.4","codeSystemName","ActCode"); StartAndEnd("statusCode","code","completed"); Start("value"); _w.WriteAttributeString("xsi","type",null,"CD"); Attribs("nullFlavor","OTH"); End("value"); _w.WriteComment("Stratum"); Start("entryRelationship","typeCode","SUBJ","inversionInd","true"); Start("observation","classCode","OBS","moodCode","EVN"); _w.WriteComment("Aggregate Count Template"); TemplateId("2.16.840.1.113883.10.20.27.3.3"); StartAndEnd("code","code","MSRAGG","displayName","rate aggregation","codeSystem","2.16.840.1.113883.5.4","codeSystemName","ActCode"); Start("value"); _w.WriteAttributeString("xsi","type",null,"INT"); int stratIndx=0; if(i==(int)QualityType2014.CariesPrevent) { if(s==0) {//first strata stratIndx=s1Indx; } if(s==1) {//second strata stratIndx=s2Indx; } if(s==2) {//third strata stratIndx=s3Indx; } } else if(i==(int)QualityType2014.WeightChild_1_1) { if(p==0) { if(s==0) {//second numerator stratIndx=s1numer1Indx; } if(s==1) {//third numerator stratIndx=s2numer1Indx; } } if(p==1) { if(s==0) {//first strata, second numerator stratIndx=s1numer2Indx; } if(s==1) {//second strata, second population stratIndx=s2numer2Indx; } } if(p==2) { if(s==0) {//first strata, third population stratIndx=s1numer3Indx; } if(s==1) {//second strata, third population stratIndx=s2numer3Indx; } } } switch(j) { case 0: Attribs("value",listQMs[stratIndx].ListEhrPats.Count.ToString()); break; case 1: Attribs("value",listQMs[stratIndx].Denominator.ToString()); break; case 2: Attribs("value",listQMs[stratIndx].Exclusions.ToString()); break; case 3: Attribs("value",listQMs[stratIndx].Numerator.ToString()); break; case 4: Attribs("value",listQMs[stratIndx].Exceptions.ToString()); break; } End("value"); StartAndEnd("methodCode","code","COUNT","displayName","Count","codeSystem","2.16.840.1.113883.5.84","codeSystemName","ObservationMethod"); End("observation"); End("entryRelationship"); //end of aggregate count //Start reference to strata in eMeasure Start("reference","typeCode","REFR"); _w.WriteComment("Reference to the relevant strata in the eMeasure"); Start("externalObservation","classCode","OBS","moodCode","EVN"); switch(j) { case 0: StartAndEnd("id","root",listQMs[stratIndx].eMeasureIppId); break; case 1: StartAndEnd("id","root",listQMs[stratIndx].eMeasureDenomId); break; case 2: StartAndEnd("id","root",listQMs[stratIndx].eMeasureDenexId); break; case 3: StartAndEnd("id","root",listQMs[stratIndx].eMeasureNumerId); break; case 4: StartAndEnd("id","root",listQMs[stratIndx].eMeasureDenexcepId); break; } End("externalObservation"); End("reference"); //end of reference to eMeasure End("observation"); End("entryRelationship"); } #endregion Stratification entries #region SUPPLEMENTAL DATA STRATUM //loop through each of the population counts for this population and generate relevant supplemental data entries foreach(KeyValuePair<string,int> kvpair in listPopCountDicts[j]) { if(kvpair.Key=="All" && kvpair.Value==0) {//do not need to have these supplemental data entries if no initial patient population, break out of loop break; } if(kvpair.Value==0 || kvpair.Key=="All") { continue; } switch(kvpair.Key) { case "Male": case "Female": case "Unknown": //**************Sex Supplemental Data entry************** #region Sex Supplemental Data Entry _w.WriteComment("Sex Supplemental Data entryRelationship"); Start("entryRelationship","typeCode","COMP"); Start("observation","classCode","OBS","moodCode","EVN"); _w.WriteComment("Sex Supplemental Data Element Template"); TemplateId("2.16.840.1.113883.10.20.27.3.6"); StartAndEnd("code","code","184100006","displayName","Patient sex","codeSystem",strCodeSystemSnomed,"codeSystemName",strCodeSystemNameSnomed); StartAndEnd("statusCode","code","completed"); Start("value"); _w.WriteAttributeString("xsi","type",null,"CD"); if(kvpair.Key==PatientGender.Male.ToString()) { Attribs("code","M","displayName","Male"); } else if(kvpair.Key==PatientGender.Female.ToString()) { Attribs("code","F","displayName","Female"); } else { Attribs("code","UN","displayName","Undifferentiated"); } Attribs("codeSystem","2.16.840.1.113883.5.1","codeSystemName","AdministrativeGender"); End("value"); #endregion Sex Supplemental Data Entry break; case "Hispanic": case "NotHispanic": //**************Ethnicity Supplemental Data************** #region Ethnicity Supplemental Data Entry _w.WriteComment("Ethnicity Supplemental Data entryRelationship"); Start("entryRelationship","typeCode","COMP"); Start("observation","classCode","OBS","moodCode","EVN"); _w.WriteComment("Ethnicity Supplemental Data Element Template"); TemplateId("2.16.840.1.113883.10.20.27.3.7"); StartAndEnd("code","code","364699009","displayName","Ethnic Group","codeSystem",strCodeSystemSnomed,"codeSystemName",strCodeSystemNameSnomed); StartAndEnd("statusCode","code","completed"); Start("value"); _w.WriteAttributeString("xsi","type",null,"CD"); if(kvpair.Key==PatRace.Hispanic.ToString()) { Attribs("code","2135-2","displayName","Hispanic or Latino"); } else if(kvpair.Key==PatRace.NotHispanic.ToString()) { Attribs("code","2186-5","displayName","Not Hispanic or Latino"); } Attribs("codeSystem","2.16.840.1.113883.6.238","codeSystemName","Race & Ethnicity - CDC"); End("value"); #endregion Ethnicity Supplemental Data Entry break; case "AfricanAmerican": case "AmericanIndian": case "Asian": case "White": case "HawaiiOrPacIsland": case "Other": //**************Race Supplemental Data************** #region Race Supplemental Data Entry _w.WriteComment("Race Supplemental Data entryRelationship"); Start("entryRelationship","typeCode","COMP"); Start("observation","classCode","OBS","moodCode","EVN"); _w.WriteComment("Race Supplemental Data Element Template"); TemplateId("2.16.840.1.113883.10.20.27.3.8"); StartAndEnd("code","code","103579009","displayName","Race","codeSystem",strCodeSystemSnomed,"codeSystemName",strCodeSystemNameSnomed); StartAndEnd("statusCode","code","completed"); Start("value"); _w.WriteAttributeString("xsi","type",null,"CD"); if(kvpair.Key==PatRace.AfricanAmerican.ToString()) { Attribs("code","2054-5","displayName","Black or African American"); } else if(kvpair.Key==PatRace.AmericanIndian.ToString()) { Attribs("code","1002-5","displayName","American Indian or Alaska Native"); } else if(kvpair.Key==PatRace.Asian.ToString()) { Attribs("code","2028-9","displayName","Asian"); } else if(kvpair.Key==PatRace.White.ToString()) { Attribs("code","2131-1","displayName","White"); } else if(kvpair.Key==PatRace.HawaiiOrPacIsland.ToString()) { Attribs("code","2076-8","displayName","Native Hawaiian or Other Pacific Islander"); } else if(kvpair.Key==PatRace.Other.ToString()) { Attribs("code","2106-3","displayName","Other Race"); } Attribs("codeSystem","2.16.840.1.113883.6.238","codeSystemName","Race & Ethnicity - CDC"); End("value"); #endregion Race Supplemental Data Entry break; case "Medicare": case "Medicaid": case "Other Gvmt": case "Private": case "Self-pay": //**************Payer Supplemental Data************** #region Payer Supplemental Data Entry _w.WriteComment("Payer Supplemental Data entryRelationship"); Start("entryRelationship","typeCode","COMP"); Start("observation","classCode","OBS","moodCode","EVN"); _w.WriteComment("Patient Characteristic Payer Template"); TemplateId("2.16.840.1.113883.10.20.24.3.55"); _w.WriteComment("Payer Supplemental Data Element Template"); TemplateId("2.16.840.1.113883.10.20.27.3.9"); Guid(); StartAndEnd("code","code","48768-6","displayName","Payment source","codeSystem",strCodeSystemLoinc,"codeSystemName",strCodeSystemNameLoinc); StartAndEnd("statusCode","code","completed"); Start("value"); _w.WriteAttributeString("xsi","type",null,"CD"); if(kvpair.Key=="Medicare") { Attribs("code","1","displayName","Medicare"); } else if(kvpair.Key=="Medicaid") { Attribs("code","2","displayName","Medicaid"); } else if(kvpair.Key=="Other Gvmt") { Attribs("code","349","displayName","Other Government (Federal/State/Local) (excluding Department of Corrections)"); } else if(kvpair.Key=="Private") { Attribs("code","5","displayName","Private Health Insurance"); } else { Attribs("code","8","displayName","No Payment from an Organization/Agency/Program/Private Payer Listed"); } Attribs("codeSystem","2.16.840.1.113883.3.221.5","codeSystemName","Source of Payment Typology"); End("value"); #endregion Payer Supplemental Data Entry break; default: throw new ApplicationException("Error in creating QRDA Category III in Measure Data Components section."); } _w.WriteComment("Aggregate Count entryRelationship"); Start("entryRelationship","typeCode","SUBJ","inversionInd","true"); _w.WriteComment("Aggregate Count Template"); Start("observation","classCode","OBS","moodCode","EVN"); TemplateId("2.16.840.1.113883.10.20.27.3.3"); StartAndEnd("code","code","MSRAGG","displayName","rate aggregation","codeSystem","2.16.840.1.113883.5.4","codeSystemName","ActCode"); Start("value"); _w.WriteAttributeString("xsi","type",null,"INT"); Attribs("value",kvpair.Value.ToString()); End("value"); StartAndEnd("methodCode","code","COUNT","displayName","Count","codeSystem","2.16.840.1.113883.5.84","codeSystemName","ObservationMethod"); End("observation"); End("entryRelationship"); End("observation"); End("entryRelationship"); } #endregion SUPPLEMENTAL DATA STRATUM //*************eMeasure Reference************** _w.WriteComment("eMeasure reference"); Start("reference","typeCode","REFR"); Start("externalObservation","classCode","OBS","moodCode","EVN"); switch(j) { case 0: StartAndEnd("id","root",listQMs[measureIndx].eMeasureIppId); break; case 1: StartAndEnd("id","root",listQMs[measureIndx].eMeasureDenomId); break; case 2: StartAndEnd("id","root",listQMs[measureIndx].eMeasureDenexId); break; case 3: StartAndEnd("id","root",listQMs[measureIndx].eMeasureNumerId); break; case 4: StartAndEnd("id","root",listQMs[measureIndx].eMeasureDenexcepId); break; } End("externalObservation"); End("reference"); End("observation"); End("component"); } #endregion Measure Data End("organizer"); End("entry"); } } End("section"); #endregion ENTRY SECTION End("component"); #endregion measure component End("structuredBody"); End("component"); #endregion QRDA III Body End("ClinicalDocument"); _w.Flush(); _w.Close(); } }
public void CreateNewConfigFile() { _logger.LogMessage("Generating new config file..."); ResultConsole.Instance.AddConsoleLine("Generating new config file..."); #region Document Creation try { XmlWriterSettings _xsets = new XmlWriterSettings(); _logger.LogMessage("Configuration file encoding set to UTF8."); _xsets.Encoding = Encoding.UTF8; _xsets.Indent = true; _xwriter = XmlWriter.Create(_configFilePath, _xsets); _xwriter.WriteStartDocument(); _xwriter.WriteStartElement("config"); //Program Settings Category _xwriter.WriteStartElement("settings"); CreateUnattributedElement("savefileversion", SaveFileVersion); // Save Offline Computers CreateUnattributedElement("saveofflinecomputers", _saveOfflineComputers.ToString()); // Save Online Computers CreateUnattributedElement("saveonlinecomputers", _saveOnlineComputers.ToString()); // Results Log File Directory CreateUnattributedElement("resultsDirectory", _resultsDirectory); // Components Directory CreateUnattributedElement("componentsDirectory", _componentsDirectory); // Close <settings> _xwriter.WriteEndElement(); // Close <config> _xwriter.WriteEndElement(); // Close file _xwriter.WriteEndDocument(); _xwriter.Close(); _logger.LogMessage("Configuration file generation complete."); ValidateDirectoryExists(_resultsDirectory); ValidateDirectoryExists(_componentsDirectory); } catch (Exception ex) { _logger.LogError("Unable to create configuration file.", ex); ResultConsole.Instance.AddConsoleLine("Exception in " + ex.TargetSite + ": " + ex.InnerException + " - Unable to create configuration file."); } #endregion }
public static void WriteXmlLogEnd(XmlWriter xw) { xw.WriteString("\r\n"); xw.WriteEndDocument(); xw.Close(); }
/// <summary> /// Closes the writer. /// </summary> /// <param name="xmlWriter"> /// The XML writer. /// </param> private static void CloseWriter(XmlWriter xmlWriter) { xmlWriter.WriteEndElement(); // rdf:RDF xmlWriter.WriteEndDocument(); xmlWriter.Close(); }
private void PresetsSaveButton_Click(object sender, EventArgs e) { string Filename = ".\\Preset" + NumberOfSaves; Writer = XmlWriter.Create(Filename); Writer.WriteStartDocument(); foreach (GridCell Cell in Grid) { Writer.WriteStartElement("CELL"); Writer.WriteStartElement("r", "RECORD", "urn:record"); Writer.WriteStartElement("X", ""); Writer.WriteValue(Cell.CellNumberX); Writer.WriteEndElement(); Writer.WriteStartElement("Y", ""); Writer.WriteValue(Cell.CellNumberY); Writer.WriteEndElement(); foreach (Condition Test in Cell.Conditions) { Writer.WriteStartElement("Condition", ""); Writer.WriteString(Test.Conditional); Writer.WriteStartElement("Response", ""); Writer.WriteString(Test.Response); } } Writer.WriteEndDocument(); Writer.Close(); NumberOfSaves++; PresetsComboBox.Items.Add(((object)Filename)); }
private void WriteGpxXml(string fileName) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.Encoding = new UTF8Encoding(false); using (xmlWriter = XmlWriter.Create(fileName, settings)) { xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("gpx", gpxNamespace); xmlWriter.WriteAttributeString("creator", "Purple Pen " + Util.PrettyVersionString(VersionNumber.Current)); xmlWriter.WriteAttributeString("version", "1.1"); xmlWriter.WriteAttributeString("xsi", "schemaLocation", xsiNamespace, gpxNamespace + " " + gpxSchema); WriteMetadata(Path.GetFileName(fileName)); WriteWaypoints(); WriteCourseTracks(); xmlWriter.WriteEndElement(); xmlWriter.Close(); } }
/// <summary> /// Writes the closing xml element and closes the xmltextwriter object /// </summary> /// <param name="xmlTextWriter">opened xml writer object</param> private void closeAbbreviationFile(XmlWriter xmlTextWriter) { try { xmlTextWriter.WriteEndDocument(); xmlTextWriter.Flush(); xmlTextWriter.Close(); } catch (Exception ex) { Log.Debug(ex.ToString()); } }
new public void writeURDF(XmlWriter writer) { writer.WriteStartDocument(); writer.WriteStartElement("robot"); Name.writeURDF(writer); BaseLink.writeURDF(writer); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); }