Exemple #1
0
        public void DroppingAnnotations()
        {
            int         maxNumberOfAnnotations = 8;
            TraceParams traceParams            =
                TraceParams.Default.ToBuilder().SetMaxNumberOfAnnotations(maxNumberOfAnnotations).Build();
            ISpan span =
                Span.StartSpan(
                    spanContext,
                    recordSpanOptions,
                    SPAN_NAME,
                    parentSpanId,
                    false,
                    traceParams,
                    startEndHandler,
                    timestampConverter,
                    testClock);
            IAnnotation annotation = Annotation.FromDescription(ANNOTATION_DESCRIPTION);
            int         i          = 0;

            for (i = 0; i < 2 * maxNumberOfAnnotations; i++)
            {
                span.AddAnnotation(annotation);
                testClock.AdvanceTime(Duration.Create(0, 100));
            }
            ISpanData spanData = ((Span)span).ToSpanData();

            Assert.Equal(maxNumberOfAnnotations, spanData.Annotations.DroppedEventsCount);
            Assert.Equal(maxNumberOfAnnotations, spanData.Annotations.Events.Count());
            i = 0;
            foreach (var te in spanData.Annotations.Events)
            {
                Assert.Equal(timestamp.AddNanos(100 * (maxNumberOfAnnotations + i)), te.Timestamp);
                Assert.Equal(annotation, te.Event);
                i++;
            }
            span.End();
            spanData = ((Span)span).ToSpanData();
            Assert.Equal(maxNumberOfAnnotations, spanData.Annotations.DroppedEventsCount);
            Assert.Equal(maxNumberOfAnnotations, spanData.Annotations.Events.Count());
            i = 0;
            foreach (var te in spanData.Annotations.Events)
            {
                Assert.Equal(timestamp.AddNanos(100 * (maxNumberOfAnnotations + i)), te.Timestamp);
                Assert.Equal(annotation, te.Event);
                i++;
            }
        }
Exemple #2
0
        public void DroppingNetworkEvents()
        {
            int         maxNumberOfNetworkEvents = 8;
            TraceParams traceParams =
                TraceParams.DEFAULT
                .ToBuilder()
                .SetMaxNumberOfMessageEvents(maxNumberOfNetworkEvents)
                .Build();
            ISpan span =
                Span.StartSpan(
                    spanContext,
                    recordSpanOptions,
                    SPAN_NAME,
                    parentSpanId,
                    false,
                    traceParams,
                    startEndHandler,
                    timestampConverter,
                    testClock);
            IMessageEvent networkEvent = MessageEvent.Builder(MessageEventType.RECEIVED, 1).SetUncompressedMessageSize(3).Build();

            for (int i = 0; i < 2 * maxNumberOfNetworkEvents; i++)
            {
                span.AddMessageEvent(networkEvent);
                testClock.AdvanceTime(Duration.Create(0, 100));
            }

            ISpanData spanData = ((Span)span).ToSpanData();

            Assert.Equal(maxNumberOfNetworkEvents, spanData.MessageEvents.DroppedEventsCount);
            Assert.Equal(maxNumberOfNetworkEvents, spanData.MessageEvents.Events.Count);
            for (int i = 0; i < maxNumberOfNetworkEvents; i++)
            {
                Assert.Equal(timestamp.AddNanos(100 * (maxNumberOfNetworkEvents + i)), spanData.MessageEvents.Events[i].Timestamp);
                Assert.Equal(networkEvent, spanData.MessageEvents.Events[i].Event);
            }

            span.End();
            spanData = ((Span)span).ToSpanData();
            Assert.Equal(maxNumberOfNetworkEvents, spanData.MessageEvents.DroppedEventsCount);
            Assert.Equal(maxNumberOfNetworkEvents, spanData.MessageEvents.Events.Count);
            for (int i = 0; i < maxNumberOfNetworkEvents; i++)
            {
                Assert.Equal(timestamp.AddNanos(100 * (maxNumberOfNetworkEvents + i)), spanData.MessageEvents.Events[i].Timestamp);
                Assert.Equal(networkEvent, spanData.MessageEvents.Events[i].Event);
            }
        }
Exemple #3
0
        public void GetErrorSampledSpans_NullCode()
        {
            Span span1 = CreateSampledSpan(REGISTERED_SPAN_NAME) as Span;

            testClock.AdvanceTime(Duration.Create(0, 1000));
            span1.End(EndSpanOptions.Builder().SetStatus(Status.Cancelled).Build());
            Span span2 = CreateSampledSpan(REGISTERED_SPAN_NAME) as Span;

            testClock.AdvanceTime(Duration.Create(0, 1000));
            span2.End(EndSpanOptions.Builder().SetStatus(Status.Unknown).Build());
            var samples =
                sampleStore.GetErrorSampledSpans(SampledSpanStoreErrorFilter.Create(REGISTERED_SPAN_NAME, null, 0));

            Assert.Equal(2, samples.Count());
            Assert.Contains(span1.ToSpanData(), samples);
            Assert.Contains(span2.ToSpanData(), samples);
        }
Exemple #4
0
        public void GetLatencySampledSpans_InclusiveLowerBound()
        {
            Span span = CreateSampledSpan(REGISTERED_SPAN_NAME) as Span;

            testClock.AdvanceTime(Duration.Create(0, 20000)); // 20 microseconds
            span.End();
            var samples =
                sampleStore.GetLatencySampledSpans(
                    SampledSpanStoreLatencyFilter.Create(
                        REGISTERED_SPAN_NAME,
                        15000,
                        25000,
                        0));

            Assert.Single(samples);
            Assert.Contains(span.ToSpanData(), samples);
        }
