示例#1
0
        internal async Task <bool> AddAsync(InstanceName instance, string ruleName, string filePath, CancellationToken cancellationToken)
        {
            _logger.WriteInfo($"Validate rule file {filePath}");

            var engineLogger = new EngineWrapperLogger(_logger);

            var(preprocessedRule, _) = await RuleFileParser.ReadFile(filePath, engineLogger, cancellationToken);

            try
            {
                var rule = new Engine.ScriptedRuleWrapper(ruleName, preprocessedRule, engineLogger);
                var(success, diagnostics) = rule.Verify();
                if (success)
                {
                    _logger.WriteInfo($"Rule file is valid");
                }
                else
                {
                    _logger.WriteInfo($"Rule file is invalid");
                    var messages = string.Join('\n', diagnostics.Select(d => d.ToString()));
                    if (!string.IsNullOrEmpty(messages))
                    {
                        _logger.WriteError($"Errors in the rule file {filePath}:\n{messages}");
                    }

                    return(false);
                }
            }
            catch
            {
                _logger.WriteInfo($"Rule file is invalid");
                return(false);
            }

            _logger.WriteVerbose($"Layout rule files");
            var inMemoryFiles = await PackagingFilesAsync(ruleName, preprocessedRule);

            _logger.WriteInfo($"Packaging rule {ruleName} complete.");

            _logger.WriteVerbose($"Uploading rule files to {instance.PlainName}");
            bool ok = await UploadRuleFilesAsync(instance, ruleName, inMemoryFiles, cancellationToken);

            if (ok)
            {
                _logger.WriteInfo($"All {ruleName} files successfully uploaded to {instance.PlainName}.");
            }

            if (preprocessedRule.Impersonate)
            {
                _logger.WriteInfo($"Configure {ruleName} to execute impersonated.");
                ok &= await ConfigureAsync(instance, ruleName, impersonate : true, cancellationToken : cancellationToken);

                if (ok)
                {
                    _logger.WriteInfo($"Updated {ruleName} configuration successfully.");
                }
            }

            return(ok);
        }
        public void RuleImportDirectiveParse_Succeeds(string ruleCode, int expectedImportCount)
        {
            (IPreprocessedRule ppRule, bool parsingSuccess) = RuleFileParser.Read(ruleCode.Mince());

            Assert.True(parsingSuccess);
            Assert.Equal(expectedImportCount, ppRule.Imports.Count);
        }
        public void RuleImpersonateDirectiveParse_Succeeds(string ruleCode)
        {
            (IPreprocessedRule ppRule, bool parsingSuccess) = RuleFileParser.Read(ruleCode.Mince());

            Assert.True(parsingSuccess);
            Assert.True(ppRule.Impersonate);
        }
        public void RuleCheckDirectiveParse_Succeeds(string ruleCode, bool expected)
        {
            (IPreprocessedRule ppRule, bool parsingSuccess) = RuleFileParser.Read(ruleCode.Mince());

            Assert.True(parsingSuccess);
            Assert.Equal(expected, ppRule.Settings.EnableRevisionCheck);
        }
示例#5
0
        internal ScriptedRuleWrapper(string ruleName, string[] ruleCode) : this(ruleName, new NullLogger())
        {
            (IPreprocessedRule preprocessedRule, bool parseSuccess) = RuleFileParser.Read(ruleCode);
            _ruleFileParseSuccess = parseSuccess;

            Initialize(preprocessedRule);
        }
        private async Task <IPreprocessedRule> LoadAndValidateRule(string ruleName, string filePath, CancellationToken cancellationToken)
        {
            var engineLogger = new EngineWrapperLogger(_logger);

            var(preprocessedRule, _) = await RuleFileParser.ReadFile(filePath, engineLogger, cancellationToken);

            try
            {
                var rule = new Engine.ScriptedRuleWrapper(ruleName, preprocessedRule, engineLogger);
                var(success, diagnostics) = rule.Verify();
                if (!success)
                {
                    var messages = string.Join('\n', diagnostics.Select(d => d.ToString()));
                    if (!string.IsNullOrEmpty(messages))
                    {
                        _logger.WriteError($"Errors in the rule file {filePath}:\n{messages}");
                    }

                    return(null);
                }
            }
            catch
            {
                return(null);
            }

            // Rule file is valid
            return(preprocessedRule);
        }
        public void RuleLanguageDirectiveParse_Fails(string ruleCode, RuleLanguage expectedLanguage = RuleLanguage.Unknown)
        {
            (IPreprocessedRule ppRule, bool parsingSuccess) = RuleFileParser.Read(ruleCode.Mince());

            Assert.False(parsingSuccess);
            Assert.Equal(expectedLanguage, ppRule.Language);
        }
