예제 #1
0
        private IMsalRequest CreateRequest(
            AuthenticationParameters authParameters,
            bool isInteractive)
        {
            var authParams = authParameters.Clone();

            authParams.TelemetryCorrelationId = _guidService.NewGuid();
            authParams.Logger = _platformProxy.CreateLogger(
                authParams.TelemetryCorrelationId,
                _msalClientConfiguration);

            var webRequestManager = new WebRequestManager(
                _httpManager,
                _platformProxy.GetSystemUtils(),
                _environmentMetadata,
                authParams);
            var cacheManager = new CacheManager(_storageManager, authParams);

            if (isInteractive)
            {
                return(new MsalInteractiveRequest(webRequestManager, cacheManager, _browserFactory, authParams));
            }
            else
            {
                return(new MsalBackgroundRequest(
                           webRequestManager,
                           cacheManager,
                           _platformProxy.GetSystemUtils(),
                           authParams));
            }
        }
예제 #2
0
        public T Create <T>(T cmd) where T : ICommand
        {
            if (_currentContext != null &&
                _currentContext.ClaimsPrincipal != null &&
                _currentContext.ClaimsPrincipal.Identity != null &&
                !string.IsNullOrWhiteSpace(_currentContext.ClaimsPrincipal.Identity.Name))
            {
                cmd.User = _currentContext.ClaimsPrincipal.Identity.Name;
            }
            else
            {
                cmd.User = "******";
            }

            MessageProperties             prop     = _currentContext.IncomingMessageProperties;
            RemoteEndpointMessageProperty endpoint = prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;

            cmd.IPAddress = endpoint.Address;

            if (cmd.CommandId == Guid.Empty)
            {
                cmd.CommandId = _guidService.NewGuid();
            }

            cmd.Timestamp = _dateTimeService.Now();

            return(cmd);
        }