Exemple #5
0
        public void DroppingEvents()
        {
            int         maxNumberOfEvents = 8;
            TraceParams traceParams       =
                TraceParams.Default.ToBuilder().SetMaxNumberOfEvents(maxNumberOfEvents).Build();
            ISpan span =
                Span.StartSpan(
                    spanContext,
                    recordSpanOptions,
                    SPAN_NAME,
                    SpanKind.Internal,
                    parentSpanId,
                    traceParams,
                    startEndHandler,
                    timestampConverter);
            IEvent testEvent = Event.Create(EVENT_DESCRIPTION);
            int    i         = 0;

            for (i = 0; i < 2 * maxNumberOfEvents; i++)
            {
                span.AddEvent(testEvent);
                interval += TimeSpan.FromMilliseconds(100);
            }
            SpanData spanData = ((Span)span).ToSpanData();

            Assert.Equal(maxNumberOfEvents, spanData.Events.DroppedEventsCount);
            Assert.Equal(maxNumberOfEvents, spanData.Events.Events.Count());
            i = 0;
            foreach (var te in spanData.Events.Events)
            {
                Assert.Equal(timestamp.AddDuration(Duration.Create(TimeSpan.FromMilliseconds(100 * (maxNumberOfEvents + i)))), te.Timestamp);
                Assert.Equal(testEvent, te.Event);
                i++;
            }
            span.End();
            spanData = ((Span)span).ToSpanData();
            Assert.Equal(maxNumberOfEvents, spanData.Events.DroppedEventsCount);
            Assert.Equal(maxNumberOfEvents, spanData.Events.Events.Count());
            i = 0;
            foreach (var te in spanData.Events.Events)
            {
                Assert.Equal(timestamp.AddDuration(Duration.Create(TimeSpan.FromMilliseconds(100 * (maxNumberOfEvents + i)))), te.Timestamp);
                Assert.Equal(testEvent, te.Event);
                i++;
            }
        }
        public void GetLatencySampledSpans()
        {
            Span span = CreateSampledSpan(REGISTERED_SPAN_NAME) as Span;

            testClock.AdvanceTime(Duration.Create(0, 20000)); // 20 microseconds
            span.End();
            IList <ISpanData> samples =
                sampleStore.GetLatencySampledSpans(
                    SampledSpanStoreLatencyFilter.Create(
                        REGISTERED_SPAN_NAME,
                        15000,
                        25000,
                        0));

            Assert.Equal(1, samples.Count);
            Assert.True(samples.Contains(span.ToSpanData()));
        }
Exemple #7
0
        public async Task ExportAsyncCallsAllHandlers()
        {
            var exporter = SpanExporter.Create(4, Duration.Create(1, 0));

            var handler1 = new Mock <IHandler>();

            exporter.RegisterHandler("first", handler1.Object);

            var span1 = CreateNotSampledEndedSpan(SPAN_NAME_1).ToSpanData();

            await exporter.ExportAsync(span1, CancellationToken.None);

            Assert.Single(handler1.Invocations);
            var args = (IEnumerable <SpanData>)handler1.Invocations.First().Arguments.First();

            handler1.Verify(c => c.ExportAsync(It.Is <IEnumerable <SpanData> >(
                                                   (x) => x.Where((s) => s == span1).Count() > 0 &&
                                                   x.Count() == 1)));
        }
        public void Post(Guid consultantId, DateTime date, [FromBody] RegistrationDTO registrationDTO)
        {
            var consultants = new ConsultantsAgent();
            var consultant  = consultants.TheOneWithId(consultantId);

            var days = new Days(db.One);
            var day  = days.CertainDayForConsultant(consultant, date);

            if (day == null)
            {
                day = new Day(consultant, date);
            }

            var projects     = new Projects(db.One);
            var project      = projects.TheOneWithName(registrationDTO.projectName);
            var registration = new Registration(Duration.Create(registrationDTO.duration), registrationDTO.activity, project);

            day.AddRegistration(registration);
            days.Save(day);
        }
Exemple #9
0
        public void GetErrorSampledSpans_MaxSpansToReturn()
        {
            Span span1 = CreateSampledSpan(REGISTERED_SPAN_NAME) as Span;

            testClock.AdvanceTime(Duration.Create(0, 1000));
            span1.End(EndSpanOptions.Builder().SetStatus(Status.Cancelled).Build());
            // Advance time to allow other spans to be sampled.
            testClock.AdvanceTime(Duration.Create(5, 0));
            Span span2 = CreateSampledSpan(REGISTERED_SPAN_NAME) as Span;

            testClock.AdvanceTime(Duration.Create(0, 1000));
            span2.End(EndSpanOptions.Builder().SetStatus(Status.Cancelled).Build());
            var samples =
                sampleStore.GetErrorSampledSpans(
                    SampledSpanStoreErrorFilter.Create(REGISTERED_SPAN_NAME, CanonicalCode.Cancelled, 1));

            Assert.Single(samples);
            // No order guaranteed so one of the spans should be in the list.
            Assert.True(samples.Contains(span1.ToSpanData()) || samples.Contains(span2.ToSpanData()));
        }