示例#8
0
        private static async Task <IDictionary <string, string> > PackagingFilesAsync(string name, IPreprocessedRule preprocessedRule)
        {
            var inMemoryFiles = new Dictionary <string, string>
            {
                { $"{name}.rule", string.Join(Environment.NewLine, RuleFileParser.Write(preprocessedRule)) }
            };

            var assembly = Assembly.GetExecutingAssembly();

            // TODO we can deserialize a KuduFunctionConfig instead of using a fixed file...
            using (var stream = assembly.GetManifestResourceStream("aggregator.cli.Rules.function.json"))
            {
                using (var reader = new StreamReader(stream))
                {
                    var content = await reader.ReadToEndAsync();

                    inMemoryFiles.Add("function.json", content);
                }
            }

            using (var stream = assembly.GetManifestResourceStream("aggregator.cli.Rules.run.csx"))
            {
                using (var reader = new StreamReader(stream))
                {
                    var content = await reader.ReadToEndAsync();

                    inMemoryFiles.Add("run.csx", content);
                }
            }

            return(inMemoryFiles);
        }
        public void RuleLanguageDirectiveParse_Succeeds(string ruleCode, RuleLanguage expectedLanguage = RuleLanguage.Csharp)
        {
            (IPreprocessedRule ppRule, bool parsingSuccess) = RuleFileParser.Read(ruleCode.Mince());

            Assert.True(parsingSuccess);
            Assert.Equal(expectedLanguage, ppRule.Language);
        }
示例#10
0
        /// <inheritdoc />
        public async Task <IRule> GetRule(string name)
        {
            var ruleFilePath = GetRuleFilePath(name);

            var(preprocessedRule, _) = await RuleFileParser.ReadFile(ruleFilePath);

            return(new ScriptedRuleWrapper(name, preprocessedRule));
        }
示例#11
0
        public void TestCanReadToysSpec()
        {
            var parser = new RuleFileParser();

            var res = parser.ParseRules(@"toy.spec", new List <string>()
            {
                "S1"
            });

            Assert.AreEqual(res.Conditions.Count, 4);
            Assert.IsTrue(res.Conditions.ContainsKey("Conditions1"));
            Assert.IsTrue(res.Conditions.ContainsKey("Conditions2"));
            Assert.IsTrue(res.Conditions.ContainsKey("Expression1"));
            Assert.IsTrue(res.Conditions.ContainsKey("Expression2"));

            Assert.IsTrue(res.Conditions["Conditions1"]["S1"] == false);
            Assert.IsTrue(res.Conditions["Conditions1"]["S2"] == true);

            Assert.IsTrue(res.Conditions["Conditions2"]["S1"] == true);
            Assert.IsTrue(res.Conditions["Conditions2"]["S2"] == true);

            Assert.IsTrue(res.Conditions["Expression1"]["A"] == true);
            Assert.IsTrue(res.Conditions["Expression1"]["B"] == true);
            Assert.IsTrue(res.Conditions["Expression1"]["C"] == true);

            Assert.IsTrue(res.Conditions["Expression2"]["A"] == false);
            Assert.IsTrue(res.Conditions["Expression2"]["B"] == true);
            Assert.IsTrue(res.Conditions["Expression2"]["C"] == true);

            Assert.IsTrue(res.Experiments.Count == 2);
            Assert.IsTrue(res.Experiments.ContainsKey("Experiment1"));
            Assert.IsTrue(res.Experiments.ContainsKey("Experiment2"));

            Assert.IsTrue(res.Experiments["Experiment1"].Conditions[0]["S1"] == false);
            Assert.IsTrue(res.Experiments["Experiment1"].Conditions[0]["S2"] == true);
            Assert.IsTrue(res.Experiments["Experiment1"].Conditions[0]["A"] == true);
            Assert.IsTrue(res.Experiments["Experiment1"].Conditions[0]["B"] == true);
            Assert.IsTrue(res.Experiments["Experiment1"].Conditions[0]["C"] == true);


            Assert.IsTrue(res.Experiments["Experiment1"].Conditions[18]["A"] == false);
            Assert.IsTrue(res.Experiments["Experiment1"].Conditions[18]["B"] == true);
            Assert.IsTrue(res.Experiments["Experiment1"].Conditions[18]["C"] == true);
            Assert.IsTrue(res.Experiments["Experiment1"].Conditions[18].IsFixedPoint);

            Assert.IsTrue(res.Experiments["Experiment2"].Conditions[0]["S1"] == true);
            Assert.IsTrue(res.Experiments["Experiment2"].Conditions[0]["S2"] == true);
            Assert.IsTrue(res.Experiments["Experiment2"].Conditions[0]["A"] == false);
            Assert.IsTrue(res.Experiments["Experiment2"].Conditions[0]["B"] == true);
            Assert.IsTrue(res.Experiments["Experiment2"].Conditions[0]["C"] == true);


            Assert.IsTrue(res.Experiments["Experiment2"].Conditions[18]["A"] == true);
            Assert.IsTrue(res.Experiments["Experiment2"].Conditions[18]["B"] == true);
            Assert.IsTrue(res.Experiments["Experiment2"].Conditions[18]["C"] == true);
            Assert.IsTrue(res.Experiments["Experiment2"].Conditions[18].IsFixedPoint);
        }
        public void RuleImpersonateDirectiveParse_Succeeds()
        {
            string ruleCode = @".impersonate=onBehalfOfInitiator 
";

            (IPreprocessedRule ppRule, bool parsingSuccess) = RuleFileParser.Read(ruleCode.Mince());

            Assert.True(parsingSuccess);
            Assert.True(ppRule.Impersonate);
        }
        public void RuleLanguageReadWrite_Succeeds(string ruleCode)
        {
            var mincedCode = ruleCode.Mince();

            (IPreprocessedRule ppRule, _) = RuleFileParser.Read(mincedCode);

            var ruleCode2 = RuleFileParser.Write(ppRule);

            Assert.Equal(mincedCode, ruleCode2, StringComparer.OrdinalIgnoreCase);
        }
