void Start()
 {
     context = new ContextBuilder()
         .ForContextView( this )
         .UseSignals()
         .Build();
 }
 // Build a Context
 void Start()
 {
     context = new ContextBuilder()
         .ForContextView( this )
         .SetStartSignalAndCommand<MainContextStartSignal, MainStartupCommand>()
         .MapBinder().AddFirstRunOnly( new ConfigureApplicationService().Setup )
         .Build();
 }
 void Start()
 {
     context = new ContextBuilder()
         .ForContextView(this)
         .SetStartSignalAndCommand<GameContextStartSignal, GameStartupCommand>()
         .MapBinder().Add( mapAllWithImplicitBinder )
         .MapBinder().Add( mapCommands )
         .Build();
 }
示例#4
0
        public void Run()
        {
            var builder = new ContextBuilder();
              using (var ctx = builder.NewContext()) {
            var root = ctx.GetRoot<IDomainRoot>();

            initSampleData(root);
            foreach (var comp in root.Companies) {
              Console.WriteLine(" {0} employees ", comp.Name);
              Console.WriteLine(" ==== ");

              foreach (var emp in comp.Employees)
            Console.WriteLine("{0} ({1}), {2} years old.",
              emp.Name, emp.Email, emp.Age);

              Console.WriteLine("\n");
            }
              }

              Console.WriteLine("Done.");
              Console.ReadKey();
        }
示例#5
0
        void Test02()
        {
            // Arrange
            var rootpayload = "rootpayload";
            var subject = new ContextBuilder<string>(() => rootpayload);
            var child1payload = "child1payload";
            subject.Enter("child1", () => child1payload);
            var child2payload = "child2payload";
            subject.Enter("child2", () => child2payload);
            subject.Leave();
            var child3payload = "child3payload";
            subject.Enter("child3", () => child3payload);
            subject.Leave();
            subject.Leave();

            Action<string, dynamic> build = (payload, obj) => { obj.property = payload; };

            // Act
            var result = subject.Flatten(build);

            // Assert
            //assert.equivalent([{name:'/',property:rootpayload},{name:'/child1',property:child1payload},{name:'/child1/child2',property:child2payload},{name:'/child1/child3',property:child3payload}], obj);
        }
 public MapBinderBuilder(ContextBuilder parent, List <Action <MVCSContext> > mapBindings)
 {
     _mapBindings = mapBindings;
     _parent      = parent;
 }
