public async Task <IActionResult> GetProfile(
            [BindRequired, FromQuery] string profileId,
            [BindRequired, FromQuery] Iri activityId,
            [FromQuery] Guid?registration = null,
            CancellationToken cancelToken = default)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var profile = await _mediator.Send(new GetActivityProfileQuery()
            {
                ProfileId    = profileId,
                ActivityId   = activityId,
                Registration = registration
            }, cancelToken);

            if (profile == null)
            {
                return(NotFound());
            }

            var result = new FileContentResult(profile.Document.Content, profile.Document.ContentType)
            {
                EntityTag    = new EntityTagHeaderValue($"\"{profile.Document.Checksum}\""),
                LastModified = profile.Document.LastModified
            };

            return(result);
        }
        private byte[] SimpleHash(Triple t)
        {
            ISubject subject;

            if (t.Subject.IsBlankNode())
            {
                subject = new BlankNode("Magic_S");
            }
            else
            {
                subject = new Iri(t.Subject.AsIri().ValueAsString());
            }
            IObject object_;

            if (t.Object.IsBlankNode())
            {
                object_ = new BlankNode("Magic_O");
            }
            else
            {
                object_ = new Iri(t.Object.AsIri().ValueAsString());
            }
            IPredicate predicate = new Iri(t.Predicate.AsIri().ValueAsString());
            var        nTriple   = _nTriplesFormatHandler.SerializeTriple(new Triple(subject, predicate, object_));

            return(_hashCalculator.CalculateHashAsBytes(nTriple));
        }
        public async Task <IActionResult> DeleteProfileAsync(
            [BindRequired, FromQuery] string profileId,
            [BindRequired, FromQuery] Iri activityId,
            [FromQuery] Guid?registration = null,
            CancellationToken cancelToken = default)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var profile = await _mediator.Send(
                GetActivityProfileQuery.Create(activityId, profileId, registration),
                cancelToken);

            if (profile == null)
            {
                return(NotFound());
            }

            if (Request.TryConcurrencyCheck(profile.Document.Checksum, profile.Document.LastModified, out int statusCode))
            {
                return(StatusCode(statusCode));
            }

            await _mediator.Send(DeleteActivityProfileCommand.Create(
                                     profileId, activityId, registration), cancelToken);

            return(NoContent());
        }
Beispiel #4
0
        private static async Task WriteGraph(JsonWriter jsonWriter, Iri graph, IEnumerable <Statement> statements)
        {
            await jsonWriter.WriteStartObjectAsync();

            await jsonWriter.WritePropertyNameAsync("@id");

            await jsonWriter.WriteValueAsync(graph != null?(string)graph : "@default");

            await jsonWriter.WritePropertyNameAsync("@graph");

            await jsonWriter.WriteStartArrayAsync();

            var subjects = statements.GroupBy(statement => statement.Subject).ToList();

            for (var index = 0; index < subjects.Count; index++)
            {
                var subject = subjects[index];
                await WriteSubject(jsonWriter, subject.Key, subject, subjects);

                if ((index < subjects.Count) && (subject != subjects[index]))
                {
                    index--;
                }
            }

            await jsonWriter.WriteEndArrayAsync();

            await jsonWriter.WriteEndObjectAsync();
        }
Beispiel #5
0
        /// <summary>Obtains a type of the link of the given <paramref name="entity" />.</summary>
        /// <param name="entity">Entity for which to obtain a link type.</param>
        /// <param name="linksPolicy">Links policy etermining how far a relation should be considered a link.</param>
        /// <param name="root">Root Iri to be used when resolving some of the policies.</param>
        /// <returns>Determined link type Iri.</returns>
        public static Iri GetLinkType(this IEntity entity, LinksPolicy linksPolicy, Iri root)
        {
            Iri result = null;

            if (entity != null)
            {
                result = entity.GetTypes().Any(_ => _ == hydra.IriTemplate) ? hydra.TemplatedLink : null;
                if (result == null && !entity.Iri.IsBlank)
                {
                    if (linksPolicy >= LinksPolicy.SameRoot &&
                        root != null &&
                        entity.Iri != root &&
                        entity.Iri.ToRoot() == root)
                    {
                        result = hydra.Link;
                    }

                    if (result == null && linksPolicy >= LinksPolicy.AllHttp && entity.Iri.IsHttp())
                    {
                        result = hydra.Link;
                    }

                    if (result == null && linksPolicy >= LinksPolicy.All)
                    {
                        result = hydra.Link;
                    }
                }
            }

            return(result);
        }