示例#14
0
        private static async Task <IDictionary <string, string> > PackagingFilesAsync(string ruleName, IPreprocessedRule preprocessedRule)
        {
            var inMemoryFiles = new Dictionary <string, string>
            {
                { $"{ruleName}.rule", string.Join(Environment.NewLine, RuleFileParser.Write(preprocessedRule)) }
            };

            //var assembly = Assembly.GetExecutingAssembly();
            //await inMemoryFiles.AddFunctionDefaultFiles(assembly);

            return(inMemoryFiles);
        }
示例#15
0
        public void TestCanReadPluriPotencySpec()
        {
            var parser = new RuleFileParser();

            var res = parser.ParseRules(@"C:\dev\Automate\GeneAutomate\GeneAutomate\Examples\pluripotency.spec", new List <string>()
            {
                "LIF"
            });

            var condition = res.Conditions;
            var exp       = res.Experiments;

            Assert.AreEqual(23, exp.Count);
            Assert.IsTrue(exp.ContainsKey("ExperimentOne"));
            Assert.IsTrue(exp.ContainsKey("ExperimentTwo"));
            Assert.IsTrue(exp.ContainsKey("ExperimentThree"));
            Assert.IsTrue(exp.ContainsKey("ExperimentFour"));
            Assert.IsTrue(exp.ContainsKey("ExperimentFive"));
            Assert.IsTrue(exp.ContainsKey("ExperimentSix"));
            Assert.IsTrue(exp.ContainsKey("ExperimentSeven"));
            Assert.IsTrue(exp.ContainsKey("ExperimentEight"));
            Assert.IsTrue(exp.ContainsKey("ExperimentNine"));
            Assert.IsTrue(exp.ContainsKey("ExperimentTen"));
            Assert.IsTrue(exp.ContainsKey("ExperimentEleven"));
            Assert.IsTrue(exp.ContainsKey("ExperimentTwelve"));
            Assert.IsTrue(exp.ContainsKey("ExperimentThirteen"));
            Assert.IsTrue(exp.ContainsKey("ExperimentFourteen"));
            Assert.IsTrue(exp.ContainsKey("ExperimentFifteen"));
            Assert.IsTrue(exp.ContainsKey("ExperimentSixteen"));
            Assert.IsTrue(exp.ContainsKey("ExperimentSeventeen"));
            Assert.IsTrue(exp.ContainsKey("ExperimentEighteen"));
            Assert.IsTrue(exp.ContainsKey("ExperimentNineteen"));
            Assert.IsTrue(exp.ContainsKey("ExperimentTwenty"));
            Assert.IsTrue(exp.ContainsKey("ExperimentTwentyOne"));
            Assert.IsTrue(exp.ContainsKey("ExperimentTwentyTwo"));
            Assert.IsTrue(exp.ContainsKey("ExperimentTwentyThree"));

            Assert.AreEqual(33, condition.Count);

            Assert.IsTrue(condition["2iPlusLifTfcp2l1Overexpression"]["MEKERK"] == false);
            Assert.IsTrue(condition["2iPlusLifTfcp2l1Overexpression"]["Oct4"] == true);
            Assert.IsTrue(condition["2iPlusLifTfcp2l1Overexpression"]["Sox2"] == true);
            Assert.IsTrue(condition["2iPlusLifTfcp2l1Overexpression"]["Nanog"] == true);
            Assert.IsTrue(condition["2iPlusLifTfcp2l1Overexpression"]["Esrrb"] == true);
            Assert.IsTrue(condition["2iPlusLifTfcp2l1Overexpression"]["Klf2"] == true);
            Assert.IsTrue(condition["2iPlusLifTfcp2l1Overexpression"]["Tfcp2l1"] == true);
            Assert.IsTrue(condition["2iPlusLifTfcp2l1Overexpression"]["Klf4"] == true);
            Assert.IsTrue(condition["2iPlusLifTfcp2l1Overexpression"]["Gbx2"] == true);
            Assert.IsTrue(condition["2iPlusLifTfcp2l1Overexpression"]["Tbx3"] == true);
            Assert.IsTrue(condition["2iPlusLifTfcp2l1Overexpression"]["Tcf3"] == false);
            Assert.IsTrue(condition["2iPlusLifTfcp2l1Overexpression"]["Sall4"] == true);
            Assert.IsTrue(condition["2iPlusLifTfcp2l1Overexpression"]["Stat3"] == true);
        }