示例#7
0
        public void BuildAdvanceDirectiveObservationDocument_1stLevelOnly()
        {
            var sectionCount = 1;
            var phase        = new Phase();

            phase.ID = "error";
            var document = new SchematronDocument();

            document.Phases.Add(phase);


            var doc = new DocumentTemplate("cda");

            doc.AddElement(new DocumentTemplateElement("observation"));
            doc.ChildElements[0].AddAttribute(new DocumentTemplateElementAttribute("classCode", "OBS"));
            doc.ChildElements[0].AddAttribute(new DocumentTemplateElementAttribute("moodCode", "EVN"));
            doc.AddElement(new DocumentTemplateElement("templateId"));
            doc.ChildElements[1].AddAttribute(new DocumentTemplateElementAttribute("root", "2.16.840.1.113883.10.20.22.4.48"));
            doc.AddElement(new DocumentTemplateElement("id"));
            doc.AddElement(new DocumentTemplateElement("code"));
            doc.ChildElements[doc.ChildElements.Count - 1].AddAttribute(new DocumentTemplateElementAttribute("xsi-type", "CE", "2.16.840.1.113883.1.11.20.2"));
            doc.AddElement(new DocumentTemplateElement("statusCode"));
            doc.ChildElements[doc.ChildElements.Count - 1].AddAttribute(new DocumentTemplateElementAttribute("code", "completed", "2.16.840.1.113883.5.14"));
            var participantElement = new DocumentTemplateElement("participant");

            doc.ChildElements[0].AddElement(participantElement);
            participantElement.AddAttribute(new DocumentTemplateElementAttribute("typeCode", "VRF"));
            var templateIdElement = new DocumentTemplateElement("templateId");

            templateIdElement.AddAttribute(new DocumentTemplateElementAttribute("root", "2.16.840.1.113883.10.20.1.58"));
            participantElement.AddElement(templateIdElement);
            var timeElement = new DocumentTemplateElement("time");

            timeElement.AddAttribute(new DocumentTemplateElementAttribute("xsi:type", "TS"));
            participantElement.AddElement(timeElement);
            var participantRoleElement = new DocumentTemplateElement("participantRole");

            participantElement.AddElement(participantRoleElement);


            var contextBuilder = new ContextBuilder(doc.ChildElements[0], "cda");
            var rule           = new Rule();

            rule.Context = contextBuilder.GetFullyQualifiedContextString();

            var assertionBuilder = new AssertionLineBuilder(this.tdb, doc.ChildElements[0].Attributes[0], this.igType, this.igTypeSchema);  //"OBS"

            rule.Assertions.Add(new Assertion()
            {
                AssertionMessage = "SHALL contain 1..1 @classCode='OBS' Observation (CodeSystem: HL7ActClass 2.16.840.1.113883.5.6) (CONF:8648).",
                Test             = assertionBuilder.WithCardinality(CardinalityParser.Parse("1..1")).WithinContext(contextBuilder.GetRelativeContextString()).ConformsTo(Conformance.SHALL).ToString()
            });

            assertionBuilder = new AssertionLineBuilder(this.tdb, doc.ChildElements[0].Attributes[1], this.igType, this.igTypeSchema);  //"EVN"
            rule.Assertions.Add(new Assertion()
            {
                AssertionMessage = "SHALL contain 1..1 @moodCode='EVN' Event (CodeSystem: ActMood 2.16.840.1.113883.5.1001) (CONF:8649).",
                Test             = assertionBuilder.WithCardinality(CardinalityParser.Parse("1..1")).WithinContext(contextBuilder.GetRelativeContextString()).ConformsTo(Conformance.SHALL).ToString()
            });
            var pattern = new Pattern();

            pattern.ID   = sectionCount.ToString();
            pattern.Name = string.Format("pattern-{0}-errors", pattern.ID);
            pattern.Rules.Add(rule);
            phase.ActivePatterns.Add(pattern);

            rule             = new Rule();
            contextBuilder   = new ContextBuilder(doc.ChildElements[1], "cda");
            rule.Context     = contextBuilder.GetFullyQualifiedContextString();
            assertionBuilder = new AssertionLineBuilder(this.tdb, doc.ChildElements[1], this.igType, this.igTypeSchema);  //"templateId[@rootCode]"
            rule.Assertions.Add(new Assertion()
            {
                AssertionMessage = "SHALL contain 1..1 @root='2.16.840.1.113883.10.20.22.4.48' (CONF:10485).",
                Test             = assertionBuilder.WithCardinality(CardinalityParser.Parse("1..1")).WithinContext(contextBuilder.GetRelativeContextString()).ConformsTo(Conformance.SHALL).ToString()
            });

            sectionCount++;
            pattern      = new Pattern();
            pattern.ID   = sectionCount.ToString();
            pattern.Name = string.Format("pattern-{0}-errors", pattern.ID);
            pattern.Rules.Add(rule);
            phase.ActivePatterns.Add(pattern);

            rule             = new Rule();
            contextBuilder   = new ContextBuilder(doc.ChildElements[2], "cda");
            rule.Context     = contextBuilder.GetFullyQualifiedContextString();
            assertionBuilder = new AssertionLineBuilder(this.tdb, doc.ChildElements[2], this.igType, this.igTypeSchema);  //"1..* id"
            rule.Assertions.Add(new Assertion()
            {
                AssertionMessage = "SHALL contain 1..* id (CONF:8654)",
                Test             = assertionBuilder.WithCardinality(CardinalityParser.Parse("1..*")).WithinContext(contextBuilder.GetRelativeContextString()).ConformsTo(Conformance.SHALL).ToString()
            });

            sectionCount++;
            pattern      = new Pattern();
            pattern.ID   = sectionCount.ToString();
            pattern.Name = string.Format("pattern-{0}-errors", pattern.ID);
            pattern.Rules.Add(rule);
            phase.ActivePatterns.Add(pattern);

            rule             = new Rule();
            contextBuilder   = new ContextBuilder(doc.ChildElements[3], "cda");
            rule.Context     = contextBuilder.GetFullyQualifiedContextString();
            assertionBuilder = new AssertionLineBuilder(this.tdb, doc.ChildElements[3], this.igType, this.igTypeSchema);  //"1..1 code @xsi:type='CE' valueset = 2.16.840.1.113883.1.11.20.2"
            rule.Assertions.Add(new Assertion()
            {
                AssertionMessage = "SHALL contain 1..1 code with @xsi:type='CE', where the @code SHOULD be selected from ValueSet AdvanceDirectiveTypeCode 2.16.840.1.113883.1.11.20.2 STATIC 2006-10-17 (CONF:8651).",
                Test             = assertionBuilder.WithCardinality(CardinalityParser.Parse("1..1")).WithinContext(contextBuilder.GetRelativeContextString()).ConformsTo(Conformance.SHALL).ToString()
            });

            sectionCount++;
            pattern      = new Pattern();
            pattern.ID   = sectionCount.ToString();
            pattern.Name = string.Format("pattern-{0}-errors", pattern.ID);
            pattern.Rules.Add(rule);
            phase.ActivePatterns.Add(pattern);

            rule             = new Rule();
            contextBuilder   = new ContextBuilder(doc.ChildElements[3], "cda");
            rule.Context     = contextBuilder.GetFullyQualifiedContextString();
            assertionBuilder = new AssertionLineBuilder(this.tdb, doc.ChildElements[3], this.igType, this.igTypeSchema);  //"1..1 statusCode @code='completed' valueset = 2.16.840.1.113883.1.11.20.2"
            rule.Assertions.Add(new Assertion()
            {
                AssertionMessage = "SHALL contain 1..1 code with @xsi:type='CE', where the @code SHOULD be selected from ValueSet AdvanceDirectiveTypeCode 2.16.840.1.113883.1.11.20.2 STATIC 2006-10-17 (CONF:8651).",
                Test             = assertionBuilder.WithCardinality(CardinalityParser.Parse("1..1")).WithinContext(contextBuilder.GetRelativeContextString()).ConformsTo(Conformance.SHALL).ToString()
            });

            sectionCount++;
            pattern      = new Pattern();
            pattern.ID   = sectionCount.ToString();
            pattern.Name = string.Format("pattern-{0}-errors", pattern.ID);
            pattern.Rules.Add(rule);
            phase.ActivePatterns.Add(pattern);

            rule           = new Rule();
            contextBuilder = new ContextBuilder(doc.ChildElements[1].Attributes[0], "cda");
            rule.Context   = contextBuilder.GetFullyQualifiedContextString();
            var childtemplateIdElementAssertionBuilder = new AssertionLineBuilder(this.tdb, templateIdElement.Attributes[0], this.igType, this.igTypeSchema)  //templateId/@root
                                                         .WithCardinality(CardinalityParser.Parse("1..1"))
                                                         .ConformsTo(Conformance.SHALL)
                                                         .WithinContext("cda:");
            var childParticipantElementAssertionBuilder = new AssertionLineBuilder(this.tdb, participantRoleElement, this.igType, this.igTypeSchema)
                                                          .WithCardinality(CardinalityParser.Parse("1..*"))
                                                          .ConformsTo(Conformance.SHALL)
                                                          .WithinContext("cda:");
            var childTimeElementAssertionBuilder = new AssertionLineBuilder(this.tdb, timeElement, this.igType, this.igTypeSchema)
                                                   .WithCardinality(CardinalityParser.Parse("0..1"))
                                                   .ConformsTo(Conformance.SHOULD)
                                                   .WithinContext("cda:");

            assertionBuilder = new AssertionLineBuilder(this.tdb, participantElement, this.igType, this.igTypeSchema);  //participant
            rule.Assertions.Add(new Assertion()
            {
                AssertionMessage = "should contain 1..* participant (CONF:8662), participant should contain 0..1 time (CONF:8665), the data type of Observation/participant/time in a verification SHALL be TS (time stamp) (CONF:8666), participant shall contain 1..1 participantRole (CONF:8825), participant shall contain 1..1 @typeCode=VRF 'Verifier' (CodeSystem: 2.16.840.1.113883.5.90) (CONF:8663), participant shall contain 1..1 templateId (CONF:8664), templateId shall contain 1..1 @root=2.16.840.1.113883.10.20.1.58 (CONF:10486)",
                Test             = assertionBuilder
                                   .WithCardinality(CardinalityParser.Parse("1..*"))
                                   .WithinContext("cda:")
                                   .ConformsTo(Conformance.SHALL)
                                   .WithChildElementBuilder(childTimeElementAssertionBuilder)
                                   .WithChildElementBuilder(childParticipantElementAssertionBuilder)
                                   .WithChildElementBuilder(childtemplateIdElementAssertionBuilder)
                                   .ToString()
            });

            sectionCount++;
            pattern      = new Pattern();
            pattern.ID   = sectionCount.ToString();
            pattern.Name = string.Format("pattern-{0}-errors", pattern.ID);
            pattern.Rules.Add(rule);
            phase.ActivePatterns.Add(pattern);

            var    builder         = new SchematronDocumentSerializer();
            string serializedModel = builder.SerializeDocument(document);

            Assert.IsFalse(string.IsNullOrEmpty(serializedModel), "No string returned from serialize document");

            string[] lModelLines = serializedModel.Split('\n');
            Assert.IsNotNull(lModelLines, "The generated string was not split on lines");
            Assert.IsTrue(lModelLines.Length > 1, "The generated string was not split on lines");
        }
