Пример #1
0
        public bool GeneratePK()
        {
            if (!ID.Equals(Guid.Empty) && DocType > -1)
            {
                PK = PartitionKeyGenerator.Create(DocType.ToString(), ID.ToString());

                return(true);
            }
            else
            {
                return(false);
            }
        }
        public void ShouldBeStableInParallelGeneratePartitionKey()
        {
            var id         = Guid.NewGuid();
            var keyPattern = PartitionKeyGenerator.Generate(id, 2000);

            Parallel.For(0, 300000, (index) =>
            {
                var key = PartitionKeyGenerator.Generate(Guid.Parse(id.ToString()), 2000);
                if (key != keyPattern)
                {
                    throw new Exception($"{keyPattern} - {key}");
                }
            });

            // ASSERT
            Assert.IsTrue(true);
        }
Пример #3
0
        public void Generate()
        {
            Assert.AreEqual("X", PartitionKeyGenerator.Generate("X"));
            Assert.AreEqual("1", PartitionKeyGenerator.Generate(1));
            Assert.AreEqual("1.51", PartitionKeyGenerator.Generate(1.51m));
            Assert.AreEqual("1990-01-31T08:09:10.0000000", PartitionKeyGenerator.Generate(new DateTime(1990, 01, 31, 08, 09, 10)));

            var g = Guid.NewGuid();

            Assert.AreEqual(g.ToString(), PartitionKeyGenerator.Generate(g));

            var p = new Person {
                First = "Jane", Last = "Doe"
            };

            Assert.AreEqual("XCmFjH2zioLOelNdmU8hEQ==", PartitionKeyGenerator.Generate(p));
            Assert.AreEqual("E9ik+Agqes6hzHMezoJigw==", PartitionKeyGenerator.Generate(p, "XYZ"));
        }
Пример #4
0
        public void Generate()
        {
            Assert.AreEqual("X", PartitionKeyGenerator.Generate("X"));
            Assert.AreEqual("1", PartitionKeyGenerator.Generate(1));
            Assert.AreEqual("1.51", PartitionKeyGenerator.Generate(1.51m));
            Assert.AreEqual("1990-01-31T08:09:10.0000000", PartitionKeyGenerator.Generate(new DateTime(1990, 01, 31, 08, 09, 10)));

            var g = Guid.NewGuid();

            Assert.AreEqual(g.ToString(), PartitionKeyGenerator.Generate(g));

            var p = new Person {
                First = "Jane", Last = "Doe"
            };

            Assert.AreEqual("2I0QhKAlJMdHjCAocBhQeuzmze73jSnnWqyOkofhRn4=", PartitionKeyGenerator.Generate(p));
            Assert.AreEqual("471H/SShWDDr5wOVpMnhcu00Fw3nhOHN1aE8VNpXCsY=", PartitionKeyGenerator.Generate(p, "XYZ"));
        }