Beispiel #6
0
        /// <inheritdoc />
        public override Statement ConvertTo(Iri subject, Iri predicate, object value, Iri graph = null)
        {
            DateTime dateTime = (DateTime)value;
            string   literalValue;
            Iri      dataType;

            if ((dateTime.Year == default(DateTime).Year) && (dateTime.Month == default(DateTime).Month) && (dateTime.Day == default(DateTime).Day))
            {
                literalValue = XmlConvert.ToString((DateTime)value, XmlDateTimeSerializationMode.RoundtripKind).Substring(11);
                dataType     = xsd.time;
            }
            else if ((dateTime.Hour == default(DateTime).Hour) && (dateTime.Minute == default(DateTime).Minute) &&
                     (dateTime.Second == default(DateTime).Second) && (dateTime.Millisecond == default(DateTime).Millisecond))
            {
                literalValue = XmlConvert.ToString((DateTime)value, XmlDateTimeSerializationMode.Utc).Substring(0, 10);
                dataType     = xsd.date;
            }
            else
            {
                literalValue = XmlConvert.ToString((DateTime)value, XmlDateTimeSerializationMode.RoundtripKind);
                dataType     = xsd.dateTime;
            }

            return(new Statement(subject, predicate, literalValue, dataType, graph));
        }
        public IHttpActionResult GetActivity(
            [FromUri] Iri activityId = null)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            if (activityId == null)
            {
                return(BadRequest("ActivityId parameter required."));
            }
            var activity = activityRepository.GetActivity(activityId);

            if (activity == null)
            {
                return(Ok(new Activity()));
            }


            ResultFormat format = ResultFormat.Exact;

            if (this.Request.Headers.AcceptLanguage != null && this.Request.Headers.AcceptLanguage.Count > 0)
            {
                format = ResultFormat.Canonical;
            }
            var req = activity.ToJson(format);
            HttpResponseMessage msg = new HttpResponseMessage()
            {
                Content = new StringContent(req, System.Text.Encoding.UTF8, "application/json")
            };

            return(ResponseMessage(msg));
        }
 public static GetActivityQuery Create(Iri activityId)
 {
     return(new GetActivityQuery()
     {
         ActivityId = activityId
     });
 }
Beispiel #9
0
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof(Iri))
            {
                return(false);
            }
            var modelName           = bindingContext.ModelName;
            var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);

            if (valueProviderResult == null)
            {
                return(false);
            }
            //set the string you receive it inside the modelstate so you can retrieve it in the controller to display error (xoxoxo : )
            bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);
            var val = valueProviderResult.RawValue as string;

            if (Iri.TryParse(val, out Iri iri))
            {
                bindingContext.Model = iri;
                return(true);
            }
            else
            {
                bindingContext.ModelState.AddModelError(
                    bindingContext.ModelName, $"Please provide a valid iri: '{val}' is an invalid IRI.");
                return(false);
            }
            return(false);
        }
Beispiel #10
0
        public async Task HandleContext(StatementBase statement, IStatementBaseEntity newStatement, CancellationToken cancellationToken)
        {
            if (statement.Context != null)
            {
                newStatement.Context = _mapper.Map <ContextEntity>(statement.Context);
                ContextEntity context = newStatement.Context;
                if (context.Instructor != null)
                {
                    var instructor = (AgentEntity)await _mediator.Send(UpsertActorCommand.Create(statement.Context.Instructor), cancellationToken);

                    context.InstructorId = instructor.AgentId;
                    context.Instructor   = null;
                }
                if (context.Team != null)
                {
                    var team = (AgentEntity)await _mediator.Send(UpsertActorCommand.Create(statement.Context.Team), cancellationToken);

                    context.TeamId = team.AgentId;
                    context.Team   = null;
                }

                if (context.ContextActivities != null)
                {
                    foreach (var contextActivity in context.ContextActivities)
                    {
                        Iri id       = new Iri(contextActivity.Activity.Id);
                        var activity = await _mediator.Send(UpsertActivityCommand.Create(id), cancellationToken);

                        contextActivity.Activity   = null;
                        contextActivity.ActivityId = activity.ActivityId;
                    }
                }
            }
        }