示例#8
0
        public void ExampleContextBuild()
        {
            //
            // Context
            //
            var contextBuilder = new ContextBuilder();

            contextBuilder
            .WithContentId(MimeUtils.GenerateMessageId())
            .WithDisposition("metadata.txt")
            .WithTransferEncoding(ContentEncoding.Base64)
            .WithVersion("1.0")
            .WithId(MimeUtils.GenerateMessageId())
            .WithPatientId(
                new PatientInstance
            {
                PidContext     = "2.16.840.1.113883.19.999999",
                LocalPatientId = "123456"
            }.ToList()
                )
            .WithType(ContextStandard.Type.CategoryRadiology, ContextStandard.Type.ActionReport)
            .WithPurpose(ContextStandard.Purpose.PurposeResearch)
            .WithPatient(
                new Patient
            {
                GivenName           = "John",
                SurName             = "Doe",
                MiddleName          = "Jacob",
                DateOfBirth         = "1961-12-31",
                Gender              = "M",
                PostalCode          = "12345",
                StateOrProvinceName = "New York",
                LocalityName        = "John County",
                Country             = "US",
                DirectAddress       = "*****@*****.**"
            }
                );

            var context = contextBuilder.Build();

            //
            // Mime message and simple body
            //
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress("HoboJoe", "*****@*****.**"));
            message.To.Add(new MailboxAddress("Toby", "*****@*****.**"));
            message.Subject = "Sample message with pdf and context attached";
            message.Headers.Add(MailStandard.Headers.DirectContext, context.Headers[ContextStandard.ContentIdHeader]);
            Assert.StartsWith("<", context.Headers[HeaderId.ContentId]);
            Assert.EndsWith(">", context.Headers[HeaderId.ContentId]);

            var body = new TextPart("plain")
            {
                Text = @"Simple Body"
            };

            //
            // Mime message and simple body
            //
            var pdf = new MimePart("application/pdf")
            {
                ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                FileName                = "report.pdf",
                ContentTransferEncoding = ContentEncoding.Base64
            };

            var byteArray = Encoding.UTF8.GetBytes("Fake PDF (invalid)");
            var stream    = new MemoryStream(byteArray);

            pdf.Content = new MimeContent(stream);

            //
            // Multi part construction
            //
            var multiPart = new Multipart("mixed")
            {
                body,
                contextBuilder.BuildMimePart(),
                pdf
            };

            message.Body = multiPart;


            //
            // Assert context can be serialized and parsed.
            //
            var messageParsed = MimeMessage.Load(message.ToString().ToStream());

            Assert.True(messageParsed.ContainsDirectContext());
            Assert.Equal(context.ContentId, messageParsed.DirectContextId());
            Assert.StartsWith("<", messageParsed.Headers[MailStandard.Headers.DirectContext]);
            Assert.EndsWith(">", messageParsed.Headers[MailStandard.Headers.DirectContext]);

            var contextParsed = message.DirectContext();

            Assert.NotNull(contextParsed);

            //
            // Headers
            //
            Assert.Equal("text", contextParsed.ContentType.MediaType);
            Assert.Equal("plain", contextParsed.ContentType.MediaSubtype);
            Assert.Equal("attachment", contextParsed.ContentDisposition.Disposition);
            Assert.Equal("metadata.txt", contextParsed.ContentDisposition.FileName);
            Assert.Equal(context.ContentId, contextParsed.ContentId);

            //
            // Metadata
            //
            Assert.Equal("1.0", contextParsed.Metadata.Version);
            Assert.Equal(context.Metadata.Id, contextParsed.Metadata.Id);

            //
            // Metatdata PatientId
            //
            Assert.Equal("2.16.840.1.113883.19.999999:123456", contextParsed.Metadata.PatientId);
            Assert.Single(contextParsed.Metadata.PatientIdentifier);
            var patientIdentifiers = Enumerable.ToList(contextParsed.Metadata.PatientIdentifier);

            Assert.Equal("2.16.840.1.113883.19.999999", patientIdentifiers[0].PidContext);
            Assert.Equal("123456", patientIdentifiers[0].LocalPatientId);

            //
            // Metatdata Type
            //
            Assert.Equal("radiology/report", contextParsed.Metadata.Type.ToString());
            Assert.Equal("radiology", contextParsed.Metadata.Type.Category);
            Assert.Equal("report", contextParsed.Metadata.Type.Action);

            //
            // Metatdata Purpose
            //
            Assert.Equal("research", contextParsed.Metadata.Purpose);

            //
            // Metadata Patient
            //
            Assert.Equal("givenName=John; surname=Doe; middleName=Jacob; dateOfBirth=1961-12-31; gender=M; localityName=John County; stateOrProvinceName=New York; postalCode=12345; country=US; [email protected]",
                         contextParsed.Metadata.Patient.ToString());

            Assert.Equal("John", contextParsed.Metadata.Patient.GivenName);
            Assert.Equal("Doe", contextParsed.Metadata.Patient.SurName);
            Assert.Equal("1961-12-31", contextParsed.Metadata.Patient.DateOfBirth);
            Assert.Equal("*****@*****.**", context.Metadata.Patient.DirectAddress);
            Assert.Equal("John County", context.Metadata.Patient.LocalityName);
            Assert.Equal("US", context.Metadata.Patient.Country);
            Assert.Equal("New York", context.Metadata.Patient.StateOrProvinceName);
        }
示例#9
0
 /// <summary>
 ///     Registers extension modules.
 /// </summary>
 /// <param name="builder">The builder.</param>
 /// <returns>ContextBuilder.</returns>
 public static ContextBuilder RegisterExtensions(this ContextBuilder builder)
 {
     ExtensionContexts.Add(builder.Context, new ExtensionContext(builder.Context));
     return(builder);
 }