Exemple #10
0
 private void AddSpanNameToAllLatencyBuckets(string spanName)
 {
     foreach (LatencyBucketBoundaries boundaries in LatencyBucketBoundaries.Values)
     {
         ISpan sampledSpan    = CreateSampledSpan(spanName);
         ISpan notSampledSpan = CreateNotSampledSpan(spanName);
         if (boundaries.LatencyLowerNs < NUM_NANOS_PER_SECOND)
         {
             testClock.AdvanceTime(Duration.Create(0, (int)boundaries.LatencyLowerNs));
         }
         else
         {
             testClock.AdvanceTime(
                 Duration.Create(
                     boundaries.LatencyLowerNs / NUM_NANOS_PER_SECOND,
                     (int)(boundaries.LatencyLowerNs % NUM_NANOS_PER_SECOND)));
         }
         sampledSpan.End();
         notSampledSpan.End();
     }
 }
        public void Create_ConferenceWithTrackAndTalk_ReturnsConference()
        {
            // Arrange
            var conferenceId = Guid.NewGuid();
            var trackId      = Guid.NewGuid();
            var talkId       = Guid.NewGuid();

            var conferenceIdObj = ConferenceId.Create(conferenceId).Data;
            var trackIdObj      = TrackId.Create(trackId).Data;
            var talkIdObj       = TalkId.Create(talkId).Data;
            var title           = Title.Create("First talk").Data;
            var description     = Description.Create("This is the first talk").Data;
            var duration        = Duration.Create(TimeSpan.FromMinutes(30)).Data;        // 30 minutes
            var startTime       = TalkStartTime.Create(DateTime.Today.AddHours(9)).Data; // 9AM

            var conference = Conference.Create(conferenceIdObj).Data;

            conference.AddTrack(trackIdObj);

            // Act
            var addTalkToTrackResult = conference.AddTalkToTrack(trackIdObj, talkIdObj, title, description, duration);

            // Assert
            Assert.IsTrue(addTalkToTrackResult.IsSuccess);
            var talkCreated = conference.Events.OfType <TalkCreated>().FirstOrDefault();

            Assert.IsNotNull(talkCreated);
            Assert.AreEqual(talkIdObj, talkCreated.TalkId);
            Assert.AreEqual(title, talkCreated.Title);
            Assert.AreEqual(description, talkCreated.Description);
            Assert.AreEqual(startTime, talkCreated.StartTime);

            var talkAddedToTrackEvent = conference.Events.OfType <TalkAddedToTrack>().FirstOrDefault();

            Assert.IsNotNull(talkAddedToTrackEvent);
            Assert.AreEqual(trackIdObj, talkAddedToTrackEvent.TrackId);
            Assert.AreEqual(talkIdObj, talkAddedToTrackEvent.TalkId);
            Assert.AreEqual(title, talkAddedToTrackEvent.Title);
        }
Exemple #12
0
        public void GetLatencySampledSpans_MaxSpansToReturn()
        {
            Span span1 = CreateSampledSpan(REGISTERED_SPAN_NAME) as Span;

            testClock.AdvanceTime(Duration.Create(0, 20000)); // 20 microseconds
            span1.End();
            // Advance time to allow other spans to be sampled.
            testClock.AdvanceTime(Duration.Create(5, 0));
            Span span2 = CreateSampledSpan(REGISTERED_SPAN_NAME) as Span;

            testClock.AdvanceTime(Duration.Create(0, 200000)); // 200 microseconds
            span2.End();
            var samples =
                sampleStore.GetLatencySampledSpans(
                    SampledSpanStoreLatencyFilter.Create(
                        REGISTERED_SPAN_NAME,
                        15000,
                        250000,
                        1));

            Assert.Single(samples);
            Assert.Contains(span1.ToSpanData(), samples);
        }
Exemple #13
0
        public void GetLatencySampledSpans_QueryBetweenMultipleBuckets()
        {
            Span span1 = CreateSampledSpan(REGISTERED_SPAN_NAME) as Span;

            testClock.AdvanceTime(Duration.Create(0, 20000)); // 20 microseconds
            span1.End();
            // Advance time to allow other spans to be sampled.
            testClock.AdvanceTime(Duration.Create(5, 0));
            Span span2 = CreateSampledSpan(REGISTERED_SPAN_NAME) as Span;

            testClock.AdvanceTime(Duration.Create(0, 200000)); // 200 microseconds
            span2.End();
            var samples =
                sampleStore.GetLatencySampledSpans(
                    SampledSpanStoreLatencyFilter.Create(
                        REGISTERED_SPAN_NAME,
                        15000,
                        250000,
                        0));

            Assert.Equal(2, samples.Count());
            Assert.Contains(span1.ToSpanData(), samples);
            Assert.Contains(span2.ToSpanData(), samples);
        }
        public void SetUp()
        {
            var project = new Project(new Customer("Ikea"), "X");

            registration = new Registration(Duration.Create("3:00"), "Programming", project);
        }
        public void StartSpanNullParent()
        {
            ISpan span =
                SpanBuilder.CreateWithParent(SPAN_NAME, SpanKind.Internal, null, spanBuilderOptions).StartSpan();

            Assert.True(span.Context.IsValid);
            Assert.True(span.Options.HasFlag(SpanOptions.RecordEvents));
            Assert.True(span.Context.TraceOptions.IsSampled);
            ISpanData spanData = ((Span)span).ToSpanData();

            Assert.Null(spanData.ParentSpanId);
            Assert.False(spanData.HasRemoteParent);
            Assert.InRange(spanData.StartTimestamp, Timestamp.FromDateTimeOffset(DateTimeOffset.Now).AddDuration(Duration.Create(-1, 0)), Timestamp.FromDateTimeOffset(DateTimeOffset.Now).AddDuration(Duration.Create(1, 0)));
            Assert.Equal(SPAN_NAME, spanData.Name);
        }