Beispiel #11
0
        public async Task <MultipleDocumentResult> GetActivityStates(Iri activityId, Agent agent, Guid?registration, DateTimeOffset?since = null, CancellationToken cancellationToken = default)
        {
            AgentEntity savedAgent = await mediator.Send(GetAgentQuery.Create(agent), cancellationToken);

            if (savedAgent == null)
            {
                return(MultipleDocumentResult.Empty());
            }

            var states = await mediator.Send(new GetActivityStatesQuery()
            {
                ActivityId   = activityId,
                AgentId      = savedAgent.AgentId,
                Registration = registration,
                Since        = since
            }, cancellationToken);

            if (!states.Any())
            {
                return(MultipleDocumentResult.Empty());
            }

            var keys         = states.Select(x => x.Key).ToHashSet();
            var lastModified = states.OrderByDescending(x => x.UpdatedAt)
                               .Select(x => x.UpdatedAt)
                               .FirstOrDefault();

            return(MultipleDocumentResult.Success(keys, lastModified));
        }
Beispiel #12
0
        /// <inheritdoc/>
        public async Task <MultipleDocumentResult> GetActivityProfiles(Iri activityId, DateTimeOffset?since = null, CancellationToken cancellationToken = default)
        {
            var activity = await mediator.Send(GetActivityQuery.Create(activityId), cancellationToken);

            if (activity == null)
            {
                return(MultipleDocumentResult.Empty());
            }

            var documents = await mediator.Send(new GetActivityProfilesQuery()
            {
                ActivityId = activityId,
                Since      = since
            }, cancellationToken);

            if (!documents.Any())
            {
                return(MultipleDocumentResult.Empty());
            }

            var ids          = documents.Select(x => x.Key).ToHashSet();
            var lastModified = documents
                               .OrderByDescending(x => x.UpdatedAt)
                               .Select(x => x.UpdatedAt)
                               .FirstOrDefault();

            return(MultipleDocumentResult.Success(ids, lastModified));
        }
        /// <summary>
        /// Fetches State ids of all state data for this context (Activity + Agent [ + registration if specified]). If "since" parameter is specified, this is limited to entries that have been stored or updated since the specified timestamp (exclusive).
        /// </summary>
        /// <param name="activityId"></param>
        /// <param name="strAgent"></param>
        /// <param name="stateId"></param>
        /// <param name="registration"></param>
        /// <returns></returns>
        private async Task <IActionResult> GetMutipleStates(
            Iri activityId,
            Guid agentId,
            Guid?registration = null,
            DateTime?since    = null,
            CancellationToken cancellationToken = default)
        {
            ICollection <ActivityStateDocument> states = await _mediator.Send(new GetActivityStatesQuery()
            {
                ActivityId   = activityId,
                AgentId      = agentId,
                Registration = registration,
                Since        = since
            }, cancellationToken);

            if (states.Count <= 0)
            {
                return(Ok(Array.Empty <string>()));
            }

            IEnumerable <string> ids = states.Select(x => x.StateId);
            string lastModified      = states.OrderByDescending(x => x.LastModified)
                                       .FirstOrDefault()?.LastModified?.ToString("o");

            Response.Headers.Add("LastModified", lastModified);

            return(Ok(ids));
        }
Beispiel #14
0
 internal AttributeTermMappingProvider(Type entityType, string prefix, string term, Iri graph = null)
 {
     EntityType = entityType;
     Prefix     = prefix;
     Term       = term;
     Graph      = graph;
 }
        /// <inheritdoc />
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (value == null)
            {
                return(null);
            }

            if (destinationType == typeof(string))
            {
                return(value.ToString());
            }

            if (destinationType == typeof(Uri))
            {
                Iri iriValue = value as Iri;
                if (iriValue == null)
                {
                    return(null);
                }

                if (iriValue.Uri != null)
                {
                    return(iriValue.Uri);
                }

                return(new Uri(value.ToString(), UriKind.RelativeOrAbsolute));
            }

            return(base.ConvertTo(context, culture, value, destinationType));
        }