示例#10
0
 /// <summary>Get the ASP.NET Core <c>TestServer</c> created in <c>Initialize()</c>.</summary>
 public static TestServer GetTestServer(this ContextBuilder _) => _testServer;
 /// <summary>Registers an intent to use the <c>TestTag</c> attribute on test methods.</summary>
 /// <remarks>This causes LeanTest tags to be written to the test log (.trx-file).</remarks>
 public static ContextBuilder RegisterTags(this ContextBuilder theContextBuilder, TestContext testContext, Assembly assembly = null) =>
 theContextBuilder.RegisterTags(testContext.TestName, assembly ?? Assembly.GetCallingAssembly(), typeof(TestTagAttribute));
示例#12
0
 public static IClientContext AsClientApplication(
     this ContextBuilder source,
     Func <CodingStyleBuilder, ICodingStyle> codingStyle
     ) => source.AsClientApplication(
     codingStyle(BuildRoutine.CodingStyle())
     );
示例#13
0
 /// <summary>Get the ASP.NET Core <c>TestServer</c> created in <c>Initialize()</c>.</summary>
 public static TestServer GetTestServer(this ContextBuilder contextBuilder) => (contextBuilder as IFactoryAccess)?.Server ?? _wrapped?.GetTestServer();
示例#14
0
        public void Parse_Complicated_Hierarchies()
        {
            // arrange
            var args    = "firewall block -p 8080 -m io firefox.exe".Split(' ');
            var builder = new ContextBuilder()
                          .AddParser <UtilOptions>("base")
                          .WithBooleanSwitch('h', "help", o => o.IsHelpRequested        = true)
                          .WithBooleanSwitch(null, "version", o => o.IsVersionRequested = true)
                          .Finish
                          .AddParser <ClipboardOptions>("clipboard")
                          .WithBooleanSwitch('o', "overwrite", o => o.IsOverwriteClipboard = true)
                          .Finish
                          .AddParser <SortOptions>("sort")
                          .WithFactoryFunction(() => new SortOptions())
                          .WithBooleanSwitch('r', "reverse", o => o.IsReversed = true)
                          .Finish
                          .AddParser <ZipOptions>("zip")
                          .WithFactoryFunction(() => new ZipOptions())
                          .WithPositional((o, s) => o.ZipFile = s)
                          .WithPositionals((o, s) => o.Globs  = s)
                          .Finish
                          .AddParser <FireWallOptions>("firewall")
                          .WithSingleValueSwitch('p', "port", (o, s) => o.Port = Convert.ToInt32(s))
                          .WithSingleValueSwitch('m', "mode", (o, s) =>
            {
                o.IsInbound  = s.Contains("i");
                o.IsOutbound = s.Contains("o");
            })
                          .WithPositional((o, s) => o.Program = s)
                          .Finish
                          .AddParser <BlockProgramOptions>("block")
                          .WithFactoryFunction(() => new BlockProgramOptions())
                          .Finish
                          .AddParser <UnblockProgramOptions>("unblock")
                          .WithFactoryFunction(() => new UnblockProgramOptions())
                          .Finish
                          .AddParser <ConvertOptions>("convert")
                          .WithFactoryFunction(() => new ConvertOptions())
                          .WithSingleValueSwitch('f', "format", (o, s) => o.Format = s)
                          .WithPositionals((o, s) => o.InputFiles = s)
                          .Finish
                          .CreateParentChildRelationship("base", "clipboard")
                          .CreateParentChildRelationship("base", "firewall")
                          .CreateParentChildRelationship("base", "convert")
                          .CreateParentChildRelationship("clipboard", "sort")
                          .CreateParentChildRelationship("clipboard", "zip")
                          .CreateParentChildRelationship("firewall", "block")
                          .CreateParentChildRelationship("firewall", "unblock");

            // act
            var result = builder.Parse(args);

            // assert
            var isParsed = false;

            result.When <BlockProgramOptions>((options, parser) =>
            {
                isParsed = true;
                options.IsInbound.Should().BeTrue();
                options.IsOutbound.Should().BeTrue();
                options.Port.Should().Be(8080);
                options.Program.Should().Be("firefox.exe");
            });
            isParsed.Should().BeTrue();
        }
示例#15
0
        public void TestLeadingPrepositionRule_OnGetAccObject()
        {
            var xml  = @"<function><type><name>LRESULT</name></type> <name><name>CMenuContainer</name><op:operator>::</op:operator><name>OnGetAccObject</name></name><parameter_list>( <param><decl><type><name>UINT</name></type> <name>uMsg</name></decl></param>, <param><decl><type><name>WPARAM</name></type> <name>wParam</name></decl></param>, <param><decl><type><name>LPARAM</name></type> <name>lParam</name></decl></param>, <param><decl><type><name>BOOL</name><type:modifier>&amp;</type:modifier></type> <name>bHandled</name></decl></param> )</parameter_list> <block>{
    <if>if <condition>(<expr><op:operator>(</op:operator><name>DWORD</name><op:operator>)</op:operator><name>lParam</name><op:operator>==</op:operator><op:operator>(</op:operator><name>DWORD</name><op:operator>)</op:operator><name>OBJID_CLIENT</name> <op:operator>&amp;&amp;</op:operator> <name>m_pAccessible</name></expr>)</condition><then> <block>{
        <return>return <expr><call><name>LresultFromObject</name><argument_list>(<argument><expr><name>IID_IAccessible</name></expr></argument>,<argument><expr><name>wParam</name></expr></argument>,<argument><expr><name>m_pAccessible</name></expr></argument>)</argument_list></call></expr>;</return>
    }</block></then> <else>else <block>{
        <expr_stmt><expr><name>bHandled</name><op:operator>=</op:operator><name>FALSE</name></expr>;</expr_stmt>
        <return>return <expr><lit:literal type=""number"">0</lit:literal></expr>;</return>
    }</block></else></if>
}</block></function>";
            var unit = fileUnitSetup.GetFileUnitForXmlSnippet(xml, "test.cpp");

            var func = unit.Descendants(SRC.Function).First();
            var mdn  = new MethodDeclarationNode(SrcMLElement.GetNameForMethod(func).Value, ContextBuilder.BuildMethodContext(func));

            builder.ApplyRules(mdn);

            Assert.AreEqual(typeof(LeadingPrepositionRule), mdn.SwumRuleUsed.GetType());
            var expected = @"handle(Verb) | On(NounModifier) Get(NounModifier) Acc(NounModifier) Object(NounIgnorable)
	 ++ [UINT(Noun) - u(Unknown) Msg(Unknown)] ++ [WPARAM(Noun) - w(Unknown) Param(Unknown)] ++ [LPARAM(Noun) - l(Unknown) Param(Unknown)] ++ [BOOL(Noun) - b(Unknown) Handled(Unknown)] ++ C(NounModifier) Menu(NounModifier) Container(NounIgnorable) ++ LRESULT(Noun)"    ;

            Assert.AreEqual(expected, mdn.ToString());
        }
 public CoursesContextBuilder(string defaultConnectionString)
 {
     this._defaultConnectionString = defaultConnectionString;
     this._builder = new ContextBuilder<ObjectContext>();
     ConfigureMappings();
 }