示例#16
0
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
        private static async Task <IDictionary <string, string> > PackagingFilesAsync(string ruleName, IPreprocessedRule preprocessedRule)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
        {
            var inMemoryFiles = new Dictionary <string, string>
            {
                { $"{ruleName}.rule", string.Join(Environment.NewLine, RuleFileParser.Write(preprocessedRule)) }
            };

            //var assembly = Assembly.GetExecutingAssembly();
            //await inMemoryFiles.AddFunctionDefaultFiles(assembly);

            return(inMemoryFiles);
        }
        public void RuleLanguageDefaultsCSharp_Succeeds()
        {
            string ruleCode = @"
return $""Hello { self.WorkItemType } #{ self.Id } - { self.Title }!"";
";

            (IPreprocessedRule ppRule, bool parsingSuccess) = RuleFileParser.Read(ruleCode.Mince());

            Assert.Empty(ppRule.References);
            Assert.Empty(ppRule.Imports);
            Assert.NotEmpty(ppRule.RuleCode);
            Assert.Equal(RuleLanguage.Csharp, ppRule.Language);
            Assert.True(parsingSuccess);
        }
        public void RuleLanguageReadWrite_Succeeds()
        {
            string ruleCode = @".language=C#
.reference=System.Xml.XDocument
.import=System.Diagnostics

return $""Hello { self.WorkItemType } #{ self.Id } - { self.Title }!"";
";

            var mincedCode = ruleCode.Mince();

            (IPreprocessedRule ppRule, _) = RuleFileParser.Read(mincedCode);

            var ruleCode2 = RuleFileParser.Write(ppRule);

            Assert.Equal(mincedCode, ruleCode2, StringComparer.OrdinalIgnoreCase);
        }
#pragma warning disable S107 // Methods should not have too many parameters
        private async Task <bool> InvokeLocalAsyncImpl(string projectName, string @event, int workItemId, string ruleFilePath, bool dryRun, SaveMode saveMode, bool impersonateExecution, DevOpsLogon devopsLogonData, VssCredentials clientCredentials, CancellationToken cancellationToken)