Beispiel #16
0
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var modelName = bindingContext.ModelName;

            var valueProviderResult =
                bindingContext.ValueProvider.GetValue(modelName);

            if (valueProviderResult == ValueProviderResult.None)
            {
                return(Task.CompletedTask);
            }

            bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);

            if (Iri.TryParse(valueProviderResult.FirstValue, out Iri iri))
            {
                bindingContext.Result = ModelBindingResult.Success(iri);
            }
            else
            {
                bindingContext.Result = ModelBindingResult.Failed();
            }

            return(Task.CompletedTask);
        }
        private IEntityMapping CreateEntityMapping <TEntity>(Iri @class = null)
        {
            var entityMapping = new Mock <IEntityMapping>(MockBehavior.Strict);

            entityMapping.SetupGet(instance => instance.Type).Returns(typeof(TEntity));
            if (@class != null)
            {
                var typeMapping = new Mock <IStatementMapping>(MockBehavior.Strict);
                typeMapping.SetupGet(instance => instance.Term).Returns(@class);
                typeMapping.SetupGet(instance => instance.Graph).Returns((Iri)null);
                entityMapping.SetupGet(instance => instance.Classes).Returns(new[] { typeMapping.Object });
            }
            else
            {
                entityMapping.SetupGet(instance => instance.Classes).Returns(Array.Empty <IStatementMapping>());
            }

            var propertyMapping = new Mock <IPropertyMapping>(MockBehavior.Strict);

            propertyMapping.SetupGet(instance => instance.Name).Returns(ExpectedProperty);
            propertyMapping.SetupGet(instance => instance.Term).Returns(new Iri(ExpectedProperty));
            propertyMapping.SetupGet(instance => instance.Graph).Returns((Iri)null);
            entityMapping.SetupGet(instance => instance.Properties).Returns(new[] { propertyMapping.Object });
            return(entityMapping.Object);
        }
        public async Task <ActionResult <string[]> > GetProfiles(Iri activityId, DateTimeOffset?since = null)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            ICollection <ActivityProfileDocument> profiles = await _mediator.Send(new GetActivityProfilesQuery()
            {
                ActivityId = activityId,
                Since      = since
            });

            if (profiles == null)
            {
                return(Ok(new string[0]));
            }

            IEnumerable <string> ids = profiles.Select(x => x.ProfileId);
            string lastModified      = profiles.OrderByDescending(x => x.LastModified)
                                       .FirstOrDefault()?
                                       .LastModified?.ToString("o");

            Response.Headers.Add("LastModified", lastModified);
            return(Ok(ids));
        }
Beispiel #19
0
        public int CreateActivity(Iri activity)
        {
            int index = -1;

            using (SqlConnection connection = new SqlConnection(DbUtils.GetConnectionString()))
            {
                // get activity
                SqlDataReader reader = null;
                try
                {
                    connection.Open();
                    // Create the activity
                    SqlCommand command = new SqlCommand(CreateActivityQuery, connection);
                    command.Parameters.AddWithValue("@activity_id", activity._iriString);
                    reader = command.ExecuteReader();
                    if (reader.Read())
                    {
                        index = reader.GetInt32(0);
                    }
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    if (reader != null && !reader.IsClosed)
                    {
                        reader.Close();
                    }
                }
            }
            return(index);
        }
        public async Task <IActionResult> DeleteProfileAsync(string profileId, Iri activityId, Guid?registration = null)
        {
            try
            {
                ActivityProfileDocument profile = await _mediator.Send(new GetActivityProfileQuery()
                {
                    ProfileId    = profileId,
                    ActivityId   = activityId,
                    Registration = registration
                });

                if (profile == null)
                {
                    return(NotFound());
                }

                await _mediator.Send(new DeleteActivityProfileCommand()
                {
                    ProfileId    = profileId,
                    ActivityId   = activityId,
                    Registration = registration
                });

                return(NoContent());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex));
            }
        }
        public IHttpActionResult DeleteProfile(
            Iri activityId   = null,
            string profileId = null)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            if (activityId == null)
            {
                return(BadRequest("ActivityId parameter needs to be provided."));
            }
            if (profileId == null)
            {
                return(BadRequest("ProfileId parameter needs to be provided."));
            }
            ActivityProfileDocument profile = activityProfileRepository.GetProfile(activityId, profileId);

            if (profile == null)
            {
                return(StatusCode(HttpStatusCode.NoContent));
            }
            else
            {
                if (this.ActionContext.TryConcurrencyCheck(profile.Checksum, profile.LastModified, out var statusCode))
                {
                    return(StatusCode(statusCode));
                }
            }
            activityProfileRepository.DeleteProfile(profile);
            return(StatusCode(HttpStatusCode.NoContent));
        }
        public IHttpActionResult GetProfiles(
            Iri activityId       = null,
            string profileId     = null,
            DateTimeOffset?since = null)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            if (activityId == null)
            {
                return(BadRequest("ActivityId parameter needs to be provided."));
            }

            if (profileId != null)
            {
                ActivityProfileDocument profile = activityProfileRepository.GetProfile(activityId, profileId);
                if (profile == null)
                {
                    return(NotFound());
                }
                return(new DocumentResult(profile));
            }

            // otherwise we return the array of profileId's associated with that activity
            Object[] profiles = activityProfileRepository.GetProfiles(activityId, since);
            if (profiles == null)
            {
                return(Ok(new string[0]));
            }

            return(new DocumentsResult(profiles));
        }
        private T Create <T>(Iri iri)
        {
            var result = new MulticastObject();

            result.SetProperty(typeof(IEntity).GetProperty(nameof(IEntity.Iri)), iri);
            return(result.ActLike <T>());
        }