Пример #5
0
        public void GeneratePartitionKeyReturnsApplicationNameAndSuffix()
        {
            // Arrange
            const string sessionId       = "dummySessionId";
            const string applicationName = "applicationName";

            var md5            = MD5.Create();
            var hashedBytes    = md5.ComputeHash(Encoding.UTF8.GetBytes(sessionId));
            var hashedInt      = BitConverter.ToInt32(hashedBytes, 0);
            var expectedResult = $"{applicationName}{Math.Abs(hashedInt) % 20}";

            var generator = new PartitionKeyGenerator();

            // Act
            var result = generator.GeneratePartitionKey(applicationName, sessionId);

            // Assert
            Assert.Equal(expectedResult, result);
            md5.Dispose();
        }
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "assessment/{sessionId}/reload")] HttpRequest req,
            string sessionId,
            ILogger log,
            [Inject] IHttpRequestHelper httpRequestHelper,
            [Inject] IHttpResponseMessageHelper httpResponseMessageHelper,
            [Inject] IUserSessionRepository userSessionRepository,
            [Inject] IQuestionRepository questionRepository,
            [Inject] IOptions <AppSettings> appSettings)
        {
            try
            {
                var correlationId = httpRequestHelper.GetDssCorrelationId(req);
                if (string.IsNullOrEmpty(correlationId))
                {
                    log.LogInformation("Unable to locate 'DssCorrelationId' in request header");
                }

                if (!Guid.TryParse(correlationId, out var correlationGuid))
                {
                    log.LogInformation("Unable to parse 'DssCorrelationId' to a Guid");
                    correlationGuid = Guid.NewGuid();
                }

                if (string.IsNullOrEmpty(sessionId))
                {
                    log.LogInformation($"CorrelationId: {correlationGuid} - Session Id not supplied");
                    return(httpResponseMessageHelper.BadRequest());
                }

                if (string.IsNullOrEmpty(appSettings?.Value.SessionSalt))
                {
                    log.LogInformation($"CorrelationId: {correlationGuid} -Session salt not missing from configuration");
                    return(httpResponseMessageHelper.BadRequest());
                }

                if (!sessionId.Contains("-"))
                {
                    string partitionKey = PartitionKeyGenerator.UserSession(sessionId);
                    sessionId = $"{partitionKey}-{sessionId}";
                }

                var userSession = await userSessionRepository.GetUserSession(sessionId);

                if (userSession == null)
                {
                    log.LogError($"CorrelationId: {correlationGuid} - Session Id does not exist {sessionId}");
                    return(httpResponseMessageHelper.NoContent());
                }

                if (userSession.ResultData?.JobCategories?.Length == 0)
                {
                    userSession.AssessmentState.CurrentQuestion = 1;
                    userSession.AssessmentState.RecordedAnswers = new Answer[] {};
                    userSession.ResultData = null;
                    await userSessionRepository.UpdateUserSession(userSession);
                }

                var questionSetVersion = userSession.CurrentQuestionSetVersion;

                var question = await questionRepository.GetQuestion(userSession.CurrentQuestion, questionSetVersion);

                if (question == null)
                {
                    log.LogInformation($"CorrelationId: {correlationGuid} - Question number {userSession.CurrentQuestion} could not be found on session {userSession.PrimaryKey}");
                    return(httpResponseMessageHelper.NoContent());
                }

                int percentComplete = Convert.ToInt32((((decimal)userSession.CurrentQuestion - 1M) / (decimal)userSession.MaxQuestions) * 100);
                var response        = new AssessmentQuestionResponse()
                {
                    CurrentFilterAssessmentCode = userSession.FilteredAssessmentState?.CurrentFilterAssessmentCode,
                    IsComplete           = userSession.IsComplete,
                    NextQuestionNumber   = question.IsFilterQuestion ? userSession.FilteredAssessmentState?.MoveToNextQuestion() : userSession.AssessmentState.MoveToNextQuestion(),
                    QuestionId           = question.QuestionId,
                    QuestionText         = question.Texts.FirstOrDefault(x => x.LanguageCode.ToLower() == "en")?.Text,
                    TraitCode            = question.TraitCode,
                    QuestionNumber       = question.Order,
                    SessionId            = userSession.PrimaryKey,
                    PercentComplete      = percentComplete,
                    ReloadCode           = userSession.UserSessionId,
                    MaxQuestionsCount    = userSession.MaxQuestions,
                    RecordedAnswersCount = userSession.RecordedAnswers.Count(),
                    StartedDt            = userSession.StartedDt,
                    IsFilterAssessment   = userSession.IsFilterAssessment,
                    JobCategorySafeUrl   = (userSession.CurrentState as FilteredAssessmentState)?.JobFamilyNameUrlSafe
                };

                return(httpResponseMessageHelper.Ok(JsonConvert.SerializeObject(response)));
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Fatal exception {message}", ex.ToString());
                return(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.InternalServerError
                });
            }
        }