Exemple #16
0
            public async Task <Result <Module> > Handle(Contract request, CancellationToken cancellationToken)
            {
                try
                {
                    if (request.UserRole == "Student" || request.UserRole == "Recruiter")
                    {
                        return(Result.Fail <Module>("Acesso Negado"));
                    }

                    Duration duration = null;
                    if (request.Duration.HasValue)
                    {
                        var durationResult = Duration.Create(request.Duration.Value);
                        if (durationResult.IsFailure)
                        {
                            return(Result.Fail <Module>(durationResult.Error));
                        }

                        duration = durationResult.Data;
                    }

                    var tags = new List <Tag>();
                    foreach (var tagStr in request.Tags)
                    {
                        var tag = Tag.Create(tagStr);
                        tags.Add(tag.Data);
                    }

                    var tutorsIds = request.TutorsIds != null?request.TutorsIds.Select(x => ObjectId.Parse(x)).ToList() :
                                        new List <ObjectId>();

                    var extraInstructorIds = request.ExtraInstructorIds != null?request.ExtraInstructorIds.Select(x => ObjectId.Parse(x)).ToList() :
                                                 new List <ObjectId>();

                    var module = Module.Create(
                        request.Title, request.Excerpt,
                        request.InstructorId, request.Instructor, request.InstructorMiniBio,
                        request.ImageUrl, request.InstructorImageUrl,
                        request.Published, duration, tags, request.CertificateUrl,
                        tutorsIds, extraInstructorIds, request.StoreUrl
                        );

                    if (module.IsFailure)
                    {
                        return(Result.Fail <Module>(module.Error));
                    }

                    if (request.Subjects != null)
                    {
                        foreach (var csubject in request.Subjects)
                        {
                            var subject = Subject.Create(csubject.Title, csubject.Excerpt, csubject.Concepts);
                            if (subject.IsFailure)
                            {
                                return(Result.Fail <Module>(subject.Error));
                            }

                            module.Data.Subjects.Add(subject.Data);
                            foreach (var ccontent in csubject.Contents)
                            {
                                var content = Content.Create(
                                    ccontent.Title, ccontent.Excerpt,
                                    ccontent.Concepts.Select(x =>
                                                             new ConceptPosition(x, null, null)
                                                             ).ToList(), new string[] { },
                                    ccontent.Link,
                                    ccontent.Type, 0
                                    );

                                if (content.IsFailure)
                                {
                                    return(Result.Fail <Module>(subject.Error));
                                }

                                subject.Data.Contents.Add(content.Data);
                            }
                        }
                    }

                    string config = _configuration[$"EcommerceIntegration:Active"];

                    if (request.CreateInEcommerce.HasValue && request.CreateInEcommerce.Value && config == "True")
                    {
                        var response = await CreateEcommerceProduct(module.Data);

                        string content = await response.Content.ReadAsStringAsync();

                        if (response.StatusCode == HttpStatusCode.Created)
                        {
                            var parsed = JObject.Parse(content);
                            module.Data.EcommerceId = (long)parsed["product"]["id"];
                        }
                        else
                        {
                            var error = ErrorLog.Create(
                                ErrorLogTypeEnum.EcommerceIntegration,
                                "create-module", content
                                ).Data;

                            await _db.ErrorLogCollection.InsertOneAsync(
                                error, cancellationToken : cancellationToken
                                );
                        }
                    }

                    await _db.ModuleCollection.InsertOneAsync(
                        module.Data,
                        cancellationToken : cancellationToken
                        );

                    return(module);
                }
                catch (Exception err)
                {
                    Console.WriteLine(err.Message);
                    throw;
                }
            }
Exemple #17
0
            public async Task <Result <Contract> > Handle(Contract request, CancellationToken cancellationToken)
            {
                if (request.UserRole == "Student" || request.UserRole == "Secretary" || request.UserRole == "Recruiter")
                {
                    return(Result.Fail <Contract>("Acesso Negado"));
                }

                Duration duration = null;

                if (request.Duration.HasValue)
                {
                    var durationResult = Duration.Create(request.Duration.Value);
                    if (durationResult.IsFailure)
                    {
                        return(Result.Fail <Contract>(durationResult.Error));
                    }

                    duration = durationResult.Data;
                }

                Duration videoDuration = null;

                if (request.VideoDuration.HasValue)
                {
                    var durationResult = Duration.Create(request.VideoDuration.Value);
                    if (durationResult.IsFailure)
                    {
                        return(Result.Fail <Contract>(durationResult.Error));
                    }

                    videoDuration = durationResult.Data;
                }

                ObjectId instructorId = String.IsNullOrEmpty(request.InstructorId) ?
                                        ObjectId.Empty : ObjectId.Parse(request.InstructorId);

                var tutorsIds = request.TutorsIds != null?
                                request.TutorsIds.Select(x => ObjectId.Parse(x)).ToList() :
                                    new List <ObjectId>();

                Event dbEvent = null;

                if (!String.IsNullOrEmpty(request.Id))
                {
                    dbEvent = await GetEvent(request.Id);
                }

                if (dbEvent == null)
                {
                    dbEvent = Event.Create(
                        request.Title,
                        request.Excerpt,
                        request.ImageUrl,
                        instructorId,
                        request.Instructor,
                        request.InstructorMiniBio,
                        request.InstructorImageUrl,
                        request.Tags,
                        request.VideoUrl,
                        request.VideoDuration,
                        request.Duration,
                        request.CertificateUrl,
                        tutorsIds,
                        request.StoreUrl
                        ).Data;

                    await _db.EventCollection.InsertOneAsync(
                        dbEvent, cancellationToken : cancellationToken
                        );

                    var newEventList = new List <Event>
                    {
                        dbEvent
                    };

                    var changeLog = AuditLog.Create(ObjectId.Parse(request.UserId), dbEvent.Id, dbEvent.GetType().ToString(),
                                                    JsonConvert.SerializeObject(newEventList), EntityAction.Add, "");

                    await _db.AuditLogCollection.InsertOneAsync(changeLog);
                }

                var newEvent = await CreateEventDraft(request, dbEvent, duration, videoDuration, cancellationToken);

                request.Id = newEvent.Id.ToString();

                return(Result.Ok(request));
            }
        public void StartSpanNullParent()
        {
            var span = new SpanBuilder(SpanName, spanBuilderOptions)
                       .SetSpanKind(SpanKind.Internal)
                       .SetNoParent()
                       .StartSpan();

            Assert.True(span.Context.IsValid);
            Assert.True(span.IsRecordingEvents);
            Assert.True(span.Context.TraceOptions.IsSampled);
            var spanData = ((Span)span).ToSpanData();

            Assert.Null(spanData.ParentSpanId);
            Assert.InRange(spanData.StartTimestamp, Timestamp.FromDateTimeOffset(DateTimeOffset.Now).AddDuration(Duration.Create(-1, 0)), Timestamp.FromDateTimeOffset(DateTimeOffset.Now).AddDuration(Duration.Create(1, 0)));
            Assert.Equal(SpanName, spanData.Name);
        }