#pragma warning restore S107 // Methods should not have too many parameters
        {
            string collectionUrl = devopsLogonData.Url;

            using (var devops = new VssConnection(new Uri(collectionUrl), clientCredentials))
            {
                await devops.ConnectAsync(cancellationToken);

                _logger.WriteInfo($"Connected to Azure DevOps");

                Guid teamProjectId;
                using (var projectClient = devops.GetClient <ProjectHttpClient>())
                {
                    _logger.WriteVerbose($"Reading Azure DevOps project data...");
                    var project = await projectClient.GetProject(projectName);

                    _logger.WriteInfo($"Project {projectName} data read.");
                    teamProjectId = project.Id;
                }

                using (var clientsContext = new AzureDevOpsClientsContext(devops))
                {
                    _logger.WriteVerbose($"Rule code found at {ruleFilePath}");
                    var(preprocessedRule, _) = await RuleFileParser.ReadFile(ruleFilePath, cancellationToken);

                    var rule = new Engine.ScriptedRuleWrapper(Path.GetFileNameWithoutExtension(ruleFilePath), preprocessedRule)
                    {
                        ImpersonateExecution = impersonateExecution
                    };

                    var engineLogger = new EngineWrapperLogger(_logger);
                    var engine       = new Engine.RuleEngine(engineLogger, saveMode, dryRun: dryRun);

                    var workItem = await clientsContext.WitClient.GetWorkItemAsync(projectName, workItemId, expand : WorkItemExpand.All, cancellationToken : cancellationToken);

                    string result = await engine.RunAsync(rule, teamProjectId, workItem, @event, clientsContext, cancellationToken);

                    _logger.WriteInfo($"Rule returned '{result}'");

                    return(true);
                }
            }
        }
示例#20
0
        internal async Task <bool> InvokeLocalAsync(string projectName, string @event, int workItemId, string ruleFilePath, bool dryRun, SaveMode saveMode, bool impersonateExecution, CancellationToken cancellationToken)
        {
            if (!File.Exists(ruleFilePath))
            {
                _logger.WriteError($"Rule code not found at {ruleFilePath}");
                return(false);
            }

            var devopsLogonData = DevOpsLogon.Load().connection;

            _logger.WriteVerbose($"Connecting to Azure DevOps using {devopsLogonData.Mode}...");
            var clientCredentials = default(VssCredentials);

            if (devopsLogonData.Mode == DevOpsTokenType.PAT)
            {
                clientCredentials = new VssBasicCredential(devopsLogonData.Mode.ToString(), devopsLogonData.Token);
            }
            else
            {
                _logger.WriteError($"Azure DevOps Token type {devopsLogonData.Mode} not supported!");
                throw new ArgumentOutOfRangeException(nameof(devopsLogonData.Mode));
            }

            string collectionUrl = devopsLogonData.Url;

            using (var devops = new VssConnection(new Uri(collectionUrl), clientCredentials))
            {
                await devops.ConnectAsync(cancellationToken);

                _logger.WriteInfo($"Connected to Azure DevOps");

                Guid teamProjectId;
                using (var projectClient = devops.GetClient <ProjectHttpClient>())
                {
                    _logger.WriteVerbose($"Reading Azure DevOps project data...");
                    var project = await projectClient.GetProject(projectName);

                    _logger.WriteInfo($"Project {projectName} data read.");
                    teamProjectId = project.Id;
                }

                using (var clientsContext = new AzureDevOpsClientsContext(devops))
                {
                    _logger.WriteVerbose($"Rule code found at {ruleFilePath}");
                    var(preprocessedRule, _) = await RuleFileParser.ReadFile(ruleFilePath, cancellationToken);

                    var rule = new Engine.ScriptedRuleWrapper(Path.GetFileNameWithoutExtension(ruleFilePath), preprocessedRule)
                    {
                        ImpersonateExecution = impersonateExecution
                    };

                    var engineLogger = new EngineWrapperLogger(_logger);
                    var engine       = new Engine.RuleEngine(engineLogger, saveMode, dryRun: dryRun);

                    var workItem = await clientsContext.WitClient.GetWorkItemAsync(projectName, workItemId, expand : WorkItemExpand.All, cancellationToken : cancellationToken);

                    string result = await engine.RunAsync(rule, teamProjectId, workItem, clientsContext, cancellationToken);

                    _logger.WriteInfo($"Rule returned '{result}'");

                    return(true);
                }
            }
        }
