Beispiel #1
0
        static void Execute(CommandLine command, string[] args)
        {
            var languageDirectory = GetLanguages(command);

            if (languageDirectory.Count == 0)
            {
                throw new Exception("至少选择一种语言");
            }
            Scorpio.Commons.Util.PrintSystemInfo();
            Logger.info("Scov Version : " + Scorpio.Version.version);
            Logger.info("Build Date : " + Scorpio.Version.date);
            var packageName = command.GetValueDefault("-package", "scov");  //默认 命名空间
            var files       = command.GetValue("-files");                   //需要转换的文件 多文件[{Util.Separator}]隔开
            var paths       = command.GetValue("-paths");                   //需要转换的文件目录 多路径[{Util.Separator}]隔开
            var data        = command.GetValue("-data");                    //数据文件输出目录 多目录[{Util.Separator}]隔开
            var suffix      = command.GetValueDefault("-suffix", "data");   //数据文件后缀 默认.data
            var name        = command.GetValueDefault("-name", "file");     //名字使用文件名或者sheet名字
            var fileSuffix  = command.GetValueDefault("-fileSuffix", "");   //生成的程序文件后缀名
            var config      = command.GetValue("-config");                  //配置文件路径 多路径[{Util.Separator}]隔开
            var spawns      = command.GetValue("-spawns");                  //派生文件列表 多个Key[{Util.Separator}]隔开
            var fileList    = new List <string>();                          //所有要生成的excel文件
            var spawnList   = new Dictionary <string, string>();            //派生文件列表
            var parser      = new PackageParser();
            var script      = parser.Script;

            if (!config.IsEmptyString())
            {
                foreach (var dir in config.Split(Util.Separator))
                {
                    parser.Parse(dir);
                }
            }
            if (!files.IsEmptyString())
            {
                foreach (var file in files.Split(Util.Separator))
                {
                    fileList.Add(Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, file)));
                }
            }
            if (!paths.IsEmptyString())
            {
                foreach (var path in paths.Split(Util.Separator))
                {
                    foreach (var file in Directory.GetFiles(Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, path)), "*", SearchOption.AllDirectories))
                    {
                        // $ 开头的 excel文件是 打开 excel 临时文件
                        if (!file.Contains("~$") && (file.EndsWith(".xls") || file.EndsWith(".xlsx")))
                        {
                            fileList.Add(file);
                        }
                    }
                }
            }
            if (fileList.Count == 0)
            {
                throw new Exception("至少选择一个excel文件");
            }
            if (!spawns.IsEmptyString())
            {
                foreach (var spawn in spawns.Split(Util.Separator))
                {
                    spawnList[spawn] = "";
                }
            }
            var successTables = new List <string>();
            var successSpawns = new Dictionary <string, List <string> >();
            var isFileName    = name.ToLower() == "file";

            foreach (var file in fileList)
            {
                var fileName  = Path.GetFileNameWithoutExtension(file).Trim();
                var extension = Path.GetExtension(file);
                var tempFile  = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, System.Guid.NewGuid().ToString("N") + extension);
                try {
                    File.Copy(file, tempFile, true);
                    using (var fileStream = new FileStream(tempFile, FileMode.Open, FileAccess.Read)) {
                        IWorkbook workbook = null;
                        if (extension.EndsWith(".xls"))
                        {
                            workbook = new HSSFWorkbook(fileStream);
                        }
                        else if (extension.EndsWith(".xlsx"))
                        {
                            workbook = new XSSFWorkbook(fileStream);
                        }
                        if (workbook == null)
                        {
                            throw new Exception("不支持的文件后缀 : " + extension);
                        }
                        for (var i = 0; i < workbook.NumberOfSheets; ++i)
                        {
                            var sheet = workbook.GetSheetAt(i);
                            if (sheet.SheetName.IsInvalid())
                            {
                                continue;
                            }
                            try {
                                var builder = new TableBuilder();
                                builder.SetPackageName(packageName);
                                builder.SetName(isFileName ? fileName : sheet.SheetName.Trim());
                                builder.SetSuffix(suffix);
                                builder.SetFileSuffix(fileSuffix);
                                builder.SetSpawn(spawnList);
                                builder.Parse(sheet, data, languageDirectory, parser);
                                Logger.info($"文件:[{file}] Sheet:[{sheet.SheetName}] 解析完成");
                                if (builder.IsSpawn)
                                {
                                    if (successSpawns.ContainsKey(builder.Spawn))
                                    {
                                        successSpawns[builder.Spawn].Add(builder.Name);
                                    }
                                    else
                                    {
                                        successSpawns[builder.Spawn] = new List <string>()
                                        {
                                            builder.Name
                                        };
                                    }
                                }
                                else
                                {
                                    successTables.Add(builder.Name);
                                }
                            } catch (Exception e) {
                                Logger.error($"文件:[{file}] Sheet:[{sheet.SheetName}] 解析出错 : " + e.ToString());
                            }
                        }
                    }
                } catch (Exception e) {
                    Logger.error($"文件 [{file}] 执行出错 : " + e.ToString());
                } finally {
                    File.Delete(tempFile);
                }
            }
            foreach (var pair in languageDirectory)
            {
                var language = pair.Key;
                foreach (var table in parser.Tables)
                {
                    ScorpioConversion.Util.CreateDataClass(language, packageName, table.Key, table.Value.Fields, pair.Value, fileSuffix);
                }
                foreach (var @enum in parser.Enums)
                {
                    ScorpioConversion.Util.CreateEnumClass(language, packageName, @enum.Value, pair.Value, fileSuffix);
                }
            }
            if (script.HasGlobal("BuildOver"))
            {
                script.GetGlobal("BuildOver").call(ScriptValue.Null, successTables, successSpawns, command, parser);
            }
        }