Exemple #19
0
        public void When_creating_a_duration_from_colon_string()
        {
            var duration = Duration.Create("0:30");

            duration.Minutes.Should().Be(30);
        }
Exemple #20
0
        public void When_creating_a_duration_from_minutes_string()
        {
            var duration = Duration.Create("30 min");

            duration.Minutes.Should().Be(30);
        }
Exemple #21
0
            public async Task <Result <bool> > Handle(Contract request, CancellationToken cancellationToken)
            {
                if (request.UserRole == "Secretary")
                {
                    return(Result.Fail <bool>("Acesso Negado"));
                }

                var mId    = ObjectId.Parse(request.Id);
                var module = await(await _db
                                   .Database
                                   .GetCollection <Module>("Modules")
                                   .FindAsync(x => x.Id == mId, cancellationToken: cancellationToken))
                             .FirstOrDefaultAsync(cancellationToken: cancellationToken);

                if (module == null)
                {
                    return(Result.Fail <bool>("Módulo não Encontrado"));
                }

                if (request.UserRole == "Student")
                {
                    var userId = ObjectId.Parse(request.UserId);

                    if ((!Module.IsInstructor(module, userId).Data) && !module.TutorsIds.Contains(userId))
                    {
                        return(Result.Fail <bool>("Acesso Negado"));
                    }
                }

                Duration duration = null;

                if (request.Duration.HasValue)
                {
                    var durationResult = Duration.Create(request.Duration.Value);
                    if (durationResult.IsFailure)
                    {
                        return(Result.Fail <bool>(durationResult.Error));
                    }

                    duration = durationResult.Data;
                }

                Duration videoDuration = null;

                if (request.VideoDuration.HasValue)
                {
                    var durationResult = Duration.Create(request.VideoDuration.Value);
                    if (durationResult.IsFailure)
                    {
                        return(Result.Fail <bool>(durationResult.Error));
                    }

                    videoDuration = durationResult.Data;
                }

                if (request.TutorsIds == null)
                {
                    request.TutorsIds = new List <string>();
                }

                if (request.ExtraInstructorIds == null)
                {
                    request.ExtraInstructorIds = new List <string>();
                }

                module.Title              = request.Title;
                module.Excerpt            = request.Excerpt;
                module.InstructorId       = string.IsNullOrEmpty(request.InstructorId) ? ObjectId.Empty : ObjectId.Parse(request.InstructorId);
                module.Instructor         = request.Instructor;
                module.InstructorMiniBio  = request.InstructorMiniBio;
                module.InstructorImageUrl = request.InstructorImageUrl;
                module.ImageUrl           = request.ImageUrl;
                module.VideoUrl           = request.VideoUrl;
                module.VideoDuration      = videoDuration;
                module.Published          = request.Published;
                module.Duration           = duration;
                module.Tags = request.Tags.Select(
                    t => ValueObjects.Tag.Create(t).Data
                    ).ToList();
                module.CertificateUrl     = request.CertificateUrl;
                module.TutorsIds          = request.TutorsIds.Select(x => ObjectId.Parse(x)).ToList();
                module.ExtraInstructorIds = request.ExtraInstructorIds.Select(x => ObjectId.Parse(x)).ToList();
                module.StoreUrl           = request.StoreUrl;
                module.EcommerceId        = request.EcommerceId;
                module.ValidFor           = request.ValidFor;

                await _db.ModuleCollection.ReplaceOneAsync(t =>
                                                           t.Id == module.Id, module,
                                                           cancellationToken : cancellationToken
                                                           );

                if (module.EcommerceId.HasValue)
                {
                    string config = _configuration[$"EcommerceIntegration:Active"];
                    if (config == "True")
                    {
                        await UpdateEcommerceProduct(module);
                    }
                }

                return(Result.Ok(true));
            }
Exemple #22
0
        public void When_creating_a_duration_from_decimal_string()
        {
            var duration = Duration.Create("0.5");

            duration.Minutes.Should().Be(30);
        }