示例#21
0
        public AssemblyBuilder DoProcess(
            Object typeLib,
            string asmFilename,
            TypeLibImporterFlags flags,
            ITypeLibImporterNotifySink notifySink,
            byte[] publicKey,
            StrongNameKeyPair keyPair,
            string asmNamespace,
            Version asmVersion,
            bool isVersion2,
            bool isPreserveSig,
            string ruleSetFileName)
        {
            m_resolver = notifySink;

            TypeLib tlb = new TypeLib((TypeLibTypes.Interop.ITypeLib)typeLib);

            if (asmNamespace == null)
            {
                asmNamespace = tlb.GetDocumentation();

                string fileName = System.IO.Path.GetFileNameWithoutExtension(asmFilename);
                if (fileName != asmNamespace)
                {
                    asmNamespace = fileName;
                }

                //
                // Support for GUID_ManagedName (for namespace)
                //
                string customManagedNamespace = tlb.GetCustData(CustomAttributeGuids.GUID_ManagedName) as string;
                if (customManagedNamespace != null)
                {
                    customManagedNamespace = customManagedNamespace.Trim();
                    if (customManagedNamespace.ToUpper().EndsWith(".DLL"))
                    {
                        customManagedNamespace = customManagedNamespace.Substring(0, customManagedNamespace.Length - 4);
                    }
                    else if (customManagedNamespace.ToUpper().EndsWith(".EXE"))
                    {
                        customManagedNamespace = customManagedNamespace.Substring(0, customManagedNamespace.Length - 4);
                    }

                    asmNamespace = customManagedNamespace;
                }
            }

            //
            // Check for GUID_ExportedFromComPlus
            //
            object value = tlb.GetCustData(CustomAttributeGuids.GUID_ExportedFromComPlus);

            if (value != null)
            {
                // Make this a critical failure, instead of returning null which will be ignored.
                throw new TlbImpGeneralException(Resource.FormatString("Err_CircularImport", asmNamespace), ErrorCode.Err_CircularImport);
            }

            string strModuleName = asmFilename;

            if (asmFilename.Contains("\\"))
            {
                int nIndex;
                for (nIndex = strModuleName.Length; strModuleName[nIndex - 1] != '\\'; --nIndex)
                {
                    ;
                }
                strModuleName = strModuleName.Substring(nIndex);
            }

            // If the version information was not specified, then retrieve it from the typelib.
            if (asmVersion == null)
            {
                using (TypeLibAttr attr = tlb.GetLibAttr())
                {
                    asmVersion = new Version(attr.wMajorVerNum, attr.wMinorVerNum, 0, 0);
                }
            }

            // Assembly name should not have .DLL
            // while module name must contain the .DLL
            string strAsmName = String.Copy(strModuleName);

            if (strAsmName.EndsWith(".DLL", StringComparison.InvariantCultureIgnoreCase))
            {
                strAsmName = strAsmName.Substring(0, strAsmName.Length - 4);
            }

            AssemblyName assemblyName = new AssemblyName();

            assemblyName.Name = strAsmName;
            assemblyName.SetPublicKey(publicKey);
            assemblyName.Version = asmVersion;
            assemblyName.KeyPair = keyPair;

            m_assemblyBuilder = CreateAssemblyBuilder(assemblyName, tlb, flags);

            m_moduleBuilder = CreateModuleBuilder(m_assemblyBuilder, strModuleName);

            // Add a listener for the reflection load only resolve events.
            AppDomain           currentDomain     = Thread.GetDomain();
            ResolveEventHandler asmResolveHandler = new ResolveEventHandler(ReflectionOnlyResolveAsmEvent);

            currentDomain.ReflectionOnlyAssemblyResolve += asmResolveHandler;

            ConverterSettings settings;

            settings.m_isGenerateClassInterfaces = true;
            settings.m_namespace     = asmNamespace;
            settings.m_flags         = flags;
            settings.m_isVersion2    = isVersion2;
            settings.m_isPreserveSig = isPreserveSig;
            RuleEngine.InitRuleEngine(new TlbImpActionManager(),
                                      new TlbImpCategoryManager(),
                                      new TlbImpConditionManager(),
                                      new TlbImpOperatorManager());
            if (ruleSetFileName != null)
            {
                try
                {
                    RuleFileParser parser = new RuleFileParser(ruleSetFileName);
                    settings.m_ruleSet = parser.Parse();
                }
                catch (Exception ex)
                {
                    Output.WriteWarning(Resource.FormatString("Wrn_LoadRuleFileFailed",
                                                              ruleSetFileName, ex.Message),
                                        WarningCode.Wrn_LoadRuleFileFailed);
                    settings.m_ruleSet = null;
                }
            }
            else
            {
                settings.m_ruleSet = null;
            }

            m_converterInfo = new ConverterInfo(m_moduleBuilder, tlb, m_resolver, settings);

            //
            // Generate class interfaces
            // NOTE:
            // We have to create class interface ahead of time because of the need to convert default interfaces to
            // class interfafces. However, this creates another problem that the event interface is always named first
            // before the other interfaces, because we need to create the type builder for the event interface first
            // so that we can create a class interface that implement it. But in the previous version of TlbImp,
            // it doesn't have to do that because it can directly create a typeref with the class interface name,
            // without actually creating anything like the TypeBuilder. The result is that the name would be different
            // with interop assemblies generated by old tlbimp in this case.
            // Given the nature of reflection API, this cannot be easily workarounded unless we switch to metadata APIs.
            // I believe this is acceptable because this only happens when:
            // 1. People decide to migrate newer .NET framework
            // 2. The event interface name conflicts with a normal interface
            //
            // In this case the problem can be easily fixed with a global refactoring, so I wouldn't worry about that
            //
            if (m_converterInfo.GenerateClassInterfaces)
            {
                CreateClassInterfaces();
            }

            //
            // Generate the remaining types except coclass
            // Because during creating coclass, we require every type, including all the referenced type to be created
            // This is a restriction of reflection API that when you override a method in parent interface, the method info
            // is needed so the type must be already created and loaded
            //
            List <TypeInfo> coclassList = new List <TypeInfo>();
            int             nCount      = tlb.GetTypeInfoCount();

            for (int n = 0; n < nCount; ++n)
            {
                TypeInfo type = null;
                try
                {
                    type = tlb.GetTypeInfo(n);
                    string strType = type.GetDocumentation();

                    TypeInfo typeToProcess;
                    TypeAttr attrToProcess;

                    using (TypeAttr attr = type.GetTypeAttr())
                    {
                        TypeLibTypes.Interop.TYPEKIND kind = attr.typekind;
                        if (kind == TypeLibTypes.Interop.TYPEKIND.TKIND_ALIAS)
                        {
                            ConvCommon.ResolveAlias(type, attr.tdescAlias, out typeToProcess, out attrToProcess);
                            if (attrToProcess.typekind == TypeLibTypes.Interop.TYPEKIND.TKIND_ALIAS)
                            {
                                continue;
                            }
                            else
                            {
                                // We need to duplicate the definition of the user defined type in the name of the alias
                                kind          = attrToProcess.typekind;
                                typeToProcess = type;
                                attrToProcess = attr;
                            }
                        }
                        else
                        {
                            typeToProcess = type;
                            attrToProcess = attr;
                        }

                        switch (kind)
                        {
                        // Process coclass later because of reflection API requirements
                        case TypeLibTypes.Interop.TYPEKIND.TKIND_COCLASS:
                            coclassList.Add(typeToProcess);
                            break;

                        case TypeLibTypes.Interop.TYPEKIND.TKIND_ENUM:
                            m_converterInfo.GetEnum(typeToProcess, attrToProcess);
                            break;

                        case TypeLibTypes.Interop.TYPEKIND.TKIND_DISPATCH:
                        case TypeLibTypes.Interop.TYPEKIND.TKIND_INTERFACE:
                            m_converterInfo.GetInterface(typeToProcess, attrToProcess);
                            break;

                        case TypeLibTypes.Interop.TYPEKIND.TKIND_MODULE:
                            m_converterInfo.GetModule(typeToProcess, attrToProcess);
                            break;

                        case TypeLibTypes.Interop.TYPEKIND.TKIND_RECORD:
                            m_converterInfo.GetStruct(typeToProcess, attrToProcess);
                            break;

                        case TypeLibTypes.Interop.TYPEKIND.TKIND_UNION:
                            m_converterInfo.GetUnion(typeToProcess, attrToProcess);
                            break;
                        }

                        m_converterInfo.ReportEvent(
                            MessageCode.Msg_TypeInfoImported,
                            Resource.FormatString("Msg_TypeInfoImported", typeToProcess.GetDocumentation()));
                    }
                }
                catch (ReflectionTypeLoadException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TlbImpResolveRefFailWrapperException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TlbImpGeneralException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TypeLoadException)
                {
                    throw; // TypeLoadException is critical. Throw.
                }
                catch (Exception)
                {
                }
            }

            // Process coclass after processing all the other types
            foreach (TypeInfo type in coclassList)
            {
                using (TypeAttr attr = type.GetTypeAttr())
                {
                    try
                    {
                        m_converterInfo.GetCoClass(type, attr);
                    }
                    catch (ReflectionTypeLoadException)
                    {
                        throw; // Fatal failure. Throw
                    }
                    catch (TlbImpResolveRefFailWrapperException)
                    {
                        throw; // Fatal failure. Throw
                    }
                    catch (TlbImpGeneralException)
                    {
                        throw; // Fatal failure. Throw
                    }
                    catch (TypeLoadException)
                    {
                        throw; // TypeLoadException is critical. Throw.
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            //
            // Build an array of EventItfInfo & generate event provider / event sink helpers
            //

            Event.TCEAdapterGenerator eventAdapterGenerator = new Event.TCEAdapterGenerator();
            List <Event.EventItfInfo> eventItfList          = new List <Event.EventItfInfo>();

            foreach (IConvBase symbol in m_converterInfo.GetAllConvBase)
            {
                IConvInterface convInterface = symbol as IConvInterface;
                if (convInterface != null)
                {
                    if (convInterface.EventInterface != null)
                    {
                        Debug.Assert(convInterface.EventInterface is ConvEventInterfaceLocal);
                        ConvEventInterfaceLocal local = convInterface.EventInterface as ConvEventInterfaceLocal;

                        Type eventInterfaceType = convInterface.EventInterface.ManagedType;

                        // Build EventItfInfo and add to the list
                        Type               sourceInterfaceType = convInterface.ManagedType;
                        string             sourceInterfaceName = sourceInterfaceType.FullName;
                        Event.EventItfInfo eventItfInfo        = new Event.EventItfInfo(
                            eventInterfaceType.FullName,
                            sourceInterfaceName,
                            local.EventProviderName,
                            eventInterfaceType,
                            convInterface.ManagedType);
                        eventItfList.Add(eventItfInfo);
                    }
                }
            }

            eventAdapterGenerator.Process(m_moduleBuilder, eventItfList);

            return(m_assemblyBuilder);
        }
        public void RuleCheckDirectiveParse_Fails(string ruleCode)
        {
            (IPreprocessedRule _, bool parsingSuccess) = RuleFileParser.Read(ruleCode.Mince());

            Assert.False(parsingSuccess);
        }
        internal async Task <IEnumerable <RuleOutputData> > ListAsync(InstanceName instance, CancellationToken cancellationToken)
        {
            var kudu = GetKudu(instance);

            _logger.WriteInfo($"Retrieving Functions in {instance.PlainName}...");

            var webFunctionApp = await GetWebApp(instance, cancellationToken);

            cancellationToken.ThrowIfCancellationRequested();
            var configuration = await AggregatorConfiguration.ReadConfiguration(webFunctionApp);

            using (var client = new HttpClient())
            {
                KuduFunction[] kuduFunctions;
                using (var request = await kudu.GetRequestAsync(HttpMethod.Get, $"api/functions", cancellationToken))
                    using (var response = await client.SendAsync(request, cancellationToken))
                    {
                        var stream = await response.Content.ReadAsStreamAsync();

                        if (!response.IsSuccessStatusCode)
                        {
                            _logger.WriteError($"{response.ReasonPhrase} {await response.Content.ReadAsStringAsync()}");
                            return(Enumerable.Empty <RuleOutputData>());
                        }

                        using (var sr = new StreamReader(stream))
                            using (var jtr = new JsonTextReader(sr))
                            {
                                var js = new JsonSerializer();
                                kuduFunctions = js.Deserialize <KuduFunction[]>(jtr);
                            }
                    }

                List <RuleOutputData> ruleData = new List <RuleOutputData>();
                foreach (var kuduFunction in kuduFunctions)
                {
                    var ruleName    = kuduFunction.Name;
                    var ruleFileUrl = $"api/vfs/site/wwwroot/{ruleName}/{ruleName}.rule";
                    _logger.WriteInfo($"Retrieving Function Rule Details {ruleName}...");

                    using (var request = await kudu.GetRequestAsync(HttpMethod.Get, ruleFileUrl, cancellationToken))
                        using (var response = await client.SendAsync(request, cancellationToken))
                        {
                            var stream = await response.Content.ReadAsStreamAsync();

                            if (!response.IsSuccessStatusCode)
                            {
                                _logger.WriteError($"{response.ReasonPhrase} {await response.Content.ReadAsStringAsync()}");
                                continue;
                            }


                            var ruleCode = new List <string>();
                            using (var sr = new StreamReader(stream))
                            {
                                string line;
                                while ((line = sr.ReadLine()) != null)
                                {
                                    ruleCode.Add(line);
                                }
                            }

                            var ruleConfiguration = configuration.GetRuleConfiguration(ruleName);
                            var(preprocessedRule, _) = RuleFileParser.Read(ruleCode.ToArray());
                            ruleData.Add(new RuleOutputData(instance, ruleConfiguration, preprocessedRule.LanguageAsString()));
                        }
                }

                return(ruleData);
            }
        }