Beispiel #2
0
        static void Reset(CommandLine command, string[] args)
        {
            var files    = command.GetValue("-files");                      //需要转换的文件 多文件[{Util.Separator}]隔开
            var paths    = command.GetValue("-paths");                      //需要转换的文件目录 多路径[{Util.Separator}]隔开
            var config   = command.GetValue("-config");                     //配置文件路径 多路径[{Util.Separator}]隔开
            var parser   = new PackageParser();
            var fileList = new List <string>();                             //所有要生成的excel文件

            Util.Split(config, (file) => { parser.Parse(file); });
            Util.Split(files, (file) => { fileList.Add(Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, file))); });
            Util.Split(paths, (path) => {
                foreach (var file in Directory.GetFiles(Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, path)), "*", SearchOption.AllDirectories))
                {
                    // $ 开头的 excel文件是 打开 excel 临时文件
                    if (!file.Contains("~$") && (file.EndsWith(".xls") || file.EndsWith(".xlsx")))
                    {
                        fileList.Add(file);
                    }
                }
            });
            foreach (var file in fileList)
            {
                var fileName  = Path.GetFileNameWithoutExtension(file).Trim();
                var extension = Path.GetExtension(file);
                try {
                    IWorkbook workbook = null;
                    using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read)) {
                        if (extension.EndsWith(".xls"))
                        {
                            workbook = new HSSFWorkbook(fileStream);
                        }
                        else if (extension.EndsWith(".xlsx"))
                        {
                            workbook = new XSSFWorkbook(fileStream);
                        }
                        if (workbook == null)
                        {
                            throw new Exception("不支持的文件后缀 : " + extension);
                        }
                    }
                    for (var i = 0; i < workbook.NumberOfSheets; ++i)
                    {
                        var sheet = workbook.GetSheetAt(i);
                        if (sheet.SheetName.IsInvalid())
                        {
                            continue;
                        }
                        try {
                            new TableBuilder().Reset(workbook, sheet, parser);
                        } catch (Exception e) {
                            Logger.error($"文件:[{file}] Sheet:[{sheet.SheetName}] 解析出错 : " + e.ToString());
                        }
                    }
                    using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.ReadWrite)) {
                        workbook.Write(fileStream);
                    }
                } catch (Exception e) {
                    Logger.error($"文件 [{file}] 执行出错 : " + e.ToString());
                }
            }
        }