示例#17
0
        public void TestModalVerb()
        {
            var xml  = @"<function><type><name>int</name></type> <name><name>ToolBarXmlHandlerEx</name><op:operator>::</op:operator><name>CanHandle</name></name><parameter_list>(<param><decl><type><name>wxXmlNode</name> <type:modifier>*</type:modifier></type><name>node</name></decl></param>)</parameter_list> <block>{
	<return>return <expr><lit:literal type=""number"">0</lit:literal></expr>;</return>
}</block></function>";
            var unit = fileUnitSetup.GetFileUnitForXmlSnippet(xml, "test.cpp");

            var func = unit.Descendants(SRC.Function).First();
            var mdn  = new MethodDeclarationNode(SrcMLElement.GetNameForMethod(func).Value, ContextBuilder.BuildMethodContext(func));

            builder.ApplyRules(mdn);

            Assert.AreEqual(typeof(CheckerRule), mdn.SwumRuleUsed.GetType());
            var expected = @"Can(VerbIgnorable) Handle(VerbIgnorable) | [wx(NounModifier) Xml(NounModifier) Node(NounIgnorable) - node(Unknown)]
	 ++ Tool(NounModifier) Bar(NounModifier) Xml(NounModifier) Handler(NounModifier) Ex(Noun) ++ int(Noun)"    ;

            Assert.AreEqual(expected, mdn.ToString());
        }
示例#18
0
        public void TestNounPhraseRule_KeyFileExists()
        {
            var xml  = @"<function><type><name>bool</name></type> <name><name>COptionsPageConnectionSFTP</name><op:operator>::</op:operator><name>KeyFileExists</name></name><parameter_list>(<param><decl><type><name>const</name> <name>wxString</name><type:modifier>&amp;</type:modifier></type> <name>keyFile</name></decl></param>)</parameter_list> <block>{
	<return>return <expr><lit:literal type=""boolean"">true</lit:literal></expr>;</return>
}</block></function>";
            var unit = fileUnitSetup.GetFileUnitForXmlSnippet(xml, "test.cpp");

            var func = unit.Descendants(SRC.Function).First();
            var mdn  = new MethodDeclarationNode(SrcMLElement.GetNameForMethod(func).Value, ContextBuilder.BuildMethodContext(func));

            builder.ApplyRules(mdn);

            Assert.AreEqual(typeof(NounPhraseRule), mdn.SwumRuleUsed.GetType());
            var expected = @"get(Verb) | Key(NounModifier) File(NounModifier) Exists(Noun)
	 ++ [wx(NounModifier) String(NounIgnorable) - key(Unknown) File(Unknown)] ++ C(NounModifier) Options(NounModifier) Page(NounModifier) Connection(NounModifier) SFTP(Noun)"    ;

            Assert.AreEqual(expected, mdn.ToString());
        }
示例#19
0
 /// <summary>Get the ASP.NET Core client from the factory created in <c>Initialize()</c>.</summary>
 /// <remarks>Returns null if a Func&lt;WebApplicationFactory&lt;T&gt;&gt; was not passed in <c>Initialize()</c></remarks>
 public static WebApplicationFactory <T> GetFactory <T>(this ContextBuilder contextBuilder) where T : class =>
 WebApplicationFactoryFromContextBuilder <T>(contextBuilder) ?? (_wrapped as FactoryWrapper <T>)?.GetFactory();
示例#20
0
 public static IClientContext AsServiceClient(
     this ContextBuilder source,
     Func <ServiceClientConfigurationBuilder, IServiceClientConfiguration> serviceClientConfiguration
     ) => source.AsServiceClient(
     serviceClientConfiguration(BuildRoutine.ServiceClientConfig())
     );
示例#21
0
 private static WebApplicationFactory <T> WebApplicationFactoryFromContextBuilder <T>(ContextBuilder contextBuilder) where T : class =>
 (contextBuilder as WebApplicationFactoryContextBuilder <T>)?.GetFactory();
示例#22
0
        /// <summary>
        /// Update races and announcements
        /// </summary>
        private static async void OnSrlUpdate(object?sender, IReadOnlyCollection <SRLApiClient.Endpoints.Races.Race> e)
        {
            _srlService.IsUpdateTriggerEnabled = false;

            Logger.Info("Waiting for lock..");
            await _contextSemaphore.WaitAsync().ConfigureAwait(false);

            DateTime startTime        = DateTime.UtcNow;
            bool     updateSuccessful = false;

            try
            {
                using DatabaseContext context = new ContextBuilder().CreateDbContext();

                Logger.Info("Reloading context");
                await context.LoadRemoteAsync().ConfigureAwait(false);

                context.ChangeTracker.DetectChanges();

                Logger.Info("Processing channel mutations");
                ProcessChannelMutations(context);

                Logger.Info("Updating races");
                await RaceAdapter
                .SyncRaces(context, _srlService, e.ToList())
                .ConfigureAwait(false);

                Logger.Info("Updating announcements");
                await AnnouncementAdapter
                .UpdateAnnouncementsAsync(context, _discordService, DatabaseAdapter.GetUpdatedRaces(context).ToList())
                .ConfigureAwait(false);

                Logger.Info("Saving changes");
                await context.SaveChangesAsync().ConfigureAwait(false);

                Logger.Info("Update completed");
                updateSuccessful = true;
            }
            catch (Exception ex)
            {
                Logger.Error("Exception thrown", ex);
            }
            finally
            {
                try
                {
                    Logger.Info("Creating update-table entry.");
                    using DatabaseContext context = new ContextBuilder().CreateDbContext();
                    context.Updates.Add(new Update(startTime, DateTime.UtcNow, updateSuccessful));
                    context.SaveChanges();
                    Logger.Info("Entry saved");
                }
                catch (Exception ex)
                {
                    Logger.Error("Exception thrown", ex);
                    throw;
                }
                finally
                {
                    _contextSemaphore.Release();
                    _srlService.IsUpdateTriggerEnabled = true;
                    Logger.Info("Released triggers");
                }
            }
        }