Exemple #23
0
        public void GoSpanData_EndedSpan()
        {
            ISpan span =
                Span.StartSpan(
                    spanContext,
                    recordSpanOptions,
                    SPAN_NAME,
                    parentSpanId,
                    false,
                    TraceParams.DEFAULT,
                    startEndHandler,
                    timestampConverter,
                    testClock);

            span.PutAttribute(
                "MySingleStringAttributeKey",
                AttributeValue.StringAttributeValue("MySingleStringAttributeValue"));
            span.PutAttributes(attributes);
            testClock.AdvanceTime(Duration.Create(0, 100));
            span.AddAnnotation(Annotation.FromDescription(ANNOTATION_DESCRIPTION));
            testClock.AdvanceTime(Duration.Create(0, 100));
            span.AddAnnotation(ANNOTATION_DESCRIPTION, attributes);
            testClock.AdvanceTime(Duration.Create(0, 100));
            IMessageEvent networkEvent =
                MessageEvent.Builder(MessageEventType.RECEIVED, 1).SetUncompressedMessageSize(3).Build();

            span.AddMessageEvent(networkEvent);
            ILink link = Link.FromSpanContext(spanContext, LinkType.CHILD_LINKED_SPAN);

            span.AddLink(link);
            testClock.AdvanceTime(Duration.Create(0, 100));
            span.End(EndSpanOptions.Builder().SetStatus(Status.CANCELLED).Build());

            ISpanData spanData = ((Span)span).ToSpanData();

            Assert.Equal(spanContext, spanData.Context);
            Assert.Equal(SPAN_NAME, spanData.Name);
            Assert.Equal(parentSpanId, spanData.ParentSpanId);
            Assert.False(spanData.HasRemoteParent);
            Assert.Equal(0, spanData.Attributes.DroppedAttributesCount);
            Assert.Equal(expectedAttributes, spanData.Attributes.AttributeMap);
            Assert.Equal(0, spanData.Annotations.DroppedEventsCount);
            Assert.Equal(2, spanData.Annotations.Events.Count);
            Assert.Equal(timestamp.AddNanos(100), spanData.Annotations.Events[0].Timestamp);
            Assert.Equal(Annotation.FromDescription(ANNOTATION_DESCRIPTION), spanData.Annotations.Events[0].Event);
            Assert.Equal(timestamp.AddNanos(200), spanData.Annotations.Events[1].Timestamp);
            Assert.Equal(Annotation.FromDescriptionAndAttributes(ANNOTATION_DESCRIPTION, attributes), spanData.Annotations.Events[1].Event);
            Assert.Equal(0, spanData.MessageEvents.DroppedEventsCount);
            Assert.Equal(1, spanData.MessageEvents.Events.Count);
            Assert.Equal(timestamp.AddNanos(300), spanData.MessageEvents.Events[0].Timestamp);
            Assert.Equal(networkEvent, spanData.MessageEvents.Events[0].Event);
            Assert.Equal(0, spanData.Links.DroppedLinksCount);
            Assert.Equal(1, spanData.Links.Links.Count);
            Assert.Equal(link, spanData.Links.Links[0]);
            Assert.Equal(timestamp, spanData.StartTimestamp);
            Assert.Equal(Status.CANCELLED, spanData.Status);
            Assert.Equal(timestamp.AddNanos(400), spanData.EndTimestamp);

            var startEndMock = Mock.Get <IStartEndHandler>(startEndHandler);
            var spanBase     = span as SpanBase;

            startEndMock.Verify(s => s.OnStart(spanBase), Times.Once);
            startEndMock.Verify(s => s.OnEnd(spanBase), Times.Once);
        }
Exemple #24
0
            public async Task <Result <Contract> > Handle(Contract request, CancellationToken cancellationToken)
            {
                if (request.UserRole == "Secretary")
                {
                    return(Result.Fail <Contract>("Acesso Negado"));
                }

                var evId = ObjectId.Parse(request.Id);

                var dbEvent = await _db.EventDraftCollection.AsQueryable()
                              .Where(x => (
                                         x.DeletedAt == null || x.DeletedAt == DateTimeOffset.MinValue
                                         ) && !x.DraftPublished && (
                                         x.Id == evId || x.EventId == evId
                                         )
                                     )
                              .FirstOrDefaultAsync(cancellationToken: cancellationToken);

                Duration duration = null;

                if (request.Duration.HasValue)
                {
                    var durationResult = Duration.Create(request.Duration.Value);
                    if (durationResult.IsFailure)
                    {
                        return(Result.Fail <Contract>(durationResult.Error));
                    }

                    duration = durationResult.Data;
                }

                Duration videoDuration = null;

                if (request.VideoDuration.HasValue)
                {
                    var durationResult = Duration.Create(request.VideoDuration.Value);
                    if (durationResult.IsFailure)
                    {
                        return(Result.Fail <Contract>(durationResult.Error));
                    }

                    videoDuration = durationResult.Data;
                }

                ObjectId instructorId = String.IsNullOrEmpty(request.InstructorId) ?
                                        ObjectId.Empty : ObjectId.Parse(request.InstructorId);

                var tutorsIds = request.TutorsIds != null?
                                request.TutorsIds.Select(x => ObjectId.Parse(x)).ToList() :
                                    new List <ObjectId>();

                var eventResult = Event.Create(
                    request.Title,
                    request.Excerpt,
                    request.ImageUrl,
                    instructorId,
                    request.Instructor,
                    request.InstructorMiniBio,
                    request.InstructorImageUrl,
                    request.Tags,
                    request.VideoUrl,
                    request.VideoDuration,
                    request.Duration,
                    request.CertificateUrl,
                    tutorsIds,
                    request.StoreUrl,
                    request.ForceProblemStatement
                    );

                if (eventResult.IsFailure)
                {
                    return(Result.Fail <Contract>(eventResult.Error));
                }

                var newEvent = eventResult.Data;

                newEvent.PrepQuizQuestionList = new List <PrepQuizQuestion>();

                if (request.PrepQuizQuestionList != null && request.PrepQuizQuestionList.Count > 0)
                {
                    var questions = request.PrepQuizQuestionList.Select(x => x.Question).ToArray();

                    for (int i = 0; i < request.PrepQuizQuestionList.Count; i++)
                    {
                        var prepQuizResult = PrepQuizQuestion.Create(request.PrepQuizQuestionList[i].Question, request.PrepQuizQuestionList[i].FileAsAnswer, questions);
                        if (prepQuizResult.IsFailure)
                        {
                            return(Result.Fail <Contract>(prepQuizResult.Error));
                        }
                        newEvent.PrepQuizQuestionList.Add(prepQuizResult.Data);
                    }
                }

                var oldEventList = JsonConvert.SerializeObject(new List <EventDraft>
                {
                    dbEvent
                });

                if (dbEvent == null)
                {
                    var originalEvent = await GetEvent(request.Id);

                    if (originalEvent == null)
                    {
                        return(Result.Fail <Contract>("Evento não existe"));
                    }

                    dbEvent = await CreateEventDraft(
                        request, originalEvent, duration, videoDuration, cancellationToken
                        );
                }
                else
                {
                    dbEvent.Title              = newEvent.Title;
                    dbEvent.Excerpt            = newEvent.Excerpt;
                    dbEvent.ImageUrl           = newEvent.ImageUrl;
                    dbEvent.InstructorId       = newEvent.InstructorId;
                    dbEvent.Instructor         = newEvent.Instructor;
                    dbEvent.InstructorMiniBio  = newEvent.InstructorMiniBio;
                    dbEvent.InstructorImageUrl = newEvent.InstructorImageUrl;
                    dbEvent.Tags                  = newEvent.Tags;
                    dbEvent.VideoUrl              = newEvent.VideoUrl;
                    dbEvent.VideoDuration         = newEvent.VideoDuration;
                    dbEvent.Duration              = newEvent.Duration;
                    dbEvent.PrepQuiz              = newEvent.PrepQuiz;
                    dbEvent.CertificateUrl        = newEvent.CertificateUrl;
                    dbEvent.TutorsIds             = newEvent.TutorsIds;
                    dbEvent.StoreUrl              = newEvent.StoreUrl;
                    dbEvent.CreateInEcommerce     = request.CreateInEcommerce.HasValue ? request.CreateInEcommerce.Value : false;
                    dbEvent.EcommerceId           = request.EcommerceId;
                    dbEvent.ForceProblemStatement = request.ForceProblemStatement;
                    dbEvent.PrepQuizQuestionList  = newEvent.PrepQuizQuestionList;

                    await _db.EventDraftCollection.ReplaceOneAsync(t =>
                                                                   t.Id == dbEvent.Id, dbEvent,
                                                                   cancellationToken : cancellationToken
                                                                   );

                    var newEventList = new List <EventDraft>
                    {
                        dbEvent
                    };

                    var changeLog = AuditLog.Create(ObjectId.Parse(request.UserId), dbEvent.Id, dbEvent.GetType().ToString(),
                                                    JsonConvert.SerializeObject(newEventList), EntityAction.Update, oldEventList);

                    await _db.AuditLogCollection.InsertOneAsync(changeLog);
                }

                return(Result.Ok(request));
            }