Beispiel #24
0
        private static async Task ReadPredicate(XmlReader reader, Iri subject, ICollection <Statement> statements, IDictionary <string, Iri> blankNodes)
        {
            bool   isEmptyElement = reader.IsEmptyElement;
            Iri    predicate      = new Iri(reader.NamespaceURI + reader.LocalName);
            Iri    @object;
            string value;
            string language;
            Iri    datatype;

            ReadAttributes(reader, blankNodes, out @object, out value, out datatype, out language);
            if (isEmptyElement)
            {
                statements.Add(CreateStatement(subject, predicate, @object, value, datatype, language));
                return;
            }

            while (await reader.ReadAsync())
            {
                switch (reader.NodeType)
                {
                case XmlNodeType.Text:
                    value = reader.Value;
                    break;

                case XmlNodeType.EndElement:
                    statements.Add(CreateStatement(subject, predicate, @object, value, datatype, language));
                    return;
                }
            }
        }
        public static DoctrinaDbContext Create()
        {
            var options = new DbContextOptionsBuilder <DoctrinaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var context = new DoctrinaDbContext(options);

            context.Database.EnsureCreated();

            var activityId = new Iri("http://www.example.com/activityId/hashset");

            context.Activities.Add(new ActivityEntity()
            {
                Id   = activityId.ToString(),
                Hash = activityId.ComputeHash()
            });

            context.Agents.AddRange(new AgentEntity[] {
                AgentsTestFixture.JamesCampbell(),
                AgentsTestFixture.JosephinaCampbell()
            });

            context.SaveChanges();

            return(context);
        }
 private void Assert(Iri owner, Statement statement, StatementEventArgs e)
 {
     e.AdditionalStatementsToAssert.Add(statement);
     if (_statementsFilter(statement))
     {
         EnsureSetFor(owner).Add(statement);
     }
 }
Beispiel #27
0
 public static GetActivityProfilesQuery Create(Iri activityId, DateTimeOffset?since)
 {
     return(new GetActivityProfilesQuery()
     {
         ActivityId = activityId,
         Since = since
     });
 }
Beispiel #28
0
 private void Update(Iri current, IPartialCollectionView view)
 {
     CurrentPartIri  = current;
     FirstPartIri    = view.First?.Iri;
     NextPartIri     = view.Next?.Iri;
     PreviousPartIri = view.Previous?.Iri;
     LastPartIri     = view.Last?.Iri;
 }
Beispiel #29
0
        private IHypermediaContainer CollectionOf(Iri iri, IResource next, IResource previous, params Iri[] iris)
        {
            var result = new Mock <IHypermediaContainer>(MockBehavior.Strict);

            result.SetupGet(_ => _.Members).Returns(new HashSet <IResource>(iris.Select(_ => Resource.Of <IResource>(_).Object)));
            result.SetupGet(_ => _.View).Returns(ViewOf(iri, next, previous));
            return(result.Object);
        }
Beispiel #30
0
 internal static Mock<T> Of<T>(Iri iri = null) where T : class, IResource
 {
     var actualIri = iri ?? new Iri();
     var result = new Mock<T>(MockBehavior.Strict);
     result.As<IEntity>().SetupGet(_ => _.Iri).Returns(iri == Null ? null : actualIri);
     result.Setup(_ => _.GetHashCode()).Returns(actualIri.GetHashCode());
     result.Setup(_ => _.Equals(It.IsAny<object>())).Returns<object>(_ => result.Object == _);
     return result;
 }