/// <summary> /// Saves all content to folder hierarchy /// </summary> /// <param name="project"></param> /// <param name="path"></param> public static void Save(DocProject project, string path, Dictionary <string, DocObject> mapEntity, FolderStorageOptions options) { bool bExportSchema = ((options & FolderStorageOptions.Schemas) != 0); bool bExportExchanges = ((options & FolderStorageOptions.Exchanges) != 0); bool bExportExamples = ((options & FolderStorageOptions.Examples) != 0); bool bExportLocalize = ((options & FolderStorageOptions.Localization) != 0); Compiler compiler = new Compiler(project, null, null, false); System.Reflection.Emit.AssemblyBuilder assembly = compiler.Assembly; // -exchanges (or mvd?) // {exchange}.mvdxml - definition // {exchange}.cs - C# partial classes for capturing exchange --- later // templates.mvdxml - shared templates // -figures -- manually added // -formats // -json // -step // -ttl // -xml // -samples // {sample}.ifcxml - ifcxml is native format for easier browsing, comparing, and validating // {sample}.htm - documentation for example // {sample}.png - preview image of example // {sample} - subdirectory if children // -schemas // {version} // {schema} // {class}.cs - definition in C# // {class}.htm - documentation in HTML // schema.cs - functions and // schema.htm - documentation of schema in HTML // schema.svg - diagram of schema in SVG // templates.ifcxml - property and quantity templates // localization // {locale}.txt - localized definitions // ifc.csproj if (bExportSchema) { string pathClasses = path + @"\schemas\" + project.GetSchemaIdentifier(); System.IO.Directory.CreateDirectory(pathClasses); FormatCSC.GenerateCode(project, pathClasses, mapEntity, DocCodeEnum.All); // generate ifcxml for templates DocumentationISO.DoExport(project, null, pathClasses + @"\templates.ifcxml", null, null, DocDefinitionScopeEnum.Default, null, mapEntity); // XSD configuration // not needed -- can re-read from C# classes //DocumentationISO.DoExport(project, null, pathClasses + @"\xsdconfig.xml", null, null, DocDefinitionScopeEnum.Default, null, mapEntity); } if (bExportExchanges) { string pathExchanges = path + @"\exchanges"; System.IO.Directory.CreateDirectory(pathExchanges); foreach (DocModelView docView in project.ModelViews) { string pathView = pathExchanges + @"\" + DocumentationISO.MakeLinkName(docView); DocumentationISO.DoExport(project, null, pathView + ".mvdxml", new DocModelView[] { docView }, null, DocDefinitionScopeEnum.Default, null, mapEntity); //... future: once it works flawlessly...FormatCSC.GenerateExchange(project, docView, pathView, mapEntity); } } if (bExportExamples) { // compile schema into assembly Type typeProject = Compiler.CompileProject(project); string pathSamples = path + @"\examples"; string pathSamplesWeb = "examples"; System.IO.Directory.CreateDirectory(pathSamples); using (StreamWriter writerIndex = new StreamWriter(Stream.Null)) //...pathSamples + @"\index.htm")) { writerIndex.WriteLine("<html><body>"); writerIndex.WriteLine("<table>"); foreach (DocExample docExam in project.Examples) { // generate ifcxml for each sample ExportExample(pathSamples, pathSamplesWeb, typeProject, docExam, writerIndex); } writerIndex.WriteLine("</table>"); writerIndex.WriteLine("</body></html>"); } } // terms, abbreviations, references, bibliography, ... #if false string pathTerms = path + @"\terms"; System.IO.Directory.CreateDirectory(pathSamples); foreach (DocTerm docTerm in this.m_project.Terms) { } #endif // localization SortedList <string, string> listLocale = new SortedList <string, string>(); foreach (DocObject eachobj in mapEntity.Values) { if (eachobj.Localization != null) { foreach (DocLocalization doclocal in eachobj.Localization) { // only deal with languages, not regions if (doclocal.Locale != null && doclocal.Locale.Length >= 2) { string language = doclocal.Locale.Substring(0, 2); if (!listLocale.ContainsKey(language)) { listLocale.Add(language, doclocal.Locale); } } } } } if (bExportLocalize) { string pathLocalize = path + @"\localize"; System.IO.Directory.CreateDirectory(pathLocalize); foreach (string locale in listLocale.Keys) { string pathLocale = path + @"\localize\" + locale + ".txt"; using (FormatCSV format = new FormatCSV(pathLocale)) { format.Instance = project; format.Locales = new string[] { locale }; format.Scope = DocDefinitionScopeEnum.Default; format.Save(); } } } }
/// <summary> /// Loads all content from a folder hierarchy (overlaying anything already existing) /// </summary> /// <param name="project"></param> /// <param name="path"></param> public static void LoadFolder(DocProject project, string path) { // get all files within folder hierarchy string pathSchema = path + @"\schemas"; IEnumerable <string> en = System.IO.Directory.EnumerateFiles(pathSchema, "*.cs", System.IO.SearchOption.AllDirectories); List <string> list = new List <string>(); foreach (string s in en) { list.Add(s); } string[] files = list.ToArray(); Dictionary <string, string> options = new Dictionary <string, string> { { "CompilerVersion", "v4.0" } }; Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider(options); System.CodeDom.Compiler.CompilerParameters parms = new System.CodeDom.Compiler.CompilerParameters(); parms.GenerateInMemory = true; parms.GenerateExecutable = false; parms.ReferencedAssemblies.Add("System.dll"); parms.ReferencedAssemblies.Add("System.Core.dll"); parms.ReferencedAssemblies.Add("System.ComponentModel.dll"); parms.ReferencedAssemblies.Add("System.ComponentModel.DataAnnotations.dll"); parms.ReferencedAssemblies.Add("System.Data.dll"); parms.ReferencedAssemblies.Add("System.Runtime.Serialization.dll"); parms.ReferencedAssemblies.Add("System.Xml.dll"); System.CodeDom.Compiler.CompilerResults results = prov.CompileAssemblyFromFile(parms, files); System.Reflection.Assembly assem = results.CompiledAssembly; LoadAssembly(project, assem); // EXPRESS rules (eventually in C#, though .exp file snippets for now) en = System.IO.Directory.EnumerateFiles(pathSchema, "*.exp", System.IO.SearchOption.AllDirectories); foreach (string file in en) { string name = Path.GetFileNameWithoutExtension(file); string expr = null; using (StreamReader readExpr = new StreamReader(file, Encoding.UTF8)) { if (name.Contains('-')) { // where rule expr = readExpr.ReadToEnd(); } else { // function: skip first and last lines readExpr.ReadLine(); StringBuilder sbExpr = new StringBuilder(); while (!readExpr.EndOfStream) { string line = readExpr.ReadLine(); if (!readExpr.EndOfStream) { sbExpr.AppendLine(line); } } expr = sbExpr.ToString(); } } if (name.Contains('-')) { // where rule string[] parts = name.Split('-'); if (parts.Length == 2) { DocWhereRule docWhere = new DocWhereRule(); docWhere.Name = parts[1]; docWhere.Expression = expr; DocDefinition docDef = project.GetDefinition(parts[0]); if (docDef is DocEntity) { DocEntity docEnt = (DocEntity)docDef; docEnt.WhereRules.Add(docWhere); } else if (docDef is DocDefined) { DocDefined docEnt = (DocDefined)docDef; docEnt.WhereRules.Add(docWhere); } else if (docDef == null) { //... global rule... } } } else { // function string schema = Path.GetDirectoryName(file); schema = Path.GetDirectoryName(schema); schema = Path.GetFileName(schema); DocSchema docSchema = project.GetSchema(schema); if (docSchema != null) { DocFunction docFunction = new DocFunction(); docSchema.Functions.Add(docFunction); docFunction.Name = name; docFunction.Expression = expr; } } } // now, hook up html documentation en = System.IO.Directory.EnumerateFiles(pathSchema, "*.htm", System.IO.SearchOption.AllDirectories); foreach (string file in en) { string name = Path.GetFileNameWithoutExtension(file); DocObject docObj = null; if (name == "schema") { string schema = Path.GetDirectoryName(file); schema = Path.GetFileName(schema); docObj = project.GetSchema(schema); } else if (name.Contains('-')) { // where rule string[] parts = name.Split('-'); if (parts.Length == 2) { DocDefinition docDef = project.GetDefinition(parts[0]); if (docDef is DocEntity) { DocEntity docEnt = (DocEntity)docDef; foreach (DocWhereRule docWhereRule in docEnt.WhereRules) { if (docWhereRule.Name.Equals(parts[1])) { docObj = docWhereRule; break; } } } else if (docDef is DocDefined) { DocDefined docEnt = (DocDefined)docDef; foreach (DocWhereRule docWhereRule in docEnt.WhereRules) { if (docWhereRule.Name.Equals(parts[1])) { docObj = docWhereRule; break; } } } } } else { docObj = project.GetDefinition(name); if (docObj == null) { docObj = project.GetFunction(name); } } if (docObj != null) { using (StreamReader readHtml = new StreamReader(file, Encoding.UTF8)) { docObj.Documentation = readHtml.ReadToEnd(); } } } // load schema diagrams en = System.IO.Directory.EnumerateFiles(pathSchema, "*.svg", System.IO.SearchOption.AllDirectories); foreach (string file in en) { string schema = Path.GetDirectoryName(file); schema = Path.GetFileName(schema); DocSchema docSchema = project.GetSchema(schema); if (docSchema != null) { using (IfcDoc.Schema.SVG.SchemaSVG schemaSVG = new IfcDoc.Schema.SVG.SchemaSVG(file, docSchema, project, DiagramFormat.UML)) { schemaSVG.Load(); } } } // psets, qsets //... // exchanges en = System.IO.Directory.EnumerateFiles(path, "*.mvdxml", System.IO.SearchOption.AllDirectories); foreach (string file in en) { IfcDoc.Schema.MVD.SchemaMVD.Load(project, file); } // examples string pathExamples = path + @"\examples"; if (Directory.Exists(pathExamples)) { en = System.IO.Directory.EnumerateFiles(pathExamples, "*.htm", SearchOption.TopDirectoryOnly); foreach (string file in en) { DocExample docExample = new DocExample(); docExample.Name = Path.GetFileNameWithoutExtension(file); project.Examples.Add(docExample); using (StreamReader reader = new StreamReader(file)) { docExample.Documentation = reader.ReadToEnd(); } string dirpath = file.Substring(0, file.Length - 4); if (Directory.Exists(dirpath)) { IEnumerable <string> suben = System.IO.Directory.EnumerateFiles(dirpath, "*.ifc", SearchOption.TopDirectoryOnly); foreach (string ex in suben) { DocExample docEx = new DocExample(); docEx.Name = Path.GetFileNameWithoutExtension(ex); docExample.Examples.Add(docEx); // read the content of the file using (FileStream fs = new FileStream(ex, FileMode.Open, FileAccess.Read)) { docEx.File = new byte[fs.Length]; fs.Read(docEx.File, 0, docEx.File.Length); } // read documentation string exdoc = ex.Substring(0, ex.Length - 4) + ".htm"; if (File.Exists(exdoc)) { using (StreamReader reader = new StreamReader(exdoc)) { docEx.Documentation = reader.ReadToEnd(); } } } } } } // localization en = System.IO.Directory.EnumerateFiles(path, "*.txt", System.IO.SearchOption.AllDirectories); foreach (string file in en) { using (FormatCSV format = new FormatCSV(file)) { try { format.Instance = project; format.Load(); } catch { } } } }
/// <summary> /// Exports file according to format. /// </summary> /// <param name="filepath">File path to export.</param> /// <param name="templates">Optional filter of templates to export.</param> /// <param name="views">Optional filter of views to export.</param> /// <param name="schemas">Optional filter of schemas to export.</param> /// <param name="locales">Optional filter of locales to export.</param> public static void DoExport(DocProject docProject, string filepath, DocModelView[] views, string[] locales, Dictionary<long, SEntity> instances) { string ext = System.IO.Path.GetExtension(filepath).ToLower(); Dictionary<DocObject, bool> included = null; if (views != null) { included = new Dictionary<DocObject, bool>(); foreach (DocModelView docView in views) { docProject.RegisterObjectsInScope(docView, included); } } switch (ext) { case ".ifc": using (FormatSPF format = new FormatSPF(filepath, Schema.IFC.SchemaIfc.Types, instances)) { format.InitHeaders(docProject.Annotations[0].Code, "IFC4"); Schema.IFC.IfcProject ifcProject = new IfcDoc.Schema.IFC.IfcProject(); Program.ExportIfc(ifcProject, docProject, included); format.Save(); } break; case ".ifcxml": using (FormatXML format = new FormatXML(filepath, typeof(Schema.IFC.IfcProject), "http://www.buildingsmart-tech.org/ifcXML/IFC4")) { Schema.IFC.IfcProject ifcProject = new IfcDoc.Schema.IFC.IfcProject(); Program.ExportIfc(ifcProject, docProject, included); format.Instance = ifcProject; format.Save(); } break; case ".mvdxml": using (FormatXML format = new FormatXML(filepath, typeof(mvdXML), mvdXML.DefaultNamespace)) { mvdXML mvd = new mvdXML(); Program.ExportMvd(mvd, docProject, included); format.Instance = mvd; format.Save(); } break; case ".cs": using (FormatCSC format = new FormatCSC(filepath)) { format.Instance = docProject; format.Save(); } break; case ".exp": // use currently visible model view(s) using (FormatEXP format = new FormatEXP(filepath)) { format.Instance = docProject; format.ModelViews = views; format.Save(); } break; case ".xsd": // use currently visible model view(s) using (FormatXSD format = new FormatXSD(filepath)) { format.Instance = docProject; format.ModelViews = views; format.Save(); } break; case ".xml": // Express XSD Configuration using (FormatXML format = new FormatXML(filepath, typeof(Schema.CNF.configuration), null, Schema.CNF.SchemaCNF.Prefixes)) { Schema.CNF.configuration config = new Schema.CNF.configuration(); Program.ExportCnf(config, docProject, views, included); format.Instance = config; format.Save(); } break; case ".txt": // pick locale using (FormatCSV format = new FormatCSV(filepath)) { format.Instance = docProject; format.Locales = locales; format.Save(); } break; case ".sch": using (FormatXML format = new FormatXML(filepath, typeof(Schema.SCH.schema), "http://purl.oclc.org/dsdl/schematron")) { Schema.SCH.schema sch = new Schema.SCH.schema(); Program.ExportSch(sch, docProject, included); format.Instance = sch; format.Save(); } break; } }
/// <summary> /// Exports file according to format. /// </summary> /// <param name="filepath">File path to export.</param> /// <param name="templates">Optional filter of templates to export.</param> /// <param name="views">Optional filter of views to export.</param> /// <param name="schemas">Optional filter of schemas to export.</param> /// <param name="locales">Optional filter of locales to export.</param> public static void DoExport(DocProject docProject, string filepath, DocModelView[] views, string[] locales, Dictionary<long, SEntity> instances) { string ext = System.IO.Path.GetExtension(filepath).ToLower(); Dictionary<DocObject, bool> included = null; if (views != null) { included = new Dictionary<DocObject, bool>(); foreach (DocModelView docView in views) { docProject.RegisterObjectsInScope(docView, included); } } // special case for zip files -- determine based on special naming; make configurable in future Type typeExport = null; if (filepath.EndsWith("-psd.zip")) { typeExport = typeof(DocPropertySet); } else if(filepath.EndsWith("-qto.zip")) { typeExport = typeof(DocQuantitySet); } switch (ext) { case ".ifc": using (FormatSPF format = new FormatSPF(filepath, Schema.IFC.SchemaIfc.Types, instances)) { string filename = System.IO.Path.GetFileName(filepath); format.InitHeaders(filename, "IFC4"); // we always use IFC4 (not later schema) for exporting templates, as that is the earliest version required. Schema.IFC.IfcProject ifcProject = new IfcDoc.Schema.IFC.IfcProject(); Program.ExportIfc(ifcProject, docProject, included); format.Save(); } break; case ".ifcxml": using (FormatXML format = new FormatXML(filepath, typeof(Schema.IFC.IfcProject), "http://www.buildingsmart-tech.org/ifcXML/IFC4")) { Schema.IFC.IfcProject ifcProject = new IfcDoc.Schema.IFC.IfcProject(); Program.ExportIfc(ifcProject, docProject, included); format.Instance = ifcProject; format.Save(); } break; case ".mvdxml": using (FormatXML format = new FormatXML(filepath, typeof(mvdXML), mvdXML.DefaultNamespace)) { mvdXML mvd = new mvdXML(); Program.ExportMvd(mvd, docProject, included); format.Instance = mvd; format.Save(); } break; case ".cs": using (FormatCSC format = new FormatCSC(filepath)) { format.Instance = docProject; format.Save(); } break; case ".exp": // use currently visible model view(s) using (FormatEXP format = new FormatEXP(filepath)) { format.Instance = docProject; format.ModelViews = views; format.Save(); } break; case ".xsd": // use currently visible model view(s) using (FormatXSD format = new FormatXSD(filepath)) { format.Instance = docProject; format.ModelViews = views; format.Save(); } break; case ".xml": // Express XSD Configuration using (FormatXML format = new FormatXML(filepath, typeof(Schema.CNF.configuration), null, Schema.CNF.SchemaCNF.Prefixes)) { Schema.CNF.configuration config = new Schema.CNF.configuration(); Program.ExportCnf(config, docProject, views, included); format.Instance = config; format.Save(); } break; case ".txt": // pick locale using (FormatCSV format = new FormatCSV(filepath)) { format.Instance = docProject; format.Locales = locales; format.Save(); } break; case ".sch": using (FormatXML format = new FormatXML(filepath, typeof(Schema.SCH.schema), "http://purl.oclc.org/dsdl/schematron")) { Schema.SCH.schema sch = new Schema.SCH.schema(); Program.ExportSch(sch, docProject, included); format.Instance = sch; format.Save(); } break; case ".zip": using (FormatZIP format = new FormatZIP(new System.IO.FileStream(filepath, System.IO.FileMode.Create), docProject, included, typeExport)) { format.Save(); } break; } }
private void toolStripMenuItemFileImport_Click(object sender, EventArgs e) { StringBuilder sbErrors = new StringBuilder(); DialogResult res = this.openFileDialogImport.ShowDialog(this); if (res == DialogResult.OK) { List<DocSchema> importedschemas = new List<DocSchema>(); bool updateDescriptions = false; if(this.openFileDialogImport.FileName.EndsWith(".vex")) { DialogResult resUpdate = MessageBox.Show(this, "Do you want to update the documentation? Click Yes to update documentation and definitions, or No to update just definitions.", "Import VEX", MessageBoxButtons.YesNoCancel); if (resUpdate == System.Windows.Forms.DialogResult.Cancel) return; if (resUpdate == System.Windows.Forms.DialogResult.Yes) updateDescriptions = true; } foreach (string filename in this.openFileDialogImport.FileNames) { string ext = System.IO.Path.GetExtension(filename).ToLower(); switch (ext) { case ".vex": using (FormatSPF format = new FormatSPF(filename, SchemaVEX.Types, null)) { format.Load(); // get the root schemata SCHEMATA vexschema = null; foreach (SEntity entity in format.Instances.Values) { if (entity is SCHEMATA) { vexschema = (SCHEMATA)entity; break; } } if (vexschema != null) { DocSchema schema = Program.ImportVex(vexschema, this.m_project, updateDescriptions); importedschemas.Add(schema); // add schemas from multiple files first, process later } } break; case ".xml": if (filename.Contains("Pset_")) { using (FormatXML format = new FormatXML(filename, typeof(PropertySetDef), "http://buildingSMART-tech.org/xml/psd/PSD_IFC4.xsd")) { format.Load(); PropertySetDef psd = (PropertySetDef)format.Instance; string schema = null; if (psd.Versions != null && psd.Versions.Count > 0) { schema = psd.Versions[0].schema; } if (String.IsNullOrEmpty(schema)) { // guess the schema according to applicable type value if (psd.ApplicableTypeValue != null) { string[] parts = psd.ApplicableTypeValue.Split(new char[] { '/', '[' }); TreeNode tnEntity = null; if (this.m_mapTree.TryGetValue(parts[0].ToLowerInvariant(), out tnEntity)) { DocSchema docschema = (DocSchema)tnEntity.Parent.Parent.Tag; schema = docschema.Name; } } } if(schema == null) { schema = "IfcProductExtension";//fallback } // find the schema TreeNode tn = null; if (schema != null && this.m_mapTree.TryGetValue(schema.ToLowerInvariant(), out tn)) { DocSchema docschema = (DocSchema)tn.Tag; // find existing pset if applicable DocPropertySet pset = docschema.RegisterPset(psd.Name); // use hashed guid if (pset.Uuid == Guid.Empty) { System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create(); byte[] hash = md5.ComputeHash(Encoding.Default.GetBytes(pset.Name)); pset.Uuid = new Guid(hash); } pset.Name = psd.Name; if (psd.Definition != null) { pset.Documentation = psd.Definition.Trim(); } if (psd.ApplicableTypeValue != null) { pset.ApplicableType = psd.ApplicableTypeValue.Replace("Type", "").Replace("[PerformanceHistory]", ""); // organize at occurrences; use pset type to determine type applicability } // for now, rely on naming convention (better to capture in pset schema eventually) if (psd.Name.Contains("PHistory")) // special naming convention { pset.PropertySetType = "PSET_PERFORMANCEDRIVEN"; } else if (psd.Name.Contains("Occurrence")) { pset.PropertySetType = "PSET_OCCURRENCEDRIVEN"; } else { pset.PropertySetType = "PSET_TYPEDRIVENOVERRIDE"; } // import localized definitions if (psd.PsetDefinitionAliases != null) { foreach (PsetDefinitionAlias pl in psd.PsetDefinitionAliases) { pset.RegisterLocalization(pl.lang, null, pl.Value); } } foreach (PropertyDef subdef in psd.PropertyDefs) { DocProperty docprop = pset.RegisterProperty(subdef.Name); Program.ImportPsdPropertyTemplate(subdef, docprop); } // add to Use Definition at applicable entity #if false if (pset.ApplicableType != null) { string[] apptypes = pset.ApplicableType.Split('/'); if (this.m_mapTree.TryGetValue(apptypes[0].ToLowerInvariant(), out tn)) { DocEntity entity = (DocEntity)tn.Tag; if (this.m_project.ModelViews.Count == 0) { // must have at least one model view for populating property set links this.m_project.ModelViews.Add(new DocModelView()); } foreach (DocModelView docView in this.m_project.ModelViews) { DocConceptRoot docRoot = null; foreach (DocConceptRoot eachRoot in docView.ConceptRoots) { if (eachRoot.ApplicableEntity == entity) { docRoot = eachRoot; break; } } if (docRoot == null) { docRoot = new DocConceptRoot(); docRoot.ApplicableEntity = entity; docView.ConceptRoots.Add(docRoot); } // find the pset template DocTemplateUsage templateuse = null; foreach (DocTemplateUsage eachtemplateuse in docRoot.Concepts) { if (eachtemplateuse.Definition != null && eachtemplateuse.Definition.Name.StartsWith("Property")) { templateuse = eachtemplateuse; break; } } DocTemplateDefinition docdefpset = this.m_project.GetTemplate(new Guid("f74255a6-0c0e-4f31-84ad-24981db62461")); if (docdefpset != null) { // if no template, add it if (templateuse == null) { // get the pset template templateuse = new DocTemplateUsage(); docRoot.Concepts.Add(templateuse); templateuse.Definition = docdefpset; } DocTemplateItem templateitem = new DocTemplateItem(); templateuse.Items.Add(templateitem); templateitem.RuleInstanceID = "IfcPropertySet"; if (apptypes.Length == 2) { templateitem.RuleParameters += "PredefinedType=" + apptypes[1] + ";"; } templateitem.RuleParameters += "Name=" + pset.Name + ";"; templateitem.RuleParameters += "TemplateType=" + pset.PropertySetType + ";"; // don't include documentation -- too wordy templateitem.Documentation = pset.Documentation; } } } else { sbErrors.Append(System.IO.Path.GetFileNameWithoutExtension(filename) + ": unrecognized ApplicableTypeValue; "); } } #endif } else { sbErrors.Append(System.IO.Path.GetFileNameWithoutExtension(filename) + ": unrecognized schema; "); } } } else if (filename.Contains("Qto_")) { using (FormatXML format = new FormatXML(filename, typeof(QtoSetDef))) { format.Load(); QtoSetDef qto = (QtoSetDef)format.Instance; string schema = qto.Versions[0].schema; TreeNode tn = null; if (schema != null && this.m_mapTree.TryGetValue(schema.ToLowerInvariant(), out tn)) { DocSchema docschema = (DocSchema)tn.Tag; // find existing pset if applicable DocQuantitySet qset = docschema.RegisterQset(qto.Name); // use hashed guid if (qset.Uuid == Guid.Empty) { System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create(); byte[] hash = md5.ComputeHash(Encoding.Default.GetBytes(qset.Name)); qset.Uuid = new Guid(hash); } // everything is currently named "Base Quantities"; get name from file instead; e.g. "Qto_Beam" qset.Name = System.IO.Path.GetFileNameWithoutExtension(filename); qset.Documentation = qto.Definition; qset.ApplicableType = qto.ApplicableClasses[0].Value; // fix: remove "Type" if (qset.ApplicableType.EndsWith("Type")) { qset.ApplicableType = qset.ApplicableType.Substring(0, qset.ApplicableType.Length - 4); } // import localized definitions if (qto.QtoDefinitionAliases != null) { foreach (QtoDefinitionAlias pl in qto.QtoDefinitionAliases) { qset.RegisterLocalization(pl.lang, null, pl.Value); } } foreach (QtoDef qtodef in qto.QtoDefs) { DocQuantity q = qset.RegisterQuantity(qtodef.Name); q.Documentation = qtodef.Definition; switch (qtodef.QtoType) { case "IfcQuantityCount": q.QuantityType = DocQuantityTemplateTypeEnum.Q_COUNT; break; case "IfcQuantityLength": q.QuantityType = DocQuantityTemplateTypeEnum.Q_LENGTH; break; case "IfcQuantityArea": q.QuantityType = DocQuantityTemplateTypeEnum.Q_AREA; break; case "IfcQuantityVolume": q.QuantityType = DocQuantityTemplateTypeEnum.Q_VOLUME; break; case "IfcQuantityWeight": q.QuantityType = DocQuantityTemplateTypeEnum.Q_WEIGHT; break; case "IfcQuantityTime": q.QuantityType = DocQuantityTemplateTypeEnum.Q_TIME; break; } foreach (NameAlias namealias in qtodef.NameAliases) { string desc = null; foreach (DefinitionAlias docalias in qtodef.DefinitionAliases) { if (docalias.lang.Equals(namealias.lang)) { desc = docalias.Value; break; } } q.RegisterLocalization(namealias.lang, namealias.Value, desc); } } // map to use definition if (this.m_mapTree.TryGetValue(qset.ApplicableType.ToLowerInvariant(), out tn)) { DocEntity entity = (DocEntity)tn.Tag; if (this.m_project.ModelViews.Count == 0) { // must have at least one model view for populating property set links this.m_project.ModelViews.Add(new DocModelView()); } foreach (DocModelView docView in this.m_project.ModelViews) { DocConceptRoot docRoot = null; foreach (DocConceptRoot eachRoot in docView.ConceptRoots) { if (eachRoot.ApplicableEntity == entity) { docRoot = eachRoot; break; } } if (docRoot == null) { docRoot = new DocConceptRoot(); docRoot.ApplicableEntity = entity; docView.ConceptRoots.Add(docRoot); } // find the qset template DocTemplateUsage templateuse = null; foreach (DocTemplateUsage eachtemplateuse in docRoot.Concepts) { if (eachtemplateuse.Definition.Name.StartsWith("Quantity")) { templateuse = eachtemplateuse; break; } } // if no template, add it if (templateuse == null) { // get the pset template templateuse = new DocTemplateUsage(); docRoot.Concepts.Add(templateuse); templateuse.Definition = this.m_project.GetTemplate(new Guid("6652398e-6579-4460-8cb4-26295acfacc7")); } if (templateuse != null) { DocTemplateItem templateitem = new DocTemplateItem(); templateuse.Items.Add(templateitem); templateitem.RuleInstanceID = "IfcElementQuantity"; templateitem.RuleParameters = "Name=" + qset.Name + ";TemplateType=QTO_OCCURRENCEDRIVEN;"; } } } } else { sbErrors.Append(System.IO.Path.GetFileNameWithoutExtension(filename) + ": unrecognized schema; "); } } } else if (filename.Contains("ifcXML")) { using (FormatXML format = new FormatXML(filename, typeof(configuration), null, SchemaCNF.Prefixes)) { try { this.m_loading = true; // prevent constructors from registering instances (xml serializer instantiates) format.Load(); DocModelView docView = null; using(FormSelectView form = new FormSelectView(this.m_project, null)) { if(form.ShowDialog(this) == System.Windows.Forms.DialogResult.OK && form.Selection != null && form.Selection.Length == 1) { docView = form.Selection[0]; } } configuration cnf = (configuration)format.Instance; Program.ImportCnf(cnf, this.m_project, docView); } catch (Exception xx) { MessageBox.Show(this, xx.Message, "Import CNFXML"); } finally { this.m_loading = false; } } } break; case ".mvdxml": this.ImportMVD(filename); break; case ".txt": using (FormatCSV format = new FormatCSV(filename)) { try { format.Instance = this.m_project; format.Load(); } catch (System.Exception xx) { MessageBox.Show(this, xx.Message, "Import CSV"); } } break; case ".ifd": using (FormatIFD format = new FormatIFD(filename)) { try { format.Instance = this.m_project; format.Load(); } catch (System.Exception xx) { MessageBox.Show(this, xx.Message, "Import IFD"); } } break; case ".xsd": using (FormatXML format = new FormatXML(filename, typeof(IfcDoc.Schema.XSD.schema), IfcDoc.Schema.XSD.SchemaXsd.DefaultNamespace)) { try { format.Load(); DocSchema docSchema = Program.ImportXsd((IfcDoc.Schema.XSD.schema)format.Instance, this.m_project); if(docSchema.Name == null) { docSchema.Name = System.IO.Path.GetFileNameWithoutExtension(filename); } } catch(System.Exception xx) { MessageBox.Show(this, xx.Message, "Import XSD"); } } break; } } // load tree before generating use definitions this.LoadTree(); // load tree again to pick up definitions if (importedschemas.Count > 0) { LoadTree(); } } if (sbErrors.Length > 0) { MessageBox.Show(this, "Import succeeded, however one or more definitions have missing or incorrect information:\r\n" + sbErrors.ToString(), "Import Errors"); } }
/// <summary> /// Loads all content from a folder hierarchy (overlaying anything already existing) /// </summary> /// <param name="project"></param> /// <param name="path"></param> public static void Load(DocProject project, string path) { // get all files within folder hierarchy string pathSchema = path + @"\schemas"; IEnumerable <string> en = System.IO.Directory.EnumerateFiles(pathSchema, "*.cs", System.IO.SearchOption.AllDirectories); List <string> list = new List <string>(); foreach (string s in en) { list.Add(s); } string[] files = list.ToArray(); Dictionary <string, string> options = new Dictionary <string, string> { { "CompilerVersion", "v4.0" } }; Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider(options); System.CodeDom.Compiler.CompilerParameters parms = new System.CodeDom.Compiler.CompilerParameters(); parms.GenerateInMemory = true; parms.GenerateExecutable = false; parms.ReferencedAssemblies.Add("System.dll"); parms.ReferencedAssemblies.Add("System.Core.dll"); parms.ReferencedAssemblies.Add("System.ComponentModel.dll"); parms.ReferencedAssemblies.Add("System.ComponentModel.DataAnnotations.dll"); parms.ReferencedAssemblies.Add("System.Data.dll"); parms.ReferencedAssemblies.Add("System.Runtime.Serialization.dll"); parms.ReferencedAssemblies.Add("System.Xml.dll"); System.CodeDom.Compiler.CompilerResults results = prov.CompileAssemblyFromFile(parms, files); System.Reflection.Assembly assem = results.CompiledAssembly; // look through classes of assembly foreach (Type t in assem.GetTypes()) { string[] namespaceparts = t.Namespace.Split('.'); string schema = namespaceparts[namespaceparts.Length - 1]; DocSection docSection = null; if (t.Namespace.EndsWith("Resource")) { docSection = project.Sections[7]; } else if (t.Namespace.EndsWith("Domain")) { docSection = project.Sections[6]; } else if (t.Namespace.Contains("Shared")) { docSection = project.Sections[5]; } else { docSection = project.Sections[4]; // kernel, extensions } // find schema DocSchema docSchema = null; foreach (DocSchema docEachSchema in docSection.Schemas) { if (docEachSchema.Name.Equals(schema)) { docSchema = docEachSchema; break; } } if (docSchema == null) { docSchema = new DocSchema(); docSchema.Name = schema; docSection.Schemas.Add(docSchema); docSection.SortSchemas(); } DocDefinition docDef = null; if (t.IsEnum) { DocEnumeration docEnum = new DocEnumeration(); docSchema.Types.Add(docEnum); docDef = docEnum; System.Reflection.FieldInfo[] fields = t.GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); foreach (System.Reflection.FieldInfo field in fields) { DocConstant docConst = new DocConstant(); docEnum.Constants.Add(docConst); docConst.Name = field.Name; DescriptionAttribute[] attrs = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attrs.Length == 1) { docConst.Documentation = attrs[0].Description; } } } else if (t.IsValueType) { DocDefined docDefined = new DocDefined(); docSchema.Types.Add(docDefined); docDef = docDefined; PropertyInfo[] fields = t.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); docDefined.DefinedType = fields[0].PropertyType.Name; } else if (t.IsInterface) { DocSelect docSelect = new DocSelect(); docSchema.Types.Add(docSelect); docDef = docSelect; } else if (t.IsClass) { DocEntity docEntity = new DocEntity(); docSchema.Entities.Add(docEntity); docDef = docEntity; if (t.BaseType != typeof(object)) { docEntity.BaseDefinition = t.BaseType.Name; } if (!t.IsAbstract) { docEntity.EntityFlags = 0x20; } Dictionary <int, DocAttribute> attrsDirect = new Dictionary <int, DocAttribute>(); List <DocAttribute> attrsInverse = new List <DocAttribute>(); PropertyInfo[] fields = t.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | BindingFlags.DeclaredOnly); foreach (PropertyInfo field in fields) { DocAttribute docAttr = new DocAttribute(); docAttr.Name = field.Name.Substring(1); Type typeField = field.PropertyType; if (typeField.IsGenericType) { Type typeGeneric = typeField.GetGenericTypeDefinition(); typeField = typeField.GetGenericArguments()[0]; if (typeGeneric == typeof(Nullable <>)) { docAttr.IsOptional = true; } else if (typeGeneric == typeof(ISet <>)) { docAttr.AggregationType = (int)DocAggregationEnum.SET; } else if (typeGeneric == typeof(IList <>)) { docAttr.AggregationType = (int)DocAggregationEnum.LIST; } } docAttr.DefinedType = typeField.Name; MinLengthAttribute mla = (MinLengthAttribute)field.GetCustomAttribute(typeof(MinLengthAttribute)); if (mla != null) { docAttr.AggregationLower = mla.Length.ToString(); } MaxLengthAttribute mxa = (MaxLengthAttribute)field.GetCustomAttribute(typeof(MaxLengthAttribute)); if (mxa != null) { docAttr.AggregationUpper = mxa.Length.ToString(); } PropertyInfo propinfo = t.GetProperty(docAttr.Name); if (propinfo != null) { DescriptionAttribute da = (DescriptionAttribute)propinfo.GetCustomAttribute(typeof(DescriptionAttribute)); if (da != null) { docAttr.Documentation = da.Description; } } DataMemberAttribute dma = (DataMemberAttribute)field.GetCustomAttribute(typeof(DataMemberAttribute)); if (dma != null) { attrsDirect.Add(dma.Order, docAttr); RequiredAttribute rqa = (RequiredAttribute)field.GetCustomAttribute(typeof(RequiredAttribute)); if (rqa == null) { docAttr.IsOptional = true; } CustomValidationAttribute cva = (CustomValidationAttribute)field.GetCustomAttribute(typeof(CustomValidationAttribute)); if (cva != null) { docAttr.IsUnique = true; } } else { InversePropertyAttribute ipa = (InversePropertyAttribute)field.GetCustomAttribute(typeof(InversePropertyAttribute)); if (ipa != null) { docAttr.Inverse = ipa.Property; attrsInverse.Add(docAttr); } } // xml XmlIgnoreAttribute xia = (XmlIgnoreAttribute)field.GetCustomAttribute(typeof(XmlIgnoreAttribute)); if (xia != null) { docAttr.XsdFormat = DocXsdFormatEnum.Hidden; } else { XmlElementAttribute xea = (XmlElementAttribute)field.GetCustomAttribute(typeof(XmlElementAttribute)); if (xea != null) { if (!String.IsNullOrEmpty(xea.ElementName)) { docAttr.XsdFormat = DocXsdFormatEnum.Element; } else { docAttr.XsdFormat = DocXsdFormatEnum.Attribute; } } } } foreach (DocAttribute docAttr in attrsDirect.Values) { docEntity.Attributes.Add(docAttr); } foreach (DocAttribute docAttr in attrsInverse) { docEntity.Attributes.Add(docAttr); } // get derived attributes based on properties PropertyInfo[] props = t.GetProperties(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public); foreach (PropertyInfo prop in props) { // if no backing field, then derived FieldInfo field = t.GetField("_" + prop.Name, BindingFlags.NonPublic | BindingFlags.Instance); if (field == null) { DocAttribute docDerived = new DocAttribute(); docDerived.Name = prop.Name; docEntity.Attributes.Add(docDerived); } } } if (docDef != null) { docDef.Name = t.Name; docDef.Uuid = t.GUID; } docSchema.SortTypes(); docSchema.SortEntities(); } // pass 2: hook up selects foreach (Type t in assem.GetTypes()) { Type[] typeInterfaces = t.GetInterfaces(); if (typeInterfaces.Length > 0) { foreach (Type typeI in typeInterfaces) { DocSelect docSelect = project.GetDefinition(typeI.Name) as DocSelect; if (docSelect != null) { DocSelectItem docItem = new DocSelectItem(); docItem.Name = t.Name; docSelect.Selects.Add(docItem); } } } } // EXPRESS rules (eventually in C#, though .exp file snippets for now) en = System.IO.Directory.EnumerateFiles(pathSchema, "*.exp", System.IO.SearchOption.AllDirectories); foreach (string file in en) { string name = Path.GetFileNameWithoutExtension(file); string expr = null; using (StreamReader readExpr = new StreamReader(file, Encoding.UTF8)) { expr = readExpr.ReadToEnd(); } if (name.Contains('-')) { // where rule string[] parts = name.Split('-'); if (parts.Length == 2) { DocWhereRule docWhere = new DocWhereRule(); docWhere.Name = parts[1]; docWhere.Expression = expr; DocDefinition docDef = project.GetDefinition(parts[0]); if (docDef is DocEntity) { DocEntity docEnt = (DocEntity)docDef; docEnt.WhereRules.Add(docWhere); } else if (docDef is DocDefined) { DocDefined docEnt = (DocDefined)docDef; docEnt.WhereRules.Add(docWhere); } else if (docDef == null) { //... global rule... } } } else { // function string schema = Path.GetDirectoryName(file); schema = Path.GetDirectoryName(schema); schema = Path.GetFileName(schema); DocSchema docSchema = project.GetSchema(schema); if (docSchema != null) { DocFunction docFunction = new DocFunction(); docSchema.Functions.Add(docFunction); docFunction.Name = name; docFunction.Expression = expr; } } } // now, hook up html documentation en = System.IO.Directory.EnumerateFiles(pathSchema, "*.htm", System.IO.SearchOption.AllDirectories); foreach (string file in en) { string name = Path.GetFileNameWithoutExtension(file); DocObject docObj = null; if (name == "schema") { string schema = Path.GetDirectoryName(file); schema = Path.GetFileName(schema); docObj = project.GetSchema(schema); } else if (name.Contains('-')) { // where rule string[] parts = name.Split('-'); if (parts.Length == 2) { DocDefinition docDef = project.GetDefinition(parts[0]); if (docDef is DocEntity) { DocEntity docEnt = (DocEntity)docDef; foreach (DocWhereRule docWhereRule in docEnt.WhereRules) { if (docWhereRule.Name.Equals(parts[1])) { docObj = docWhereRule; break; } } } else if (docDef is DocDefined) { DocDefined docEnt = (DocDefined)docDef; foreach (DocWhereRule docWhereRule in docEnt.WhereRules) { if (docWhereRule.Name.Equals(parts[1])) { docObj = docWhereRule; break; } } } } } else { docObj = project.GetDefinition(name); if (docObj == null) { docObj = project.GetFunction(name); } } if (docObj != null) { using (StreamReader readHtml = new StreamReader(file, Encoding.UTF8)) { docObj.Documentation = readHtml.ReadToEnd(); } } } // load schema diagrams en = System.IO.Directory.EnumerateFiles(pathSchema, "*.svg", System.IO.SearchOption.AllDirectories); foreach (string file in en) { string schema = Path.GetDirectoryName(file); schema = Path.GetFileName(schema); DocSchema docSchema = project.GetSchema(schema); if (docSchema != null) { using (IfcDoc.Schema.SVG.SchemaSVG schemaSVG = new IfcDoc.Schema.SVG.SchemaSVG(file, docSchema, project)) { schemaSVG.Load(); } } } // psets, qsets //... // exchanges en = System.IO.Directory.EnumerateFiles(path, "*.mvdxml", System.IO.SearchOption.AllDirectories); foreach (string file in en) { IfcDoc.Schema.MVD.SchemaMVD.Load(project, file); } // examples string pathExamples = path + @"\examples"; if (Directory.Exists(pathExamples)) { en = System.IO.Directory.EnumerateFiles(pathExamples, "*.htm", SearchOption.TopDirectoryOnly); foreach (string file in en) { DocExample docExample = new DocExample(); docExample.Name = Path.GetFileNameWithoutExtension(file); project.Examples.Add(docExample); using (StreamReader reader = new StreamReader(file)) { docExample.Documentation = reader.ReadToEnd(); } string dirpath = file.Substring(0, file.Length - 4); if (Directory.Exists(dirpath)) { IEnumerable <string> suben = System.IO.Directory.EnumerateFiles(dirpath, "*.ifc", SearchOption.TopDirectoryOnly); foreach (string ex in suben) { DocExample docEx = new DocExample(); docEx.Name = Path.GetFileNameWithoutExtension(ex); docExample.Examples.Add(docEx); // read the content of the file using (FileStream fs = new FileStream(ex, FileMode.Open, FileAccess.Read)) { docEx.File = new byte[fs.Length]; fs.Read(docEx.File, 0, docEx.File.Length); } // read documentation string exdoc = ex.Substring(0, ex.Length - 4) + ".htm"; if (File.Exists(exdoc)) { using (StreamReader reader = new StreamReader(exdoc)) { docEx.Documentation = reader.ReadToEnd(); } } } } } } // localization en = System.IO.Directory.EnumerateFiles(path, "*.txt", System.IO.SearchOption.AllDirectories); foreach (string file in en) { using (FormatCSV format = new FormatCSV(file)) { try { format.Instance = project; format.Load(); } catch { } } } }