Exemple #25
0
            public async Task<Result> Handle(Contract request, CancellationToken cancellationToken)
            {
                if (request.UserRole != "Admin" && request.UserRole != "Author")
                    return Result.Fail("Acesso Negado");

                var userId = ObjectId.Parse(request.UserId);
                var modId = ObjectId.Parse(request.Id);

                var module = await _db.ModuleDraftCollection.AsQueryable()
                    .Where(x => (
                            x.DeletedAt == null || x.DeletedAt == DateTimeOffset.MinValue
                        ) && !x.DraftPublished && (
                            x.Id == modId || x.ModuleId == modId
                        )
                    )
                    .FirstOrDefaultAsync(cancellationToken: cancellationToken);


                if (request.UserRole == "Author" && module.CreatedBy != userId)
                    return Result.Fail("Você não tem permissão para alterar o módulo selecionado.");

                Duration duration = null;
                if (request.Duration.HasValue)
                {
                    var durationResult = Duration.Create(request.Duration.Value);
                    if (durationResult.IsFailure)
                        return Result.Fail(durationResult.Error);

                    duration = durationResult.Data;
                }

                Duration videoDuration = null;
                if (request.VideoDuration.HasValue)
                {
                    var durationResult = Duration.Create(request.VideoDuration.Value);
                    if (durationResult.IsFailure)
                        return Result.Fail(durationResult.Error);

                    videoDuration = durationResult.Data;
                }

                if (request.TutorsIds == null)
                    request.TutorsIds = new List<string>();

                if (request.ExtraInstructorIds == null)
                    request.ExtraInstructorIds = new List<string>();

                if (module == null)
                {
                    var originalModule = await GetModule(request.Id);
                    if (originalModule == null)
                        return Result.Fail("Módulo não existe");

                    module = await CreateModuleDraft(userId, request, originalModule, 
                        duration, videoDuration, cancellationToken
                    );
                }
                else
                {
                    var oldValues = JsonConvert.SerializeObject(new List<ModuleDraft>
                    {
                        module
                    });

                    module.Title = request.Title;
                    module.Excerpt = request.Excerpt;
                    module.InstructorId = string.IsNullOrEmpty(request.InstructorId) ? ObjectId.Empty : ObjectId.Parse(request.InstructorId);
                    module.Instructor = request.Instructor;
                    module.InstructorMiniBio = request.InstructorMiniBio;
                    module.InstructorImageUrl = request.InstructorImageUrl;
                    module.ImageUrl = request.ImageUrl;
                    module.VideoUrl = request.VideoUrl;
                    module.VideoDuration = videoDuration;
                    module.Published = request.Published;
                    module.Duration = duration;
                    module.Tags = request.Tags.Select(
                        t => Tag.Create(t).Data
                    ).ToList();
                    module.CertificateUrl = request.CertificateUrl;
                    module.TutorsIds = request.TutorsIds.Select(x => ObjectId.Parse(x)).ToList();
                    module.ExtraInstructorIds = request.ExtraInstructorIds.Select(x => ObjectId.Parse(x)).ToList();
                    module.StoreUrl = request.StoreUrl;
                    module.EcommerceUrl = request.EcommerceUrl;
                    module.CreateInEcommerce = request.CreateInEcommerce.HasValue ? request.CreateInEcommerce.Value : false;
                    module.EcommerceId = request.EcommerceId;
                    module.ModuleGradeType = request.ModuleGradeType;
                    module.ValidFor = request.ValidFor;

                    await _db.ModuleDraftCollection.ReplaceOneAsync(t =>
                        t.Id == module.Id, module,
                        cancellationToken: cancellationToken
                    );

                    var newDraftList = new List<ModuleDraft>
                    {
                        module
                    };

                    var changeLog = AuditLog.Create(userId, module.Id, module.GetType().ToString(),
                    JsonConvert.SerializeObject(newDraftList), EntityAction.Update, oldValues);

                    await _db.AuditLogCollection.InsertOneAsync(changeLog);

                }

                return Result.Ok();
            }