예제 #3
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            [ServiceBus("scratch", Connection = "SbConnection")] IAsyncCollector <string> queueCollector)
        {
            _log.LogInformation("Information");
            _log.LogTrace("Trace");
            _log.LogDebug("Debug");
            _log.LogCritical("Critical");
            _log.LogError("Error");
            _log.LogMetric("Metric", 9.001e+3);
            _log.LogWarning("Warning");
            string name = req.Query["name"];

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            name = name ?? data?.name;

            var greeting = _cfg["Greeting"] ?? "Hello";

            _log.LogInformation("Guid Service says {guid}", _guidService.NewGuid());
            _log.LogInformation("{greeting}, {name}!", greeting, name);
            await queueCollector.AddAsync($"{greeting}, {name}!");

            return(name != null
                ? (ActionResult) new OkObjectResult($"{greeting}, {name}!")
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body"));
        }
        public async Task <TestSummary> RunTests(IEnumerable <Test> tests)
        {
            var testSummary = new TestSummary();
            var tasks       = new List <Task <Models.TestAutomation.TestResult> >();

            foreach (var test in tests)
            {
                tasks.Add(Process(test.TestClass, test));
            }
            ;

            testSummary.StartDateTime = DateTime.UtcNow;
            testSummary.TestResults   = (await Task.WhenAll(tasks)).ToList();
            testSummary.EndDateTime   = DateTime.UtcNow;
            testSummary.Id            = _guidService.NewGuid().ToString();
            return(testSummary);
        }
예제 #5
0
 private async Task RequestUsingProxy(IJsonPlaceHolderProxyService jsonPlaceHolderProxyService, ICorrelationService correlationService, IGuidService guidService)
 {
     correlationService.CorrelationId = guidService.NewGuid().ToString();
     await jsonPlaceHolderProxyService.GetTodosAsync(new GetTodosRequest
     {
         Items = 2
     }).ConfigureAwait(false);
 }
        internal string EnsureCorrelationId(HttpRequest request)
        {
            if (!request.Headers.Any(e => e.Key == CORRELATION_ID))
            {
                return(_guidService.NewGuid().ToString());
            }

            return(request.Headers.First(e => e.Key == CORRELATION_ID).Value);
        }
        public async Task <CreateAccountDescriptor> CreateAsync(string username, string password, string email)
        {
            var createAccountDescriptor = new CreateAccountDescriptor();

            var encryptResult = _encryptionService.Encrypt(password);

            var activateEmailToken   = _guidService.NewGuid().ToString();
            var emailPreferenceToken = _guidService.NewGuid().ToString();

            var insertAccountResult = await
                                      _accountDBService.InsertAccountAsync
                                      (
                new InsertAccountRequest
            {
                Username             = username,
                PasswordHash         = encryptResult.Hash,
                Salt                 = encryptResult.Salt,
                ActivateEmailToken   = activateEmailToken,
                EmailPreferenceToken = emailPreferenceToken,
                Email                = email,
                EmailPreference      = EmailPreference.Any
            }
                                      );

            if (insertAccountResult.DuplicateUser)
            {
                createAccountDescriptor.Result = CreateAccountResult.DuplicateUser;
                return(createAccountDescriptor);
            }

            if (email != null)
            {
                await _emailService.SendActivateEmailAsync(email, username, activateEmailToken, emailPreferenceToken);
            }

            //Service Bus, Or Que To N Services, Or call N Services., Or Single Que that will call all the services.

            createAccountDescriptor.Result    = CreateAccountResult.Successful;
            createAccountDescriptor.AccountId = insertAccountResult.AccountId;

            return(createAccountDescriptor);
        }
예제 #8
0
        public T Create <T>(T query)
            where T : IQuery
        {
            query.IPAddress = _currentContext.Request.UserHostAddress;

            if (query.QueryId == Guid.Empty)
            {
                query.QueryId = _guidService.NewGuid();
            }

            query.Timestamp = _dateTimeService.Now();

            return(query);
        }
예제 #9
0
        public T Create <T>(T cmd)
            where T : ICommand
        {
            cmd.IPAddress = _currentContext.Request.UserHostAddress;

            if (cmd.CommandId == Guid.Empty)
            {
                cmd.CommandId = _guidService.NewGuid();
            }

            cmd.Timestamp = _dateTimeService.Now();

            return(cmd);
        }
예제 #10
0
        private async Task Request(ICorrelationService correlationService, IGuidService guidService, IDurableRestService durableRestService)
        {
            correlationService.CorrelationId = guidService.NewGuid().ToString();

            using var httpClient = new HttpClient
                  {
                      BaseAddress = new Uri("https://jsonplaceholder.typicode.com/")
                  };

            var httpRequestMessage = new HttpRequestMessage
            {
                Method     = HttpMethod.Get,
                RequestUri = new Uri("todos/1", UriKind.Relative)
            };

            var retrys           = 3;
            var timeoutInSeconds = 30;
            var restResponse     = await durableRestService.ExecuteAsync(httpClient, httpRequestMessage, retrys, timeoutInSeconds).ConfigureAwait(false);
        }
예제 #11
0
        private IMsalRequest CreateRequest(
            AuthenticationParameters authParameters,
            bool isInteractive)
        {
            var authParams = authParameters.Clone();

            // "hack" to work around default constructors in legacy scenarios...
            if (string.IsNullOrWhiteSpace(authParams.ClientId))
            {
                authParams.ClientId = _msalClientConfiguration.DefaultClientId;
            }

            if (string.IsNullOrWhiteSpace(authParams.Authority))
            {
                authParams.Authority = _msalClientConfiguration.DefaultAuthority;
            }

            authParams.TelemetryCorrelationId = _guidService.NewGuid();
            authParams.Logger = _platformProxy.CreateLogger(
                authParams.TelemetryCorrelationId,
                _msalClientConfiguration);

            var webRequestManager = new WebRequestManager(
                _httpManager,
                _platformProxy.GetSystemUtils(),
                _environmentMetadata,
                authParams);
            var cacheManager = new CacheManager(_storageManager, authParams);

            if (isInteractive)
            {
                return(new MsalInteractiveRequest(webRequestManager, cacheManager, _browserFactory, authParams));
            }
            else
            {
                return(new MsalBackgroundRequest(
                           webRequestManager,
                           cacheManager,
                           _platformProxy.GetSystemUtils(),
                           authParams));
            }
        }
        public async Task <ActionResult> Register([FromBody] RegisterDto model)
        {
            var user = new AppUser
            {
                Email         = model.Email,
                UserName      = model.Email,
                SecurityStamp = _guidService.NewGuid().ToString()
            };
            var result = await _userManager.CreateAsync(user, model.Password);

            if (result.Succeeded)
            {
                await _userManager.AddToRoleAsync(user, Roles.User.ToString());
            }
            else
            {
                return(BadRequest(result.Errors));
            }

            return(Ok());
        }
예제 #13
0
        private void PersistEventToDatabase(IEvent e, ICommand c, Guid aggregateId)
        {
            e.EventId     = _guidService.NewGuid();
            e.Timestamp   = _dateTimeService.Now();
            e.CommandId   = c.CommandId;
            e.AggregateId = aggregateId;

            var eventXml = SerializeEvent(e);
            var sql      = "INSERT INTO Events(EventId, EventDateTime, CommandId, AggregateId, EventType, EventData, Published)";

            sql += " VALUES(@EventId, @EventDateTime, @CommandId, @AggregateId, @EventType, @EventData, @Published)";

            _databaseLayer.ExecuteNonQuery(
                sql,
                "@EventId", e.EventId,
                "@EventDateTime", e.Timestamp.ToUniversalTime().ToString("dd-MMM-yyyy HH:mm:ss.ff"),
                "@CommandId", e.CommandId,
                "@AggregateId", e.AggregateId,
                "@EventType", e.GetType().AssemblyQualifiedName,
                "@EventData", eventXml,
                "@Published", false);
        }
예제 #14
0
        public async Task <Guid> CreateNewTestRunAsync(string testAssemblyName, byte[] outputFilesZip, int retriesCount, double threshold, bool runInParallel, int maxParallelProcessesCount, string nativeArguments, string testTechnology, bool isTimeBasedBalance, bool sameMachineByClass, IEnumerable <string> customArgumentsPairs = null)
        {
            if (testAssemblyName == null)
            {
                throw new ArgumentException("testAssemblyName must be provided.");
            }

            var newTestRun = new TestRunDto
            {
                TestRunId                 = _guidService.NewGuid(),
                DateStarted               = _dateTimeProvider.GetCurrentTime(),
                TestAssemblyName          = testAssemblyName,
                Status                    = TestRunStatus.InProgress,
                RetriesCount              = retriesCount,
                Threshold                 = threshold,
                RunInParallel             = runInParallel,
                NativeArguments           = nativeArguments,
                MaxParallelProcessesCount = maxParallelProcessesCount,
                TestTechnology            = testTechnology,
                IsTimeBasedBalance        = isTimeBasedBalance,
                SameMachineByClass        = sameMachineByClass,
            };

            newTestRun = await _testRunServiceClient.CreateAsync(newTestRun);

            var newTestRunOutput = new TestRunOutputDto()
            {
                TestRunId = newTestRun.TestRunId,
                TestOutputFilesPackage = outputFilesZip,
            };
            await _testRunOutputServiceClient.CreateAsync(newTestRunOutput);

            if (customArgumentsPairs != null)
            {
                await CreateTestRunCustomArgumentsAsync(newTestRun.TestRunId, customArgumentsPairs);
            }

            return(newTestRun.TestRunId);
        }
예제 #15
0
        private async Task ExecuteTestAgentRunAsync(TestAgentRunDto testAgentRun, int testAgentRunTimeout, CancellationTokenSource cancellationTokenSource)
        {
            _pluginService.ExecuteAllTestAgentPluginsPreTestRunLogic();

            testAgentRun.Status = TestAgentRunStatus.InProgress;
            await CreateEnvironmentVariablesForCustomArgumentsAsync(testAgentRun.TestRunId).ConfigureAwait(false);

            await _testAgentRunRepository.UpdateAsync(testAgentRun.TestAgentRunId, testAgentRun).ConfigureAwait(false);

            var testRun = await _testRunRepository.GetAsync(testAgentRun.TestRunId).ConfigureAwait(false);

            var tempExecutionFolder = _pathProvider.Combine(_pathProvider.GetTempFolderPath(), _guidService.NewGuid().ToString());
            var tempZipFileName     = _pathProvider.GetTempFileName();
            var testRunOutput       = await _testRunOutputServiceClient.GetTestRunOutputByTestRunIdAsync(testRun.TestRunId).ConfigureAwait(false);

            if (testRunOutput == null)
            {
                // DEBUG:
                await _testRunLogService.CreateTestRunLogAsync("The test run output cannot be null.", testAgentRun.TestRunId).ConfigureAwait(false);

                throw new ArgumentException("The test run output cannot be null.");
            }

            _fileProvider.WriteAllBytes(tempZipFileName, testRunOutput.TestOutputFilesPackage);
            _fileProvider.ExtractZip(tempZipFileName, tempExecutionFolder);
            var testRunTestsAssemblyPath = _pathProvider.Combine(tempExecutionFolder, testRun.TestAssemblyName);

            if (cancellationTokenSource.IsCancellationRequested)
            {
                return;
            }

            var testsResults = await _nativeTestsRunner.ExecuteTestsAsync(
                testRun.TestTechnology,
                testAgentRun.TestList,
                tempExecutionFolder,
                testAgentRun.TestRunId,
                testRunTestsAssemblyPath,
                testRun.TestAssemblyName,
                testRun.RunInParallel,
                testRun.NativeArguments,
                testAgentRunTimeout,
                testRun.IsTimeBasedBalance,
                testRun.SameMachineByClass,
                cancellationTokenSource).ConfigureAwait(false);

            var retriedTestResults = string.Empty;

            if (testRun.RetriesCount > 0)
            {
                retriedTestResults = await _nativeTestsRunner.ExecuteTestsWithRetryAsync(
                    testRun.TestTechnology,
                    testsResults,
                    testAgentRun.TestList,
                    tempExecutionFolder,
                    testAgentRun.TestRunId,
                    testRunTestsAssemblyPath,
                    testRun.TestAssemblyName,
                    testRun.RunInParallel,
                    testRun.NativeArguments,
                    testAgentRunTimeout,
                    testRun.RetriesCount,
                    testRun.Threshold,
                    testRun.IsTimeBasedBalance,
                    testRun.SameMachineByClass,
                    cancellationTokenSource).ConfigureAwait(false);
            }

            if (cancellationTokenSource.IsCancellationRequested)
            {
                return;
            }

            await CompleteTestAgentRunAsync(testAgentRun.TestAgentRunId, testsResults, retriedTestResults).ConfigureAwait(false);

            _pluginService.ExecuteAllTestAgentPluginsPostTestRunLogic();

            DeleteTempExecutionFolder(tempExecutionFolder);
        }
        public string GenerateTRXReport
        (
            TestSummary testSummary
        )
        {
            var runId            = _guidService.NewGuid().ToString();
            var testSettingsGuid = _guidService.NewGuid().ToString();

            var testLists = new TestList[]
            {
                new TestList
                {
                    Id   = _guidService.NewGuid().ToString(),
                    Name = TEST_LIST_NAME_RESULTS_NOT_IN_A_LIST
                },
                new TestList
                {
                    Id   = _guidService.NewGuid().ToString(),
                    Name = TEST_LIST_NAME_ALL_LOADED_TESTS
                }
            };

            var testRun = new TestRun
            {
                Id      = runId,
                Name    = $"{ TEST_RUN_NAME} {testSummary.StartDateTime.ToString(@"yyyy-MM-dd HH:mm:ss")}",
                RunUser = TEST_RUN_USER,
                Times   = new Times
                {
                    Creation = testSummary.StartDateTime.ToString(@"yyyy-MM-ddTHH:mm:ss.FFFFFFF+00:00"),
                    Finsh    = testSummary.EndDateTime.ToString(@"yyyy-MM-ddTHH:mm:ss.FFFFFFF+00:00"),
                    Queuing  = testSummary.StartDateTime.ToString(@"yyyy-MM-ddTHH:mm:ss.FFFFFFF+00:00"),
                    Start    = testSummary.StartDateTime.ToString(@"yyyy-MM-ddTHH:mm:ss.FFFFFFF+00:00")
                },
                TestSettings = new TestSettings
                {
                    Deployment = new Deployment
                    {
                        RunDeploymentRoot = RUN_DEPLOYMENT_ROOT
                    },
                    Name = DEPLOYMENT_NAME,
                    Id   = testSettingsGuid.ToString()
                },
                Results = testSummary.TestResults.Select(testResult => new UnitTestResult
                {
                    ComputerName             = COMPUTER_NAME,
                    Duration                 = testResult.Duration.ToString(),
                    StartTime                = testResult.StartTime.ToString(@"yyyy-MM-ddTHH:mm:ss.FFFFFFF+00:00"),
                    EndTime                  = testResult.EndTime.ToString(@"yyyy-MM-ddTHH:mm:ss.FFFFFFF+00:00"),
                    ExecutionId              = testResult.ExecutionId.ToString(),
                    Outcome                  = testResult.Pass ? "passed" : "failed",
                    RelativeResultsDirectory = RELATIVE_RESULTS_DIRECTORY,
                    TestId     = testResult.TestId.ToString(),
                    TestListId = testLists[0].Id,
                    TestName   = testResult.TestName,
                    TestType   = testResult.TestType.ToString(),
                }).ToArray(),
                TestDefinitions = testSummary.TestResults.Select(testResult => new UnitTest
                {
                    Execution = new Execution
                    {
                        Id = testResult.ExecutionId.ToString()
                    },
                    Id         = testResult.TestId.ToString(),
                    Name       = testResult.TestName,
                    Storage    = UNIT_TEST_PATH,
                    TestMethod = new TestMethod
                    {
                        AdapterTypeName = ADAPTER_TYPE_NAME,
                        ClassName       = testResult.ClassName,
                        CodeBase        = CODE_BASE,
                        Name            = testResult.TestName
                    }
                }).ToArray(),
                TestEntries = testSummary.TestResults.Select(testResult => new TestEntry
                {
                    ExecutionId = testResult.ExecutionId.ToString(),
                    TestId      = testResult.TestId.ToString(),
                    TestListId  = testLists[0].Id
                }).ToArray(),
                TestLists     = testLists,
                ResultSummary = new ResultSummary
                {
                    Outcome  = RESULT_OUTCOME,
                    Counters = new Counters
                    {
                        Total    = testSummary.TestResults.Count(),
                        Executed = testSummary.TestResults.Count(),
                        Passed   = testSummary.TestResults.Count(testresult => testresult.Pass),
                        Failed   = testSummary.TestResults.Count(testresult => !testresult.Pass)
                    }
                }
            };

            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

            ns.Add("", "");
            XmlSerializer xmlSerializer = new XmlSerializer(testRun.GetType());

            using Utf8StringWriter textWriter = new Utf8StringWriter();
            xmlSerializer.Serialize(textWriter, testRun, ns);
            return(textWriter.ToString());
        }
예제 #17
0
        private string BuildTokenRequestMessage(
            AuthorizationType authType,
            string cloudAudienceUri,
            string username,
            string password)
        {
            string soapAction;
            string trustNamespace;
            string keyType;
            string requestType;

            if (Version == WsTrustVersion.WsTrust2005)
            {
                soapAction     = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue";
                trustNamespace = "http://schemas.xmlsoap.org/ws/2005/02/trust";
                keyType        = "http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey";
                requestType    = "http://schemas.xmlsoap.org/ws/2005/02/trust/Issue";
            }
            else
            {
                soapAction     = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue";
                trustNamespace = "http://docs.oasis-open.org/ws-sx/ws-trust/200512";
                keyType        = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer";
                requestType    = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue";
            }

            const string wsaNamespaceValue = "http://www.w3.org/2005/08/addressing";

            using (var sw = new StringWriterWithEncoding(Encoding.UTF8))
            {
                using (var writer = XmlWriter.Create(
                           sw,
                           new XmlWriterSettings()
                {
                    Async = false,
                    Encoding = Encoding.UTF8,
                    CloseOutput = false
                }))
                {
                    writer.WriteStartElement("s", "Envelope", envelopeNamespaceValue);
                    writer.WriteAttributeString("wsa", "http://www.w3.org/2000/xmlns/", wsaNamespaceValue);
                    writer.WriteAttributeString("wsu", "http://www.w3.org/2000/xmlns/", wsuNamespaceValue);

                    writer.WriteStartElement("Header", envelopeNamespaceValue);
                    writer.WriteStartElement("Action", wsaNamespaceValue);
                    writer.WriteAttributeString("mustUnderstand", envelopeNamespaceValue, "1");
                    writer.WriteString(soapAction);
                    writer.WriteEndElement(); // Action

                    writer.WriteStartElement("messageID", wsaNamespaceValue);
                    writer.WriteString($"urn:uuid:{_guidService.NewGuid().ToString("D")}");
                    writer.WriteEndElement(); // messageID

                    writer.WriteStartElement("ReplyTo", wsaNamespaceValue);
                    writer.WriteStartElement("Address", wsaNamespaceValue);
                    writer.WriteString("http://www.w3.org/2005/08/addressing/anonymous");
                    writer.WriteEndElement(); // Address
                    writer.WriteEndElement(); // ReplyTo

                    writer.WriteStartElement("To", wsaNamespaceValue);
                    writer.WriteAttributeString("mustUnderstand", envelopeNamespaceValue, "1");
                    writer.WriteString(Uri.ToString());
                    writer.WriteEndElement(); // To

                    if (authType == AuthorizationType.UsernamePassword)
                    {
                        AppendSecurityHeader(writer, username, password);
                    }

                    writer.WriteEndElement(); // Header

                    writer.WriteStartElement("Body", envelopeNamespaceValue);
                    writer.WriteStartElement("wst", "RequestSecurityToken", trustNamespace);
                    writer.WriteStartElement("wsp", "AppliesTo", "http://schemas.xmlsoap.org/ws/2004/09/policy");
                    writer.WriteStartElement("EndpointReference", wsaNamespaceValue);
                    writer.WriteStartElement("Address", wsaNamespaceValue);
                    writer.WriteString(cloudAudienceUri);
                    writer.WriteEndElement(); // Address
                    writer.WriteEndElement(); // EndpointReference
                    writer.WriteEndElement(); // AppliesTo

                    writer.WriteStartElement("KeyType", trustNamespace);
                    writer.WriteString(keyType);
                    writer.WriteEndElement(); // KeyType

                    writer.WriteStartElement("RequestType", trustNamespace);
                    writer.WriteString(requestType);
                    writer.WriteEndElement(); // RequestType

                    writer.WriteEndElement(); // RequestSecurityToken

                    writer.WriteEndElement(); // Body
                    writer.WriteEndElement(); // Envelope
                }

                return(sw.ToString());
            }
        }