Beispiel #3
0
        public void Compile()
        {
            // Already processing?
            if (interactionModel == null || processingStack.Contains(interactionModel.PackageLocation.ToString(MifCompiler.NAME_FORMAT)))
            {
                return;
            }

            // Add to the processing stack
            processingStack.Add(interactionModel.PackageLocation.ToString(MifCompiler.NAME_FORMAT));

            // Otput the name of the package.
            System.Diagnostics.Trace.WriteLine(string.Format("Compiling interaction model package '{0}'...", interactionModel.PackageLocation.ToString(MifCompiler.NAME_FORMAT)), "debug");

            // Check if the package has already been "compiled"
            if (ClassRepository.ContainsKey(interactionModel.PackageLocation.ToString(MifCompiler.NAME_FORMAT)))
            {
                return; // Already compiled
            }
            // Process the interaction
            MohawkCollege.EHR.gpmr.COR.Interaction interaction = new MohawkCollege.EHR.gpmr.COR.Interaction();
            interaction.Name = interactionModel.PackageLocation.ToString(MifCompiler.NAME_FORMAT);
            //interaction.Realm = interactionModel.PackageLocation.Realm;

            // Process business names
            foreach (BusinessName bn in interactionModel.BusinessName ?? new List <BusinessName>())
            {
                if (bn.Language == MifCompiler.Language || bn.Language == null)
                {
                    interaction.BusinessName = bn.Name;
                }
            }

            // Process documentation
            if (interactionModel.Annotations != null)
            {
                interaction.Documentation = DocumentationParser.Parse(interactionModel.Annotations.Documentation);
            }

            // Set the derivation from pointer
            interaction.DerivedFrom = interactionModel;

            // Trigger event
            interaction.TriggerEvent = interactionModel.InvokingTriggerEvent.ToString(MifCompiler.NAME_FORMAT);

            // Types
            TypeReference tr = new TypeReference();

            // Has the entry class been created yet?
            if (!ClassRepository.ContainsKey(interactionModel.ArgumentMessage.ToString(MifCompiler.NAME_FORMAT)))
            {
                // Process
                PackageParser.Parse(interactionModel.ArgumentMessage.ToString(MifCompiler.NAME_FORMAT), repository, ClassRepository);
            }

            var entry = (ClassRepository[interactionModel.ArgumentMessage.ToString(MifCompiler.NAME_FORMAT)] as MohawkCollege.EHR.gpmr.COR.SubSystem);

            // Could we even find the model?
            if (entry == null)
            {
                System.Diagnostics.Trace.WriteLine(string.Format("Could not find the argument message '{0}', interaction '{1}' can't be processed",
                                                                 interactionModel.ArgumentMessage.ToString(MifCompiler.NAME_FORMAT), interaction.Name), "error");
                return;
            }
            else if (entry.EntryPoint.Count == 0)
            {
                System.Diagnostics.Trace.WriteLine(string.Format("Argument message '{0}' must have an entry point, interaction '{1}' can't be processed",
                                                                 entry.Name, interaction.Name), "error");
                return;
            }
            else if (entry.EntryPoint.Count != 1)
            {
                System.Diagnostics.Trace.WriteLine(string.Format("Ambiguous entry point for argument message '{0}', interaction '{1}' can't be processed", entry.Name, interaction.Name), "error");
                return;
            }

            // Set the entry class
            tr          = entry.EntryPoint[0].CreateTypeReference();
            tr.MemberOf = ClassRepository; // Set member of property
            ProcessTypeParameters(interactionModel.ArgumentMessage.ParameterModel, tr, interaction);
            interaction.MessageType = tr;

            #region Response types
            if (interactionModel.ReceiverResponsibilities != null)
            {
                // Create the array
                interaction.Responses = new List <MohawkCollege.EHR.gpmr.COR.Interaction>();

                //  Iterate through
                foreach (ReceiverResponsibility rr in interactionModel.ReceiverResponsibilities)
                {
                    if (rr.InvokeInteraction == null)
                    {
                        System.Diagnostics.Trace.WriteLine("Invoking interaction on receiver responsibility is missing", "warn");
                        continue;
                    }

                    // Does the receiver responsibility exist in the class repository
                    if (!ClassRepository.ContainsKey(rr.InvokeInteraction.ToString(MifCompiler.NAME_FORMAT)))
                    {
                        InteractionCompiler icc = new InteractionCompiler();
                        icc.PackageRepository = repository;
                        icc.Package           = repository.Find(o => o.PackageLocation.ToString(MifCompiler.NAME_FORMAT) == rr.InvokeInteraction.ToString(MifCompiler.NAME_FORMAT));
                        icc.ClassRepository   = ClassRepository;
                        icc.Compile();
                    }

                    MohawkCollege.EHR.gpmr.COR.Feature foundFeature = null;
                    if (ClassRepository.TryGetValue(rr.InvokeInteraction.ToString(MifCompiler.NAME_FORMAT), out foundFeature))
                    {
                        // Reason element for documentation
                        if (rr.Reason != null && (rr.Reason.Language == MifCompiler.Language || rr.Reason.Language == null) &&
                            (rr.Reason.MarkupElements != null || rr.Reason.MarkupText != null))
                        {
                            MohawkCollege.EHR.gpmr.COR.Documentation.TitledDocumentation td = new MohawkCollege.EHR.gpmr.COR.Documentation.TitledDocumentation()
                            {
                                Title = "Reason", Name = "Reason", Text = new List <string>()
                            };
                            if (rr.Reason.MarkupText != null)
                            {
                                td.Text.Add(rr.Reason.MarkupText);
                            }
                            if (rr.Reason.MarkupElements != null)
                            {
                                foreach (XmlElement xe in rr.Reason.MarkupElements)
                                {
                                    td.Text.Add(xe.OuterXml.Replace(" xmlns:html=\"http://www.w3.org/1999/xhtml\"", "").Replace("html:", ""));
                                }
                            }

                            // Append the documentation
                            if (interaction.Documentation == null)
                            {
                                interaction.Documentation = new MohawkCollege.EHR.gpmr.COR.Documentation();
                            }
                            if (interaction.Documentation.Other == null)
                            {
                                interaction.Documentation.Other = new List <MohawkCollege.EHR.gpmr.COR.Documentation.TitledDocumentation>();
                            }
                            interaction.Documentation.Other.Add(td);
                        }
                        interaction.Responses.Add(foundFeature as MohawkCollege.EHR.gpmr.COR.Interaction);
                    }
                    else
                    {
                        System.Diagnostics.Trace.WriteLine(String.Format("Can't find response interaction '{0}'...", rr.InvokeInteraction.ToString(MifCompiler.NAME_FORMAT)), "warn");
                    }
                }
            }
            #endregion

            // Fire the complete method
            interaction.FireParsed();
        }
        public void ParseAssociation(Association asc, Dictionary <string, Package> derivationSuppliers)
        {
            // There are two scenarios
            // A: Two traversable connections
            // B: A traversable and non traversable end


            // Case A: Two traversable connections, this means that the connection appears in both classes
            if (asc.Ends[0] is AssociationEnd && asc.Ends[1] is AssociationEnd)
            {
                // Make processing a little easier
                AssociationEnd[] ends = new AssociationEnd[] {
                    asc.Ends[0] as AssociationEnd,
                    asc.Ends[1] as AssociationEnd
                };


                // Loop so we write the code once
                for (int i = 0; i < 2; i++)
                {
                    Property p = new Property();
                    p.Name = ends[i].Name;

                    // Business Name
                    foreach (BusinessName bn in ends[i].BusinessName ?? new List <BusinessName>())
                    {
                        if (bn.Language == MifCompiler.Language || bn.Language == null)
                        {
                            p.BusinessName = bn.Name;
                        }
                    }

                    // The multiplicity of the opposing end influences the property on this end of the
                    // association
                    p.MinOccurs   = ends[1 - i].MinimumMultiplicity;
                    p.MaxOccurs   = ends[1 - i].MaximumMultiplicity;
                    p.Conformance = ends[1 - i].IsMandatory ? ClassContent.ConformanceKind.Mandatory :
                                    ends[1 - i].Conformance == ConformanceKind.Required ? ClassContent.ConformanceKind.Required :
                                    ends[1 - i].MinimumMultiplicity == "1" ? ClassContent.ConformanceKind.Populated :
                                    ClassContent.ConformanceKind.Optional;

                    // The type of this end is the type of the association
                    p.Type = CreateTypeReference(ends[i], p);

                    if (p.Type.Name == null)
                    {
                        if (p.Documentation == null)
                        {
                            p.Documentation = new MohawkCollege.EHR.gpmr.COR.Documentation();
                        }
                        if (p.Documentation.Description == null)
                        {
                            p.Documentation.Description = new List <string>();
                        }

                        p.Documentation.Description.Add(String.Format("GPMR: Association to type '{0}' was ignored and set as nothing as '{0}' could not be found. You should consider revising this", ends[i].ParticipantClassName));
                    }

                    // Traversable association
                    p.PropertyType = Property.PropertyTypes.TraversableAssociation;

                    // Annotations
                    if (asc.Annotations != null)
                    {
                        p.Documentation = MohawkCollege.EHR.gpmr.Pipeline.Compiler.Mif20.Parsers.DocumentationParser.Parse(asc.Annotations.Documentation);
                    }

                    // Find the class this end belongs in
                    if (!ClassRepository.ContainsKey(string.Format("{0}.{1}", staticModel.PackageLocation.Artifact == ArtifactKind.RIM ? "RIM" : staticModel.PackageLocation.ToString(MifCompiler.NAME_FORMAT),
                                                                   ends[1 - i].ParticipantClassName)))
                    {
                        throw new Exception(string.Format("Can't bind property '{0}' to class '{1}'... Class does not exist", p.Name, ends[1 - i].ParticipantClassName));
                    }

                    // Set derivation
                    p.DerivedFrom = asc;
                    p.SortKey     = asc.SortKey;

                    try
                    {
                        if (ends[i].DerivedFrom != null)
                        {
                            p.Realization = new List <ClassContent>();
                            foreach (var dei in ends[i].DerivedFrom)
                            {
                                MohawkCollege.EHR.gpmr.COR.Feature f = null;
                                if (!ClassRepository.TryGetValue(string.Format("{0}.{1}", derivationSuppliers[dei.StaticModelDerivationId].PackageLocation.Artifact == ArtifactKind.RIM ? "RIM" : derivationSuppliers[dei.StaticModelDerivationId].PackageLocation.ToString(MifCompiler.NAME_FORMAT),
                                                                               dei.ClassName), out f))
                                {
                                    System.Diagnostics.Trace.WriteLine(String.Format("Can't find derivation class '{0}' for association '{1}'", dei.ClassName, ends[i].Name), "debug");
                                }
                                else
                                {
                                    ClassContent cc = (f as MohawkCollege.EHR.gpmr.COR.Class).GetFullContent().Find(o => o.Name == dei.AssociationEndName);
                                    p.Realization.Add(cc);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteLine(String.Format("Cannot append derivation information to {0} (reason:{1})", ends[i].Name, ex.ToString()), "error");
                    }

                    // Add to repository
                    if (ends[1 - i].Conformance != ConformanceKind.NotPermitted)
                    {
                        (ClassRepository[string.Format("{0}.{1}", staticModel.PackageLocation.Artifact == ArtifactKind.RIM ? "RIM" : staticModel.PackageLocation.ToString(MifCompiler.NAME_FORMAT),
                                                       ends[1 - i].ParticipantClassName)] as MohawkCollege.EHR.gpmr.COR.Class).AddContent(p);
                    }
                }
            }
            else // Case 2: A traversable and non-traversable connection,
            {
                AssociationEnd ae = (asc.Ends[0] as AssociationEnd) ?? (asc.Ends[1] as AssociationEnd);
                NonTraversableAssociationEnd ntae = (asc.Ends[0] as NonTraversableAssociationEnd) ?? (asc.Ends[1] as NonTraversableAssociationEnd);

                // Start to process the property.
                ClassContent cc;
                if (ae.ChoiceItem != null && ae.ChoiceItem.Count > 0)
                {
                    cc = new Choice();
                }
                else
                {
                    cc = new Property();
                }

                cc.Name = ae.Name;

                // Business Name
                foreach (BusinessName bn in ae.BusinessName ?? new List <BusinessName>())
                {
                    if (bn.Language == MifCompiler.Language || bn.Language == null)
                    {
                        cc.BusinessName = bn.Name;
                    }
                }

                // The multiplicity of the opposing end influences the property on this end of the
                // association
                cc.MinOccurs   = ae.MinimumMultiplicity;
                cc.MaxOccurs   = ae.MaximumMultiplicity;
                cc.Conformance = ae.IsMandatory ? ClassContent.ConformanceKind.Mandatory :
                                 ae.Conformance == ConformanceKind.Required && ae.MinimumMultiplicity == "1" ? ClassContent.ConformanceKind.Populated :
                                 ae.Conformance == ConformanceKind.Required ? ClassContent.ConformanceKind.Required :
                                 ClassContent.ConformanceKind.Optional;

                #region Bind To Class
                // Find the class on the traversable end, we'll need to append the property to it
                if (!ClassRepository.ContainsKey(string.Format("{0}.{1}", staticModel.PackageLocation.Artifact == ArtifactKind.RIM ? "RIM" : staticModel.PackageLocation.ToString(MifCompiler.NAME_FORMAT),
                                                               ntae.ParticipantClassName)))
                {
                    System.Diagnostics.Trace.WriteLine(string.Format("Can't bind property '{0}' to class '{1}'... Class does not exist", cc.Name, ntae.ParticipantClassName), "error");
                }
                //throw new Exception(string.Format("Can't bind property '{0}' to class '{1}'... Class does not exist", p.Name, ae.ParticipantClassName));
                else if (ae.Conformance != ConformanceKind.NotPermitted) // Append the property to the class
                {
                    MohawkCollege.EHR.gpmr.COR.Class cls = ClassRepository[string.Format("{0}.{1}", staticModel.PackageLocation.Artifact == ArtifactKind.RIM ? "RIM" : staticModel.PackageLocation.ToString(MifCompiler.NAME_FORMAT),
                                                                                         ntae.ParticipantClassName)] as MohawkCollege.EHR.gpmr.COR.Class;
                    cls.AddContent(cc);
                    // Add template parameter
                    if (templateParameters.ContainsKey(ae.ParticipantClassName))
                    {
                        cls.AddTypeParameter(templateParameters[ae.ParticipantClassName]);
                    }
                }
                else
                {
                    return;
                }

                #endregion

                // Choice or property?
                if (cc is Property)
                {
                    Property p = cc as Property;
                    p.Type = CreateTypeReference(ae, p);
                    if (p.Type.Name == null)
                    {
                        if (p.Documentation == null)
                        {
                            p.Documentation = new MohawkCollege.EHR.gpmr.COR.Documentation();
                        }
                        if (p.Documentation.Description == null)
                        {
                            p.Documentation.Description = new List <string>();
                        }
                        p.Documentation.Description.Add(String.Format("GPMR: Association to type '{0}' was ignored and set as nothing as '{0}' could not be found. You should consider revising this", ae.ParticipantClassName));
                    }
                    // Traversable association
                    p.PropertyType = Property.PropertyTypes.TraversableAssociation;
                }
                else // Choice
                {
                    Choice chc = cc as Choice;
                    chc.MemberOf = ClassRepository;
                    chc.Content  = new List <ClassContent>();

                    // Get a type reference to the CMET or main type to be used
                    TypeReference trf = CreateTypeReference(ae, cc);

                    // Cannot find association
                    if (trf.Name == null)
                    {
                        if (chc.Documentation == null)
                        {
                            chc.Documentation = new MohawkCollege.EHR.gpmr.COR.Documentation();
                        }
                        if (chc.Documentation.Description == null)
                        {
                            chc.Documentation.Description = new List <string>();
                        }

                        chc.Documentation.Description.Add(String.Format("GPMR: Association to type '{0}' was ignored and set as nothing as '{0}' could not be found. You should consider revising this", ae.ParticipantClassName));
                    }

                    // Warn
                    if (trf.Class == null)
                    {
                        throw new InvalidOperationException(String.Format("Cannot make association to class '{0}' as it was not defined!", ae.ParticipantClassName));
                    }
                    if (ae.ChoiceItem.Count != trf.Class.SpecializedBy.Count)
                    {
                        System.Diagnostics.Trace.WriteLine(string.Format("Number of choices on property does not match the number of child classes for its data type for association '{0}'", cc.Name), "warn");
                    }

                    chc.Content.AddRange(ProcessAssociations(ae, ae.ChoiceItem, trf, chc));

                    /*
                     * // Specializations
                     * List<TypeReference> specializations = new List<TypeReference>(trf.Class.SpecializedBy);
                     *
                     * // Flatten choice members
                     * for (int i = 0; i < ae.ChoiceItem.Count ; i++)
                     *  if (ae.ChoiceItem[i].Specialization != null && ae.ChoiceItem[i].Specialization.Count > 0)
                     *  {
                     *      AssociationEndSpecialization aes = ae.ChoiceItem[i]; // Get local reference
                     *      // Remove redundant data
                     *      ae.ChoiceItem.RemoveAt(i); // Remove the redundant choice item
                     *      i--; // redo this item
                     *      // is this a cmet?
                     *      if (ClassRepository.ContainsKey(aes.ClassName) && ClassRepository[aes.ClassName] is CommonTypeReference)
                     *      {
                     *          specializations.RemoveAll(o => o.Name == (ClassRepository[aes.ClassName] as CommonTypeReference).Class.Name);
                     *          specializations.AddRange((ClassRepository[aes.ClassName] as CommonTypeReference).Class.Class.SpecializedBy);
                     *      }
                     *
                     *      ae.ChoiceItem.AddRange(aes.Specialization); // Now add the choices
                     *  }
                     *
                     * int ip = 0;
                     *
                     * // Add choice members
                     * foreach (AssociationEndSpecialization aes in ae.ChoiceItem)
                     * {
                     *  Property p = new Property();
                     *
                     *  // Now, construct the properties from the CMET entries
                     *  // Try ...
                     *
                     *  var rClassName = specializations.Find(o => o.Class != null && o.Class.Name.Equals(aes.ClassName));
                     *
                     *  // Determine if this is a CMET
                     *  if (ClassRepository.ContainsKey(aes.ClassName) && ClassRepository[aes.ClassName] is CommonTypeReference)
                     *      p.Type = (ClassRepository[aes.ClassName] as CommonTypeReference).Class;
                     *  else if (rClassName != null) // Try using the inheritence method
                     *      p.Type = rClassName;
                     *  else if (ClassRepository.ContainsKey(String.Format("{0}.{1}", staticModel.PackageLocation.ToString(MifCompiler.NAME_FORMAT), aes.ClassName)))
                     *      p.Type = ((ClassRepository[String.Format("{0}.{1}", staticModel.PackageLocation.ToString(MifCompiler.NAME_FORMAT), aes.ClassName)] as MohawkCollege.EHR.gpmr.COR.Class).CreateTypeReference());
                     *  else
                     *  {
                     *      System.Diagnostics.Trace.WriteLine(string.Format("Class '{2}' of CMET '{1}' could not be found or was not processed. The processing of the property '{0}' in '{3}.{4}' will NOT continue", cc.Name, aes.ClassName, ae.ParticipantClassName, staticModel.PackageLocation.ToString(MifCompiler.NAME_FORMAT), ntae.ParticipantClassName), "error");
                     *      break;
                     *  }
                     *
                     *  p.PropertyType = Property.PropertyTypes.TraversableAssociation;
                     *
                     *  // Fix bug with optional choice
                     *  p.MinOccurs = chc.MinOccurs;
                     *  p.MaxOccurs = chc.MaxOccurs;
                     *  p.Conformance = chc.Conformance;
                     *
                     *  p.DerivedFrom = aes;
                     *  p.Documentation = p.Type.ClassDocumentation;
                     *
                     *  p.MemberOf = ClassRepository;
                     *  p.Container = chc;
                     *
                     *  // Traversal names
                     *  p.Name = aes.TraversalName;
                     *
                     *  chc.Content.Add(p);
                     *
                     *  ip++;
                     * }
                     */
                }


                // Annotations
                if (asc.Annotations != null)
                {
                    cc.Documentation = MohawkCollege.EHR.gpmr.Pipeline.Compiler.Mif20.Parsers.DocumentationParser.Parse(asc.Annotations.Documentation);
                }

                // Set derivation
                cc.DerivedFrom = asc;
                cc.SortKey     = ae.SortKey;

                try
                {
                    if (ae.DerivedFrom != null)
                    {
                        cc.Realization = new List <ClassContent>();
                        foreach (var dei in ae.DerivedFrom)
                        {
                            MohawkCollege.EHR.gpmr.COR.Feature ss = null;
                            Package derivationPkg = null;
                            if (!derivationSuppliers.TryGetValue(dei.StaticModelDerivationId, out derivationPkg) || derivationPkg == null)
                            {
                                continue;
                            }

                            // Has the package been compiled?
                            if (!ClassRepository.TryGetValue(string.Format("{0}", derivationPkg.PackageLocation.Artifact == ArtifactKind.RIM ? "RIM" : derivationPkg.PackageLocation.ToString(MifCompiler.NAME_FORMAT)), out ss))
                            {
                                // Attempt to parse
                                PackageParser.Parse(derivationPkg.PackageLocation.ToString(MifCompiler.NAME_FORMAT), derivationPkg.MemberOfRepository, ClassRepository);
                                // Ditch if still can't find
                                if (!ClassRepository.TryGetValue(string.Format("{0}", derivationPkg.PackageLocation.Artifact == ArtifactKind.RIM ? "RIM" : derivationPkg.PackageLocation.ToString(MifCompiler.NAME_FORMAT)), out ss))
                                {
                                    System.Diagnostics.Trace.WriteLine(String.Format("Can't find derivation class '{0}' for association '{1}' (derivation supplier {2})", dei.ClassName, dei.AssociationEndName, dei.StaticModelDerivationId), "warn");
                                }
                            }

                            // Feature was found
                            var f = (ss as MohawkCollege.EHR.gpmr.COR.SubSystem).FindClass(dei.ClassName);
                            if (f != null)
                            {
                                // Realized Class content
                                ClassContent rcc = f.GetFullContent().Find(o => o.Name == dei.AssociationEndName);
                                cc.Realization.Add(rcc);
                            }
                            else
                            {
                                System.Diagnostics.Trace.WriteLine(String.Format("Can't find derivation class '{0}' for association '{1}' (derivation supplier {2})", dei.ClassName, dei.AssociationEndName, dei.StaticModelDerivationId), "warn");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(String.Format("Cannot append derivation information to {0} (reason:{1})", ae.Name, ex.ToString()), "error");
                }

                (cc.Container as MohawkCollege.EHR.gpmr.COR.Class).Content.Sort(new ClassContent.Comparator());
            }
        }
Beispiel #5
0
        private void ProcessTypeParameters(List <ParameterModel> parms, TypeReference baseRef, MohawkCollege.EHR.gpmr.COR.Interaction ownerInteraction)
        {
            if (parms != null && baseRef.Class != null && baseRef.Class.TypeParameters != null && parms.Count != baseRef.Class.TypeParameters.Count)
            {
                Trace.WriteLine(
                    string.Format("The argument message '{0}.{1}' requires {2} parameter messages however interaction '{3}' only specifies {4}",
                                  baseRef.Class.ContainerName, baseRef.Class.Name, baseRef.Class.TypeParameters.Count, ownerInteraction.Name, parms.Count)
                    , "warn");
            }
            else if (parms == null || parms.Count == 0)
            {
                return;                                         // Check for null
            }
            // Setup the parameters
            foreach (ParameterModel p in parms)
            {
                // Check if the parameter model exists
                if (!ClassRepository.ContainsKey(p.ToString(MifCompiler.NAME_FORMAT)))
                {
                    PackageParser.Parse(p.ToString(MifCompiler.NAME_FORMAT), repository, ClassRepository); // Process the package if it doesn't
                }
                // Check again, if this fails all hell breaks loose
                var model = (ClassRepository[p.ToString(MifCompiler.NAME_FORMAT)] as MohawkCollege.EHR.gpmr.COR.SubSystem);
                if (model == null)
                {
                    System.Diagnostics.Trace.WriteLine(string.Format("Could not find the parameter model '{0}'",
                                                                     p.ToString(MifCompiler.NAME_FORMAT)), "error");
                    return;
                }
                else if (model.EntryPoint.Count == 0)
                {
                    System.Diagnostics.Trace.WriteLine(string.Format("Parameter model '{0}' must have an entry point",
                                                                     p.ToString(MifCompiler.NAME_FORMAT)), "error");
                    return;
                }
                else if (model.EntryPoint.Count != 1)
                {
                    System.Diagnostics.Trace.WriteLine(string.Format("Ambiguous entry point for parameter model '{0}'",
                                                                     p.ToString(MifCompiler.NAME_FORMAT)), "error");
                    return;
                }

                // Entry class for p
                TypeReference parmRef = model.EntryPoint[0].CreateTypeReference();

                // Find any reference and set an alternate traversal name for that property
                if (p.Specialization.Count == 0)
                {
                    AppendTraversalName(baseRef, p.ParameterName, p.TraversalName, parmRef, ownerInteraction, new Stack <string>());
                }
                else
                {
                    ProcessSpecializations(p, p.Specialization, baseRef, ownerInteraction, null);
                }

                // Process Children
                ProcessTypeParameters(p.ParameterModel, parmRef, ownerInteraction);

                // Assign for tr as a parameter reference
                try
                {
                    baseRef.AddGenericSupplier(p.ParameterName, parmRef);
                }
                catch (ArgumentException e) // This is thrown when there are more than one supplier binding
                {
                    // Was more than one specified
                    if (baseRef.GenericSupplier.Exists(o => (o as TypeParameter).ParameterName == p.ParameterName))
                    {
                        //baseRef.GenericSupplier.RemoveAll(o => (o as TypeParameter).ParameterName == p.ParameterName);  // remove the existing type reference
                        // Add the generic supplier manually for the new type
                        baseRef.AddGenericSupplier(p.ParameterName, parmRef, false);
                        Trace.WriteLine(String.Format("Generic supplier {0} has been specified more than once, will use base object in it's place", p.ParameterName), "warn");
                    }
                }
                catch (Exception e)
                {
                    // JF - Some UV models attempt to bind to classes that don't support binding
                    if (baseRef.Class.TypeParameters == null)
                    {
                        System.Diagnostics.Trace.WriteLine(String.Format("{0} can't force bind because the target class has not template parameters", e.Message), "error");
                        if (MifCompiler.hostContext.Mode == Pipeline.OperationModeType.Quirks)
                        {
                            System.Diagnostics.Trace.WriteLine(String.Format("{0} will ignore this binding in order to continue. This interaction will effectively be useless", ownerInteraction.Name));
                        }
                        else
                        {
                            throw new InvalidOperationException(String.Format("Cannot bind parameter '{0}' to class '{1}' because '{1}' does not support templates", parmRef.Name, baseRef.Name));
                        }
                    }
                    else
                    {
                        System.Diagnostics.Trace.WriteLine(String.Format("{0} will try force binding", e.Message), "error");
                        foreach (var t in baseRef.Class.TypeParameters)
                        {
                            if (baseRef.GenericSupplier.Find(o => o.Name.Equals(t.ParameterName)) == null)
                            {
                                baseRef.AddGenericSupplier(t.ParameterName, parmRef);
                                System.Diagnostics.Trace.WriteLine(String.Format("Bound {0} to {1} in {2}", parmRef, t.ParameterName, baseRef), "warn");
                                break;
                            }
                        }
                    }
                }
            }
        }