Exemple #26
0
        public static Result <Event> Create(
            string title, string excerpt, string imageUrl,
            ObjectId instructorId, string instructor, string instructorMiniBio, string instructorImageUrl,
            string[] tags, string videoUrl, int?videoDuration, int?duration,
            string certificateUrl, List <ObjectId> tutorsIds, string storeUrl = "", bool?forceProblemStatement = false
            )
        {
            if (title.Length > 200)
            {
                return(Result.Fail <Event>($"Tamanho máximo do título do evento é de 200 caracteres. ({title})"));
            }

            Duration videoDurationObj = null;

            if (videoDuration.HasValue)
            {
                var result = Duration.Create(videoDuration.Value);
                if (result.IsFailure)
                {
                    return(Result.Fail <Event>(result.Error));
                }
                videoDurationObj = result.Data;
            }

            Duration durationObj = null;

            if (duration.HasValue)
            {
                var result = Duration.Create(duration.Value);
                if (result.IsFailure)
                {
                    return(Result.Fail <Event>(result.Error));
                }
                durationObj = result.Data;
            }

            var tagResults      = tags.Select(Tag.Create).ToArray();
            var combinedResults = Result.Combine(tagResults);

            if (combinedResults.IsFailure)
            {
                return(Result.Fail <Event>(combinedResults.Error));
            }

            if (tags
                .GroupBy(x => x)
                .Select(x => new { x.Key, count = x.Count() })
                .Any(x => x.count > 1))
            {
                return(Result.Fail <Event>("Não podem haver tags repetidos"));
            }

            var newObj = new Event(
                title, excerpt, imageUrl,
                instructorId, instructor, instructorMiniBio, instructorImageUrl,
                tagResults.Select(x => x.Data).ToList(),
                videoUrl, videoDurationObj, durationObj,
                certificateUrl, tutorsIds, storeUrl, forceProblemStatement
                );

            return(Result.Ok(newObj));
        }
Exemple #27
0
        public void ToSpanData_ActiveSpan()
        {
            ISpan span =
                Span.StartSpan(
                    spanContext,
                    recordSpanOptions,
                    SPAN_NAME,
                    parentSpanId,
                    true,
                    TraceParams.Default,
                    startEndHandler,
                    timestampConverter,
                    testClock);

            span.PutAttribute(
                "MySingleStringAttributeKey",
                AttributeValue.StringAttributeValue("MySingleStringAttributeValue"));
            span.PutAttributes(attributes);
            testClock.AdvanceTime(Duration.Create(0, 100));
            span.AddAnnotation(Annotation.FromDescription(ANNOTATION_DESCRIPTION));
            testClock.AdvanceTime(Duration.Create(0, 100));
            span.AddAnnotation(ANNOTATION_DESCRIPTION, attributes);
            testClock.AdvanceTime(Duration.Create(0, 100));
            IMessageEvent networkEvent =
                MessageEvent.Builder(MessageEventType.Received, 1).SetUncompressedMessageSize(3).Build();

            span.AddMessageEvent(networkEvent);
            testClock.AdvanceTime(Duration.Create(0, 100));
            ILink link = Link.FromSpanContext(spanContext, LinkType.ChildLinkedSpan);

            span.AddLink(link);
            ISpanData spanData = ((Span)span).ToSpanData();

            Assert.Equal(spanContext, spanData.Context);
            Assert.Equal(SPAN_NAME, spanData.Name);
            Assert.Equal(parentSpanId, spanData.ParentSpanId);
            Assert.True(spanData.HasRemoteParent);
            Assert.Equal(0, spanData.Attributes.DroppedAttributesCount);
            Assert.Equal(expectedAttributes, spanData.Attributes.AttributeMap);
            Assert.Equal(0, spanData.Annotations.DroppedEventsCount);
            Assert.Equal(2, spanData.Annotations.Events.Count());
            Assert.Equal(timestamp.AddNanos(100), spanData.Annotations.Events.ToList()[0].Timestamp);
            Assert.Equal(Annotation.FromDescription(ANNOTATION_DESCRIPTION), spanData.Annotations.Events.ToList()[0].Event);
            Assert.Equal(timestamp.AddNanos(200), spanData.Annotations.Events.ToList()[1].Timestamp);
            Assert.Equal(Annotation.FromDescriptionAndAttributes(ANNOTATION_DESCRIPTION, attributes), spanData.Annotations.Events.ToList()[1].Event);
            Assert.Equal(0, spanData.MessageEvents.DroppedEventsCount);
            Assert.Single(spanData.MessageEvents.Events);
            Assert.Equal(timestamp.AddNanos(300), spanData.MessageEvents.Events.First().Timestamp);
            Assert.Equal(networkEvent, spanData.MessageEvents.Events.First().Event);
            Assert.Equal(0, spanData.Links.DroppedLinksCount);
            Assert.Single(spanData.Links.Links);
            Assert.Equal(link, spanData.Links.Links.First());
            Assert.Equal(timestamp, spanData.StartTimestamp);
            Assert.Null(spanData.Status);
            Assert.Null(spanData.EndTimestamp);

            var startEndMock = Mock.Get <IStartEndHandler>(startEndHandler);
            var spanBase     = span as SpanBase;

            startEndMock.Verify(s => s.OnStart(spanBase), Times.Once);
        }