示例#23
0
 /// <summary>Get the ASP.NET Core client from the <c>TestServer</c> created in <c>Initialize()</c>.</summary>
 public static HttpClient GetHttpClient(this ContextBuilder contextBuilder) => (contextBuilder as IFactoryAccess)?.CreateClient() ?? _wrapped?.GetHttpClient();
        /// <summary>
        /// Creates and updates announcements for the specified <paramref name="races"/>
        /// if an active tracker is found
        /// </summary>
        /// <param name="context">The database context</param>
        /// <param name="discordService">The discord service</param>
        /// <param name="races">The races</param>
        public static async Task UpdateAnnouncementsAsync(
            DatabaseContext context
            , DiscordService discordService
            , List <Race> races)
        {
            foreach (Race race in races)
            {
                foreach (Tracker tracker in context.GetActiveTrackers(race.Game))
                {
                    Logger.Info($"({race.SrlId}) Updating tracker {tracker.Id}");

                    Announcement?announcement = context.GetAnnouncement(race, tracker);

                    try
                    {
                        if (discordService.HasRequiredPermissions(tracker.Channel.Guild.Snowflake, announcement?.Channel?.Snowflake ?? tracker.Channel.Snowflake) != true)
                        {
                            Logger.Error($"Missing permissions in channel {tracker.ChannelId}: {tracker.Channel.Guild.DisplayName}/{tracker.Channel.DisplayName}");
                            continue;
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Error($"({announcement?.Race?.SrlId}) Exception thrown:", ex);
                        continue;
                    }

                    List <Entrant> entrants = new List <Entrant>();

                    foreach (Entrant e in context.GetEntrants(race))
                    {
                        if (context.Entry(e).State != EntityState.Deleted)
                        {
                            entrants.Add(e);
                        }
                    }

                    if (
                        announcement == null &&
                        race.State < SRLApiClient.Endpoints.RaceState.Finished &&
                        race.State != SRLApiClient.Endpoints.RaceState.Unknown
                        )
                    {
                        DateTime controlRange = DateTime.UtcNow.Subtract(TimeSpan.FromDays(7));

                        using DatabaseContext altContext = new ContextBuilder().CreateDbContext();
                        Race?persistedRace = await altContext
                                             .Races
                                             .AsQueryable()
                                             .FirstOrDefaultAsync(r => r
                                                                  .SrlId.Equals(race.SrlId, StringComparison.CurrentCultureIgnoreCase) &&
                                                                  r.CreatedAt > controlRange)
                                             .ConfigureAwait(false);

                        if (persistedRace != null)
                        {
                            // If a race with the same id was registered within the last week, skip announcement
                            Logger.Info($"({race.SrlId}) Persisted race found: {persistedRace.Id}/{persistedRace.SrlId}. Skipping announcement!");
                        }
                        else
                        {
                            announcement = await PostAnnouncementAsync(discordService, tracker, race, entrants).ConfigureAwait(false);

                            if (announcement != null)
                            {
                                context.AddOrUpdate(announcement);
                            }
                        }
                    }
                    else if (announcement != null)
                    {
                        await UpdateAnnouncementAsync(discordService, announcement, entrants).ConfigureAwait(false);
                    }
                }
            }
        }
示例#25
0
 /// <summary>Get the ASP.NET Core client from the <c>TestServer</c> created in <c>Initialize()</c>.</summary>
 public static HttpClient GetClient(this ContextBuilder _) => _client;
 /// <summary>Registers an intent to use the <c>Description</c> attribute on test methods.</summary>
 /// <remarks>This causes MsTest descriptions to be written to the test log (.trx-file).</remarks>
 public static ContextBuilder RegisterDescription(this ContextBuilder theContextBuilder, TestContext testContext, Assembly assembly = null, IStdOut stdOut = null) =>
 theContextBuilder.RegisterDescription(testContext.MethodName, assembly ?? Assembly.GetCallingAssembly(), typeof(TestDescriptionAttribute), stdOut ?? new StdOutTestOutputHelper(testContext));
 /// <summary>Registers an intent to use the <c>Description</c> attribute on test methods.</summary>
 /// <remarks>This causes MsTest descriptions to be written to the test log (.trx-file).</remarks>
 public static ContextBuilder RegisterDescription(this ContextBuilder theContextBuilder, TestContext testContext, Assembly assembly = null) =>
 theContextBuilder.RegisterDescription(testContext.TestName, assembly ?? Assembly.GetCallingAssembly());
示例#28
0
        public async Task ExecuteShouldEditAddNewDayOfWeekWithNewUser()
        {
            //Arrange
            SchoolManagementContext context = new ContextBuilder().BuildClean();
            GroupLevel groupLevel           = new GroupLevelBuilder(context).With(x => x.Level = 1).With(x => x.Name = "Początkujący").BuildAndSave();

            new RoleBuilder(context).WithName(Roles.Anchor).BuildAndSave();
            List <User> participants           = new List <User>();
            var         participantRoleBuilder = new RoleBuilder(context).WithName(Roles.Participant);

            User user = new UserBuilder(context).WithEmail($"email{5}@gmail.com").BuildAndSave();

            participants.Add(user);
            participantRoleBuilder.AddUserToRole(user).BuildAndSave();

            var groupClass = new GroupClassBuilder(context)
                             .WithName("Stara grupa")
                             .WithRoom(builder => builder.WithName("Old room"))
                             .WithGroupLevel(x => x.With(z => z.Name = "Beginner"))
                             .AddAnchor(anchor => anchor.WithEmail("*****@*****.**").WithName("Jan", "Kowalski"))
                             .AddParticipant(aprticipant => aprticipant.WithEmail("*****@*****.**").WithName("Jan", "Kowalski"), ParticipantRole.Follower)
                             .AddClassDayOfWeek(x => x.WithDate(DayOfWeek.Monday, new TimeSpan(18, 0, 0)))
                             .WithStartClasses(new DateTime(2019, 09, 02, 0, 0, 0))
                             .WithTimeDurationInMinutes(90)
                             .WithNumberOfClasses(10)
                             .CreateSchedule().BuildAndSave();

            participants.Add(groupClass.Participants.First().User);

            Command cmd = new Command
            {
                GroupClassId = groupClass.Id,
                Name         = "Groupa zajęciowa",
                Anchors      = new List <string> {
                    groupClass.Anchors.First().UserId
                },
                IsSolo           = true,
                ParticipantLimit = 20,
                Start            = groupClass.StartClasses,
                GroupLevelId     = groupLevel.Id,
                Participants     = participants.Select(x => new ParticipantDto
                {
                    Id   = x.Id,
                    Role = ParticipantRole.Leader
                }).ToList(),
                DayOfWeeks = new List <ClassDayOfWeekDto>
                {
                    new ClassDayOfWeekDto()
                    {
                        BeginTime = new TimeSpan(18, 0, 0),
                        DayOfWeek = DayOfWeek.Monday
                    },
                    new ClassDayOfWeekDto()
                    {
                        BeginTime = new TimeSpan(20, 0, 0),
                        DayOfWeek = DayOfWeek.Wednesday
                    }
                },
                DurationTimeInMinutes = 90,
                UtcOffsetInMinutes    = 0,
                NumberOfClasses       = 10,
                RoomId = groupClass.Room.Id
            };


            //Act
            DataResult result = await new Handler(context).Handle(cmd, CancellationToken.None);

            //Assert
            result
            .Should().NotBeNull();
            result.Status.Should().Be(DataResult.ResultStatus.Success, "all parameters are corrected");


            context.ClassTimes.Should().HaveCount(cmd.NumberOfClasses);
            context.ParticipantPresences.Should().HaveCount(cmd.NumberOfClasses * cmd.Participants.Count);
            foreach (var contextClassTime in context.ClassTimes)
            {
                contextClassTime.PresenceParticipants.Should().HaveCount(2);
            }
        }
示例#29
0
 public ContextBuilderFixture()
 {
     builder = new ContextBuilder("http://localhost", HttpMethod.Get);
 }
示例#30
0
 public API(LoggerDelegate logger)
 {
     Context = new ContextBuilder<Timer>(() => new Timer(), timer => timer.Stop());
     _logger = logger;
 }
示例#31
0
 public void Init()
 {
     contextBuilder = new ContextBuilder();
 }
示例#32
0
        public void TestBooleanArgument()
        {
            var xml  = @"<function><type><name>boolean</name></type> <name><name>Automobile</name><op:operator>::</op:operator><name>HasEmptyGasTank</name></name><parameter_list>(<param><decl><type><name>boolean</name></type> <name>gasTank</name></decl></param>)</parameter_list> <block>{
	<return>return <expr><lit:literal type=""boolean"">false</lit:literal></expr>;</return>
}</block></function>";
            var unit = fileUnitSetup.GetFileUnitForXmlSnippet(xml, "test.cpp");

            var func = unit.Descendants(SRC.Function).First();
            var mdn  = new MethodDeclarationNode(SrcMLElement.GetNameForMethod(func).Value, ContextBuilder.BuildMethodContext(func));

            builder.ApplyRules(mdn);
        }