Пример #7
0
        static async Task Main()
        {
            var cs  = Environment.GetEnvironmentVariable("Beef_EventHubConnectionString");
            var ehc = new AzureEventHubs.EventHubProducerClient(cs);
            var ehp = new EventHubProducer(ehc);

            cs = Environment.GetEnvironmentVariable("Beef_ServiceBusConnectionString");
            var sbsc = new AzureServiceBus.ServiceBusClient(cs);
            var sbs  = new ServiceBusSender(sbsc, "Default");

            Console.WriteLine("Options are:");
            Console.WriteLine(" x - Stop.");
            Console.WriteLine();
            Console.WriteLine("EventHubs...");
            Console.WriteLine(" 1 - Non-subscribed Event.");
            Console.WriteLine(" 2 - Null Identifier.");
            Console.WriteLine(" 3 - Not Found Exception.");
            Console.WriteLine(" 4 - Unhandled Exception.");
            Console.WriteLine(" 5 - Invalid Data.");
            Console.WriteLine(" 6 - Success.");
            Console.WriteLine();
            Console.WriteLine("ServiceBus...");
            Console.WriteLine(" 11 - Non-subscribed Event.");
            Console.WriteLine(" 12 - Null Identifier.");
            Console.WriteLine(" 13 - Not Found Exception.");
            Console.WriteLine(" 14 - Unhandled Exception.");
            Console.WriteLine(" 15 - Invalid Data.");
            Console.WriteLine(" 16 - Success.");
            Console.WriteLine();

            while (true)
            {
                Console.Write("Enter option: ");
                switch (Console.ReadLine())
                {
                case "x":
                    return;

                case "1":
                    ehp.Publish("Something.Random", "Blah");
                    await ehp.SendAsync();

                    break;

                case "2":
                    ehp.Publish("Demo.Robot.Null", "PowerSourceChange");
                    await ehp.SendAsync();

                    break;

                case "3":
                    ehp.PublishValue(new PowerSourceChangeData {
                        RobotId = Guid.NewGuid(), PowerSource = "N"
                    }, "Demo.Robot.???", "PowerSourceChange");
                    await ehp.SendAsync();

                    break;

                case "4":
                    ehp.PublishValue(new PowerSourceChangeData {
                        RobotId = new Guid(88, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), PowerSource = "N"
                    }, "Demo.Robot.88", "PowerSourceChange");
                    await ehp.SendAsync();

                    break;

                case "5":
                    ehp.PublishValue(new PowerSourceChangeData {
                        RobotId = new Guid(2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), PowerSource = "!"
                    }, "Demo.Robot.2", "PowerSourceChange");
                    await ehp.SendAsync();

                    break;

                case "6":
                    var ed = EventData.CreateValueEvent(new PowerSourceChangeData {
                        RobotId = new Guid(2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), PowerSource = "N"
                    }, "Demo.Robot.2", "PowerSourceChange");
                    ed.Key          = new Guid(2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
                    ed.PartitionKey = PartitionKeyGenerator.Generate(Guid.NewGuid());
                    ehp.Publish(ed);
                    await ehp.SendAsync();

                    break;

                case "11":
                    sbs.Publish("Something.Random", "Blah");
                    await sbs.SendAsync();

                    break;

                case "12":
                    sbs.Publish("Demo.Robot.Null", "PowerSourceChange");
                    await sbs.SendAsync();

                    break;

                case "13":
                    sbs.PublishValue(new PowerSourceChangeData {
                        RobotId = Guid.NewGuid(), PowerSource = "N"
                    }, "Demo.Robot.???", "PowerSourceChange");
                    await sbs.SendAsync();

                    break;

                case "14":
                    sbs.PublishValue(new PowerSourceChangeData {
                        RobotId = new Guid(88, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), PowerSource = "N"
                    }, "Demo.Robot.88", "PowerSourceChange");
                    await sbs.SendAsync();

                    break;

                case "15":
                    sbs.PublishValue(new PowerSourceChangeData {
                        RobotId = new Guid(2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), PowerSource = "!"
                    }, "Demo.Robot.2", "PowerSourceChange");
                    await sbs.SendAsync();

                    break;

                case "16":
                    ed = EventData.CreateValueEvent(new PowerSourceChangeData {
                        RobotId = new Guid(2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), PowerSource = "N"
                    }, "Demo.Robot.2", "PowerSourceChange");
                    ed.Key          = new Guid(2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
                    ed.PartitionKey = PartitionKeyGenerator.Generate(Guid.NewGuid());
                    sbs.Publish(ed);
                    await sbs.SendAsync();

                    break;
                }

                ehp.Reset();
                sbs.Reset();
            }
        }
Пример #8
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "assessment")] HttpRequest req,
            ILogger log,
            [Inject] IHttpRequestHelper httpRequestHelper,
            [Inject] IHttpResponseMessageHelper httpResponseMessageHelper,
            [Inject] IUserSessionRepository userSessionRepository,
            [Inject] IQuestionSetRepository questionSetRepository,
            [Inject] IOptions <AppSettings> appSettings)
        {
            try
            {
                var correlationId = httpRequestHelper.GetDssCorrelationId(req);
                if (string.IsNullOrEmpty(correlationId))
                {
                    log.LogWarning("Unable to locate 'DssCorrelationId' in request header");
                    correlationId = Guid.NewGuid().ToString();
                }

                log.LogInformation($"CorrelationId: {correlationId} - Creating a new assessment");

                // Get the assessmentType and questionSetTitle values from the query string
                var queryDictionary = System.Web.HttpUtility.ParseQueryString(req.QueryString.ToString());
                var assessmentType  = queryDictionary.Get("assessmentType");
                if (string.IsNullOrEmpty(assessmentType))
                {
                    log.LogInformation($"CorrelationId: {correlationId} - Missing assessmentType {assessmentType}");
                    return(httpResponseMessageHelper.BadRequest());
                }

                // Get the current question set version for this assesssment type and title (supplied by CMS - configured in appsettings)
                var currentQuestionSetInfo = await questionSetRepository.GetCurrentQuestionSet(assessmentType);

                if (currentQuestionSetInfo == null)
                {
                    log.LogInformation($"CorrelationId: {correlationId} - Unable to load latest question set {assessmentType}");
                    return(httpResponseMessageHelper.NoContent());
                }


                // Create a new user session
                string salt         = appSettings.Value.SessionSalt;
                string sessionId    = SessionIdHelper.GenerateSessionId(salt);
                string partitionKey = PartitionKeyGenerator.UserSession(sessionId);

                var userSession = new UserSession()
                {
                    UserSessionId   = sessionId,
                    Salt            = salt,
                    StartedDt       = DateTime.Now,
                    LanguageCode    = "en",
                    PartitionKey    = partitionKey,
                    AssessmentState = new AssessmentState(currentQuestionSetInfo.QuestionSetVersion, currentQuestionSetInfo.MaxQuestions),
                    AssessmentType  = currentQuestionSetInfo.AssessmentType.ToLower()
                };
                await userSessionRepository.CreateUserSession(userSession);

                log.LogInformation($"CorrelationId: {correlationId} - Finished creating new assessment {userSession.UserSessionId}");

                var result = new FilterSessionResponse()
                {
                    SessionId = userSession.PrimaryKey
                };
                return(httpResponseMessageHelper.Ok(JsonConvert.SerializeObject(result)));
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Fatal exception {message}", ex.ToString());
                return(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.InternalServerError
                });
            }
        }