示例#33
0
 public MapBinderBuilder(ContextBuilder parent, List <Action <ICrossContextCapable> > preBindings)
 {
     _preBindings = preBindings;
     _parent      = parent;
 }
示例#34
0
        static void Main(string[] args)
        {
            ConsoleColor forecolor       = Console.ForegroundColor;
            ConsoleColor backgroundColor = Console.BackgroundColor;

            try
            {
                if (!File.Exists("dataflip.json"))
                {
                    HelpWithDataflipJsonFile();
                    return;
                }
                Console.Title           = "Dataflip is working on some awesome stuff right now...";
                Console.BackgroundColor = ConsoleColor.Black;
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("Working on it!");
                Console.WriteLine();
                GlobalProgress.Notify += GlobalProgress_Notify;

                string json = null;

                Console.WriteLine("Getting data from 'dataflip.json'.");
                using (var stream = File.Open("dataflip.json", FileMode.Open))
                    using (StreamReader reader = new StreamReader(stream))
                        json = reader.ReadToEnd();

                Console.WriteLine("File found, parsing configuration...");
                var config = GlobalConfiguration.FromJson(json);

                Console.WriteLine("Configuration looks OK. Resolving contexts...");
                foreach (var contextConfig in config.Contexts)
                {
                    Console.WriteLine();
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine($"Working on {contextConfig.Name}, {contextConfig.Sprocs.Count} sproc(s)...");
                    Console.ForegroundColor = ConsoleColor.White;
                    ContextBuilder resolver = new ContextBuilder(contextConfig);
                    var            context  = resolver.BuildContext();
                    Console.WriteLine();
                    Console.WriteLine("Generating code...");
                    CSharpContextGenerator generator = new CSharpContextGenerator(context);
                    string code = generator.GenerateCode();

                    TypeScriptTypingsGenerator typeScript = new TypeScriptTypingsGenerator(context);
                    string typeScriptCode = typeScript.GenerateCode();

                    HtmlBindingsGenerator htmlBindings = new HtmlBindingsGenerator(context);
                    string htmlBindingsCode            = htmlBindings.GenerateCode();

                    Console.WriteLine($"Writing code to {contextConfig.Output}...");
                    using (FileStream stream = File.Create(contextConfig.Output))
                        using (StreamWriter writer = new StreamWriter(stream))
                        {
                            writer.Write(code);
                            Console.WriteLine();
                            Console.WriteLine("Awesome! C# Context class written successfully.");
                        }

                    if (contextConfig.TypeScriptTypings != null)
                    {
                        Console.WriteLine($"Working on typescript typings! Creating file {contextConfig.TypeScriptTypings}...");
                        using (FileStream stream = File.Create(contextConfig.TypeScriptTypings))
                            using (StreamWriter writer = new StreamWriter(stream))
                            {
                                writer.Write(typeScriptCode);
                                Console.WriteLine();
                                Console.WriteLine("Great! TypeScript typings file written successfully.");
                            }
                    }

                    if (contextConfig.AngularHtmlBindings != null)
                    {
                        Console.WriteLine($"Working on angular html bindings! Creating file {contextConfig.AngularHtmlBindings}...");
                        using (FileStream stream = File.Create(contextConfig.AngularHtmlBindings))
                            using (StreamWriter writer = new StreamWriter(stream))
                            {
                                writer.Write(htmlBindingsCode);
                                Console.WriteLine();
                                Console.WriteLine("Excellent! TypeScript typings file written successfully.");
                            }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Title           = "Darn... I guess not.";
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("Ouch!");
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
                Console.WriteLine();
                Console.WriteLine("Write any line to continue...");
                Console.Read();
            }

            Console.BackgroundColor = backgroundColor;
            Console.ForegroundColor = forecolor;
        }
示例#35
0
        public async Task ExecuteShouldEditScheduleGroupClass()
        {
            //Arrange
            SchoolManagementContext context = new ContextBuilder().BuildClean();
            GroupLevel groupLevel           = new GroupLevelBuilder(context).With(x => x.Level = 1).With(x => x.Name = "Początkujący").BuildAndSave();
            Room       room   = new RoomBuilder(context).WithName("Sala biała").BuildAndSave();
            User       anchor = new UserBuilder(context).WithEmail("*****@*****.**").BuildAndSave();

            new RoleBuilder(context).WithName(Roles.Anchor).AddUserToRole(anchor).BuildAndSave();
            List <User> participants           = new List <User>();
            var         participantRoleBuilder = new RoleBuilder(context).WithName(Roles.Participant);

            for (var i = 0; i < 10; i++)
            {
                User user = new UserBuilder(context).WithEmail($"email{i}@gmail.com").BuildAndSave();
                participants.Add(user);
                participantRoleBuilder.AddUserToRole(user);
            }

            participantRoleBuilder.BuildAndSave();

            string expectedAnchorEmail = "*****@*****.**";
            var    groupClass          = CreateGroupClass(context, expectedAnchorEmail);
            string expectedAnchorId    = groupClass.Anchors.Where(x => x.User.Email == expectedAnchorEmail).Select(x => x.UserId).First();

            Command cmd = new Command
            {
                GroupClassId = groupClass.Id,
                Name         = "Groupa zajęciowa",
                Anchors      = new List <string> {
                    anchor.Id, expectedAnchorId
                },
                IsSolo             = true,
                ParticipantLimit   = 20,
                UtcOffsetInMinutes = 0,
                GroupLevelId       = groupLevel.Id,
                Participants       = participants.Select(x => new ParticipantDto
                {
                    Id   = x.Id,
                    Role = ParticipantRole.Leader
                }).ToList(),
                DayOfWeeks = new List <ClassDayOfWeekDto>
                {
                    new ClassDayOfWeekDto()
                    {
                        BeginTime = new TimeSpan(19, 0, 0),
                        DayOfWeek = DayOfWeek.Tuesday
                    },
                    new ClassDayOfWeekDto()
                    {
                        BeginTime = new TimeSpan(18, 0, 0),
                        DayOfWeek = DayOfWeek.Wednesday
                    },
                    new ClassDayOfWeekDto()
                    {
                        BeginTime = new TimeSpan(19, 0, 0),
                        DayOfWeek = DayOfWeek.Friday
                    },
                },
                DurationTimeInMinutes = 90,
                NumberOfClasses       = 24,
                RoomId = room.Id
            };

            var            expectedParticipant = groupClass.Participants.Select(x => x.User).First();
            ParticipantDto expectedRole        = new ParticipantDto()
            {
                Id   = expectedParticipant.Id,
                Role = ParticipantRole.Leader
            };

            cmd.Participants.Add(expectedRole);
            //Act
            DataResult result = await new Handler(context).Handle(cmd, CancellationToken.None);

            //Assert
            result
            .Should().NotBeNull();
            result.Status.Should().Be(DataResult.ResultStatus.Success, "all parameters are corrected");
            context.GroupClass.Should().NotBeEmpty("we add new group");
            groupClass.Anchors.Should().NotBeEmpty().And.HaveCount(cmd.Anchors.Count);
            groupClass.Room.Should().Be(room);
            groupClass.IsSolo.Should().BeTrue();
            groupClass.Name.Should().Be(cmd.Name);
            groupClass.GroupLevel.Should().Be(groupLevel);
            groupClass.Participants.Should().NotBeEmpty().And.HaveCount(cmd.Participants.Count).And
            .Contain(x => participants.Contains(x.User));
            groupClass.Participants.Where(x => x.User.Email == expectedParticipant.Email).Select(x => x.Role).First()
            .Should().Be(expectedRole.Role, "we changed role");

            ValidateClassDayOfWeek(groupClass);

            groupClass.Schedule.Should().NotBeNullOrEmpty().And.HaveCount(24).And.OnlyContain(x =>
                                                                                              x.StartDate.DayOfWeek == DayOfWeek.Tuesday || x.StartDate.DayOfWeek == DayOfWeek.Friday ||
                                                                                              x.StartDate.DayOfWeek == DayOfWeek.Wednesday);
        }
示例#36
0
        public async Task RequestProcessing()
        {
            //Listener.AcceptSocketAsync
            using (TcpClient client = await TcpListener.AcceptTcpClientAsync().ConfigureAwait(false))
            {
                Logger.LogInformation($"New connection from: {client.Client.RemoteEndPoint}");
                // Get a stream object for reading and writing
                using (NetworkStream netStream = client.GetStream())
                {
                    // Stream Checks =================================================================
                    if (!netStream.CanRead)
                    {
                        Logger.LogCritical("Can Not Read Stream".ToErrorString(this));
                        netStream.Close();
                        client.Close();
                        return;
                    }

                    if (!netStream.CanWrite)
                    {
                        Logger.LogCritical("Can Not Write To The Stream".ToErrorString(this));
                        netStream.Close();
                        client.Close();
                        return;
                    }

                    // Stream Checks =================================================================

                    ExecutedCommand executedCommand = null;
                    Request         request         = null;
                    Exception       exception       = null;



                    try
                    {
#if DEBUG
                        request = await Request.BuildRequest(netStream, Settings.RequestSettings, ServiceProvider.GetRequiredService <ILogger <Request> >()).ConfigureAwait(false);

                        //request.LogPacket();
#else
                        request = await Request.BuildRequest(netStream, Settings.RequestSettings).ConfigureAwait(false);
#endif
                    }
                    catch (MalformedRequestException MalformedRequestException)
                    {
                        exception = MalformedRequestException;
                    }

                    if (request is not null && RequestedEndpoint(request) is ExecutedCommand executedCommand1)
                    {
                        executedCommand = executedCommand1;
                    }

                    var response = new Response(Settings.ResponseSettings);

                    var middleware = ContextBuilder.CreateContext(executedCommand?.ClassExecuted, Middleware, netStream, request, response, ServiceProvider);

                    object bodyContent;
                    bool   isReturnTypeVoid = false;

                    if (exception is not null)
                    {
                        bodyContent = await middleware.BadRequest(exception).ConfigureAwait(false);
                    }
                    else if (executedCommand is null)
                    {
                        bodyContent = await middleware.NotFound(request).ConfigureAwait(false);
                    }
                    else
                    {
                        try
                        {
                            var temp = await middleware.ActionExecuting(executedCommand).ConfigureAwait(false);

                            isReturnTypeVoid = temp.IsReturnTypeVoid;
                            bodyContent      = temp.ReturnValue;
                        }

                        catch (IOException)
                        {
                            throw;
                        }
                        catch (Exception ex)
                        {
                            bodyContent = await middleware.InternalServerError(ex).ConfigureAwait(false);
                        }
                    }

                    await middleware.Context.WriteBodyAsync(isReturnTypeVoid, bodyContent).ConfigureAwait(false);
                }
            }
        }
示例#37
0
 internal SyntaxTreeBinding(Compilation compilation, SyntaxTree tree)
 {
     this.tree = tree;
     this.root = tree.Root; // keep node tree alive
     this.builder = compilation.GetContextBuilder(tree);
 }
示例#38
0
        public void InitializeFixture()
        {
            var linkers = BuildLinkers();

            ContextBuilder = new ContextBuilder <ITestDbContext>(new Dictionary <Type, object>(), linkers);
        }