/// <summary>
        /// retrieves tags and categories for the resource
        /// </summary>
        private void RetrieveTagsAndCategories()
        {
            using (ZentityContext context = CoreHelper.CreateZentityContext())
            {
                ScholarlyWorkItem resource = context.Resources
                                             .OfType <ScholarlyWorkItem>()
                                             .Where(res => res.Id == ResourceUri)
                                             .FirstOrDefault();

                if (resource == null ||
                    !resource.Authorize("Read", context, CoreHelper.GetAuthenticationToken()))
                {
                    return;
                }

                resource.CategoryNodes.Load();
                List <string> categoryNames = resource.CategoryNodes
                                              .Select(category => category.Title)
                                              .ToList();
                CategoryNames.AddRange(categoryNames);

                resource.Tags.Load();
                List <string> tagNames = resource.Tags
                                         .Select(tag => tag.Name)
                                         .ToList();
                TagNames.AddRange(tagNames);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ZentityAggregatedResource"/> class.
        /// </summary>
        /// <param name="id">id of the resource</param>
        /// <param name="levelOfStripping">stripping level</param>
        public ZentityAggregatedResource(Guid id, int levelOfStripping)
        {
            if (Guid.Empty == id)
            {
                return;
            }

            ResourceUri           = id;
            this.levelOfStripping = levelOfStripping;
            Resource resource;

            using (ZentityContext context = CoreHelper.CreateZentityContext())
            {
                resource = context.Resources
                           .Where(res => res.Id == ResourceUri)
                           .FirstOrDefault();

                if (resource == null ||
                    !resource.Authorize("Read", context, CoreHelper.GetAuthenticationToken()))
                {
                    throw new ArgumentException(Properties.Resources.ORE_RESOURCE_NOT_FOUND, "id");
                }
            }

            if (string.IsNullOrEmpty(ResourcesType))
            {
                ResourcesType = resource.GetType().ToString();
            }
            RetrieveRelations();
            RetrieveTagsAndCategories();
            RetrieveMetadata(resource);
            RetrieveAggreagates(levelOfStripping);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Updates the metadata for the specified resource.
        /// </summary>
        /// <param name="collectionName">Name of the target collection.</param>
        /// <param name="memberResourceId">The Id of the member resource.</param>
        /// <param name="atomEntry">Describes the resource to be modified.</param>
        /// <returns>A SyndicationItem that describes the updated resource.</returns>
        /// <exception cref="ArgumentNullException">Throws exception if collectionName is null/empty
        /// or atomEntry is null.</exception>
        /// <exception cref="ArgumentException">Throws exception if requested memberResourceId is not a unique identifier.</exception>
        SyndicationItem IAtomPubStoreWriter.UpdateMemberInfo(string collectionName, string memberResourceId, AtomEntryDocument atomEntry)
        {
            if (string.IsNullOrEmpty(collectionName))
            {
                throw new ArgumentNullException("collectionName");
            }

            if (string.IsNullOrEmpty(memberResourceId))
            {
                throw new ArgumentNullException("memberResourceId");
            }

            if (null == atomEntry)
            {
                throw new ArgumentNullException("atomEntry");
            }

            using (ZentityContext context = CoreHelper.CreateZentityContext())
            {
                ScholarlyWork resource = (ScholarlyWork)AtomPubHelper.GetMember(context, collectionName, memberResourceId, "Update");
                resource.Files.Load();

                // Bug Fix : 177689 - AtomPub (M2): Author node is appending after every PUT request instead of overwriting it.
                resource.Authors.Load();
                resource.Contributors.Load();

                UpdateResourceProperty(context, resource, atomEntry);
                context.SaveChanges();

                return(ZentityAtomPubStoreReader.GenerateSyndicationItem(this.BaseUri, resource));
            }
        }
        /// <summary>
        /// retrieves aggregate relations for a resource
        /// </summary>
        /// <param name="levelOfStripping">stripping level</param>
        private void RetrieveAggreagates(int levelOfStripping)
        {
            //No retrievals below stripping level
            if (levelOfStripping <= 0)
            {
                return;
            }
            Debug.Assert(ResourceUri != Guid.Empty);

            using (ZentityContext context = CoreHelper.CreateZentityContext())
            {
                List <Relationship> contains = context.Relationships.Where(
                    relationship =>
                    relationship.Subject.Id == ResourceUri &&
                    relationship.Predicate.Uri == Properties.Resources.ORE_CONTAINS_PREDICATE
                    ).ToList();
                foreach (Relationship relation in contains)
                {
                    relation.ObjectReference.Load();
                    ZentityAggregatedResource resource = new ZentityAggregatedResource(relation.Object.Id, --levelOfStripping);
                    AggreagtedResources.Add(resource);
                    Type objectType = context.Resources.Where(res => res.Id == relation.Object.Id).First().GetType();
                    AggregateTypes.Add(objectType);
                }
            }
        }
        /// <summary>
        /// Checks if the member of given type a specified id is present in the given collection.
        /// </summary>
        /// <param name="collectionName">Name of the target collection.</param>
        /// <param name="memberResourceId">Id of the member.</param>
        /// <returns>True if media is present for the given member, else false.</returns>
        /// <exception cref="ArgumentNullException">Throws exception if memberResourceId is null/empty.</exception>
        bool IAtomPubStoreReader.IsMediaPresentForMember(string collectionName, string memberResourceId)
        {
            if (string.IsNullOrEmpty(collectionName))
            {
                throw new ArgumentNullException("collectionName");
            }

            if (string.IsNullOrEmpty(memberResourceId))
            {
                throw new ArgumentNullException("memberResourceId");
            }

            ResourceType collectionType = coreHelper.GetResourceType(collectionName);

            // Prepare a query to get a resource with specified Id and specified type.
            string commandText = string.Format(CultureInfo.InvariantCulture, AtomPubConstants.EsqlToGetFileContents,
                                               collectionType.FullName);

            using (ZentityContext context = CoreHelper.CreateZentityContext())
            {
                ObjectQuery <ScholarlyWork> query = new ObjectQuery <ScholarlyWork>(commandText, context);
                query.Parameters.Add(new ObjectParameter("Id", new Guid(memberResourceId)));

                return(0 < query.Count());
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Creates a new resource of type collectionName in the repository.
        /// </summary>
        /// <param name="collectionName">The resource type.</param>
        /// <param name="atomEntry">Information about the resource.</param>
        /// <returns>A SyndicationItem that describes the newly created resource.</returns>
        /// <exception cref="ArgumentNullException">Throws exception if collectionName is null/empty
        /// or atomEntry is null/empty .</exception>
        SyndicationItem IAtomPubStoreWriter.CreateMember(string collectionName, AtomEntryDocument atomEntry)
        {
            if (string.IsNullOrEmpty(collectionName))
            {
                throw new ArgumentNullException("collectionName");
            }

            if (null == atomEntry)
            {
                throw new ArgumentNullException("atomEntry");
            }

            AuthenticatedToken authenticatedToken = CoreHelper.GetAuthenticationToken();

            using (ZentityContext context = CoreHelper.CreateZentityContext())
            {
                if (!authenticatedToken.HasCreatePermission(context))
                {
                    throw new UnauthorizedException(Resources.ATOMPUB_UNAUTHORIZED);
                }

                ScholarlyWork resource = CreateScholarlyWork(collectionName);
                context.AddToResources(resource);
                ZentityAtomPubStoreWriter.UpdateResourceProperty(context, resource, atomEntry);

                resource.GrantDefaultPermissions(context, authenticatedToken);

                context.SaveChanges();

                return(ZentityAtomPubStoreReader.GenerateSyndicationItem(this.BaseUri, resource));
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Gets the type of the media content.
        /// </summary>
        /// <param name="collectionName">Name of the collection.</param>
        /// <param name="memberResourceId">The member resource id.</param>
        /// <param name="fileExtension">The file extension.</param>
        /// <returns>The media content type.</returns>
        private static string GetMediaContentType(
            string collectionName,
            string memberResourceId,
            out string fileExtension)
        {
            ResourceType collectionType = new CoreHelper().GetResourceType(collectionName);

            // Prepare a query to get a resource with specified Id and specified type.
            string commandText = string.Format(CultureInfo.InvariantCulture, AtomPubConstants.EsqlToGetFileContents,
                                               collectionType.FullName);
            ObjectQuery <Core.File> query = new ObjectQuery <Core.File>(commandText, CoreHelper.CreateZentityContext());

            query.Parameters.Add(new ObjectParameter("Id", new Guid(memberResourceId)));

            var fileProperty = query.Select(file => new
            {
                file.MimeType,
                file.FileExtension
            }).FirstOrDefault();

            if (null != fileProperty)
            {
                fileExtension = fileProperty.FileExtension;
                return(fileProperty.MimeType);
            }
            else
            {
                fileExtension = string.Empty;
                return(null);
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Gets the type of the resource.
        /// </summary>
        /// <param name="typeName">Name of the type.</param>
        /// <returns>The <see cref="ResourceType"/>.</returns>
        internal ResourceType GetResourceType(string typeName)
        {
            if (string.IsNullOrEmpty(typeName))
            {
                return(null);
            }

            ResourceType typeInfo = null;

            using (Core.ZentityContext context = CoreHelper.CreateZentityContext(entityConnectionString))
            {
                var resourceTypes = context.DataModel.Modules
                                    .SelectMany(tuple => tuple.ResourceTypes);

                if (typeName.Contains("."))
                {
                    typeInfo = resourceTypes.FirstOrDefault(type => type.FullName.ToUpperInvariant() == typeName.ToUpperInvariant());
                }
                else
                {
                    typeInfo = resourceTypes.FirstOrDefault(type => type.Name.ToUpperInvariant() == typeName.ToUpperInvariant());
                }
            }

            return(typeInfo);
        }
Exemplo n.º 9
0
        /// <summary>
        /// This method processes the request sent to the Ore service.
        /// </summary>
        /// <param name="context">HttpContext object containing the request information.</param>
        /// <param name="statusCode">Out parameter returns the status of the request.</param>
        /// <returns>Response in string format.</returns>
        public string ProcessRequest(HttpContext context, out System.Net.HttpStatusCode statusCode)
        {
            string response = string.Empty;

            try
            {
                Guid id = ExtractGuidFromRequestUri(GetBaseUri(), context.Request.Url);
                using (ZentityContext zentityContext = CoreHelper.CreateZentityContext())
                {
                    ResourceMap <Guid>     resourceMap = new ResourceMap <Guid>(id);
                    SerializeRDFXML <Guid> serializer  = new SerializeRDFXML <Guid>(resourceMap.CreateMemento());
                    string deployedAt = GetBaseUri().AbsoluteUri;
                    response = serializer.Serialize(deployedAt);
                    context.Response.ContentType = GetContentType();
                    statusCode = HttpStatusCode.OK;
                }
            }
            catch (ArgumentNullException)
            {
                statusCode = HttpStatusCode.NotFound;
                response   = Properties.Resources.ORE_RESOURCE_NOT_FOUND;
            }

            return(response);
        }
Exemplo n.º 10
0
 /// <summary>
 /// Gets the specified resource.
 /// </summary>
 /// <param name="collectionName">The name of the resource type.</param>
 /// <param name="memberResourceId">The Guid of the resource to return.</param>
 /// <returns>A SyndicationItem for the specified resource.</returns>
 /// <exception cref="ArgumentNullException">Throws exception if collectionName is null/empty.</exception>
 SyndicationItem IAtomPubStoreReader.GetMember(string collectionName, string memberResourceId)
 {
     using (ZentityContext context = CoreHelper.CreateZentityContext())
     {
         ScholarlyWork resource = (ScholarlyWork)AtomPubHelper.GetMember(context, collectionName, memberResourceId, "Read");
         return(ZentityAtomPubStoreReader.GenerateSyndicationItem(this.BaseUri, resource));
     }
 }
Exemplo n.º 11
0
        /// <summary>
        /// Updates the Resource.File of the specified resource.
        /// </summary>
        /// <param name="collectionName">The type of the resource.</param>
        /// <param name="memberResourceId">The resource whose File needs to be updated.</param>
        /// <param name="mimeType">The MIME type of media.</param>
        /// <param name="media">The new File contents.</param>
        /// <returns>A SyndicationItem that describes the updated resource.</returns>
        /// <exception cref="ArgumentNullException">Throws exception if collectionName is null/empty
        /// or media is null.</exception>
        /// <exception cref="ArgumentException">Throws exception if requested memberResourceId is not a unique identifier.</exception>
        SyndicationItem IAtomPubStoreWriter.UpdateMedia(string collectionName, string memberResourceId, string mimeType, byte[] media)
        {
            if (string.IsNullOrEmpty(collectionName))
            {
                throw new ArgumentNullException("collectionName");
            }

            if (null == media)
            {
                throw new ArgumentNullException("media");
            }

            if (string.IsNullOrEmpty(memberResourceId))
            {
                throw new ArgumentNullException("memberResourceId");
            }

            if (!AtomPubHelper.IsValidGuid(memberResourceId))
            {
                throw new ArgumentException(Resources.ATOMPUB_INVALID_RESOURCE_ID, "memberResourceId");
            }

            using (ZentityContext context = CoreHelper.CreateZentityContext())
            {
                Type collectionType = CoreHelper.GetSystemResourceType(collectionName);
                // Prepare a query to get a resource with specified Id and specified type.
                string commandText = string.Format(CultureInfo.InvariantCulture, AtomPubConstants.EsqlToGetFileContents,
                                                   collectionType.FullName);

                ObjectQuery <Core.File> query = new ObjectQuery <Core.File>(commandText, context);
                query.Parameters.Add(new ObjectParameter("Id", new Guid(memberResourceId)));
                Core.File mediaResource = query.FirstOrDefault();

                if (null == mediaResource)
                {
                    throw new ResourceNotFoundException(Resources.ATOMPUB_RESOURCE_NOT_FOUND);
                }

                if (!mediaResource.Authorize("Update", context, CoreHelper.GetAuthenticationToken()))
                {
                    throw new UnauthorizedException(Resources.ATOMPUB_UNAUTHORIZED);
                }

                mediaResource.Resources.Load();
                ScholarlyWork resource = (ScholarlyWork)mediaResource.Resources.First();
                resource.DateModified       = DateTime.Now;
                mediaResource.MimeType      = mimeType;
                mediaResource.FileExtension = AtomPubHelper.GetFileExtension(mimeType);

                MemoryStream mediaStream = ZentityAtomPubStoreWriter.GetMediaStream(media);
                context.UploadFileContent(mediaResource, mediaStream);

                // Bug Fix : 180811 - Save Changes once mime type and contents are set.
                context.SaveChanges();

                return(ZentityAtomPubStoreReader.GenerateSyndicationItem(this.BaseUri, resource));
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Processes the request sent to the specified Uri.
        /// This method assumes that the request is already validated.
        /// </summary>
        /// <param name="context">An instance of HttpContext containing the request details.</param>
        /// <param name="statusCode">The HttpStatusCode indicating status of the request.</param>
        /// <returns>
        /// A string containing the response to the request.
        /// </returns>
        public string ProcessRequest(HttpContext context, out HttpStatusCode statusCode)
        {
            string response = string.Empty;
            SyndicationRequestType requestType = SyndicationHelper.GetSyndicationRequestType(context, this.baseUri);

            if (SyndicationRequestType.Help == requestType)
            {
                statusCode = HttpStatusCode.OK;
                response   = Properties.Resources.Help;
            }
            else
            {
                string searchQuery = HttpUtility.UrlDecode(context.Request.QueryString.ToString());
                int    pageSize    = int.Parse(ConfigurationManager.AppSettings["DefaultPageSize"], CultureInfo.InvariantCulture);
                int    maxPageSize = int.Parse(ConfigurationManager.AppSettings["MaxPageSize"], CultureInfo.InvariantCulture);

                if (SyndicationRequestType.DefaultSearchWithPageNo == requestType ||
                    SyndicationRequestType.RSSSearchWithPageNo == requestType ||
                    SyndicationRequestType.ATOMSearchWithPageNo == requestType)
                {
                    pageSize = int.Parse(SyndicationHelper.GetValueOfParameterFromUri(context, this.baseUri,
                                                                                      requestType, SyndicationParameterType.PageSize), CultureInfo.InvariantCulture);
                    pageSize = (pageSize > maxPageSize) ? maxPageSize : pageSize;
                }

                AuthenticatedToken token = (AuthenticatedToken)context.Items["AuthenticatedToken"];
                List <Resource>    resources;
                try
                {
                    SearchEngine searchEngin =
                        new SearchEngine(pageSize, true, token);
                    int            totalRecords;
                    ZentityContext zentityContext = CoreHelper.CreateZentityContext();
                    SortProperty   sortProperty   =
                        new SortProperty("dateModified", SortDirection.Descending);

                    resources = searchEngin.SearchResources(searchQuery,
                                                            zentityContext, sortProperty, 0, out totalRecords).ToList();
                    ;
                }
                catch (SearchException exception)
                {
                    statusCode = HttpStatusCode.BadRequest;
                    response   = exception.Message;
                    return(response);
                }
                SyndicationFeed feed = SyndicationHelper.CreateSyndicationFeed(resources, searchQuery, context.Request.Url);

                response = SyndicationHelper.GetResponseDocument(feed, requestType);

                statusCode = HttpStatusCode.OK;
            }
            return(response);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Gets a media contents of a member resource.
        /// </summary>
        /// <param name="collectionName">Name of the target collection.</param>
        /// <param name="memberResourceId">The Id of the member resource.</param>
        /// <param name="outputStream">A stream containing the media corresponding to the specified resource. If no matching media is found, null is returned.</param>
        /// <exception cref="ArgumentNullException">Throws exception if memberResourceId is null/empty
        /// or outputStream is null.</exception>
        /// <exception cref="ArgumentException">Throws exception if outputStream stream is not readable.</exception>
        void IAtomPubStoreReader.GetMedia(string collectionName, string memberResourceId, Stream outputStream)
        {
            if (string.IsNullOrEmpty(collectionName))
            {
                throw new ArgumentNullException("collectionName");
            }

            if (string.IsNullOrEmpty(memberResourceId))
            {
                throw new ArgumentNullException("memberResourceId");
            }

            if (null == outputStream)
            {
                throw new ArgumentNullException("outputStream");
            }

            if (!AtomPubHelper.IsValidGuid(memberResourceId))
            {
                throw new ArgumentException(Resources.ATOMPUB_INVALID_RESOURCE_ID);
            }

            if (!outputStream.CanWrite)
            {
                throw new ArgumentException(Properties.Resources.ATOMPUB_CANNOT_WRITE_ON_STREAM, "outputStream");
            }

            using (ZentityContext context = CoreHelper.CreateZentityContext())
            {
                ResourceType collectionType = coreHelper.GetResourceType(collectionName);

                // Prepare a query to get a resource with specified Id and specified type.
                string commandText = string.Format(CultureInfo.InvariantCulture, AtomPubConstants.EsqlToGetFileContents,
                                                   collectionType.FullName);

                ObjectQuery <Core.File> query = new ObjectQuery <Core.File>(commandText, context);
                query.Parameters.Add(new ObjectParameter("Id", new Guid(memberResourceId)));
                Core.File mediaFile = query.FirstOrDefault();

                if (null == mediaFile)
                {
                    throw new ResourceNotFoundException(Resources.ATOMPUB_RESOURCE_NOT_FOUND);
                }

                if (!mediaFile.Authorize("Read", context, CoreHelper.GetAuthenticationToken()))
                {
                    throw new UnauthorizedException(Resources.ATOMPUB_UNAUTHORIZED);
                }

                context.DownloadFileContent(mediaFile, outputStream);
            }
        }
Exemplo n.º 14
0
 /// <summary>
 /// Get Date modified value of a specified resource.
 /// </summary>
 /// <param name="memberResourceId">Id of resource to get modified date.</param>
 /// <returns>Returns NULL if resource does not exists.
 /// Returns minimum date value if resource's modified date is empty in data store.</returns>
 private static DateTime?GetModifiedDate(string memberResourceId)
 {
     using (ZentityContext context = CoreHelper.CreateZentityContext())
     {
         Guid resourceId = new Guid(memberResourceId);
         return(context.ScholarlyWorks()
                .Where(resource => resource.Id == resourceId)
                .AsEnumerable()
                .Select(resource => (null == resource) ? null :
                        (null == resource.DateModified) ? DateTime.MinValue : resource.DateModified)
                .FirstOrDefault());
     }
 }
Exemplo n.º 15
0
        /// <summary>
        /// Retrieves a collection of all the resources that have recently been added or modified
        /// </summary>
        /// <typeparam name="T">Type of Resource which derive from
        /// <typeref name="Zentity.Core.Resource"/></typeparam>
        /// <param name="isForDateAdded">
        /// boolean indicating if we want to retrieve resources that have been currently added
        /// or those resources that have been recently modified</param>
        /// <param name="count">The number of resources that are to be retrieved</param>
        /// <param name="date">The date on which resources have been added or modified</param>
        /// <param name="connectionString">Data storage connection string.</param>
        /// <returns>List of resources</returns>
        internal static List <T> GetResourcesByDate <T>(bool isForDateAdded,
                                                        ushort count,
                                                        DateTime date,
                                                        string connectionString) where T : Core.Resource
        {
            if (0 >= count)
            {
                throw new ArgumentException(Properties.Resources.EXCEPTION_ARGUMENTINVALID, "count");
            }

            if (count > PlatformSettings.MaximumFeedCount)
            {
                count = PlatformSettings.MaximumFeedCount;
            }

            List <T>       listOfResources = null;
            Func <T, bool> predicate       = null;

            if (isForDateAdded)
            {
                predicate = resource => resource.DateAdded >= date;
            }
            else
            {
                predicate = resource => resource.DateModified >= date;
            }

            try
            {
                using (Core.ZentityContext zentityContext = CoreHelper.CreateZentityContext(connectionString))
                {
                    zentityContext.CommandTimeout = PlatformSettings.ConnectionTimeout;
                    listOfResources = zentityContext.Resources
                                      .OfType <T>()
                                      .Where(predicate)
                                      .OrderByDescending(resource => resource.DateModified)
                                      .AsEnumerable()
                                      .Where(resource => !(resource is Contact || resource is Tag || resource is CategoryNode))
                                      .Take(count)
                                      .ToList();
                    LoadResources <T>(listOfResources);
                }
            }
            catch (ArgumentNullException)
            {
                throw;
            }

            return(listOfResources);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Creates a new Resource.File for a specified resource of type collectionName in the repository.
        /// </summary>
        /// <param name="collectionName">The resource type.</param>
        /// <param name="mimeType">The MIME type of media.</param>
        /// <param name="media">The new File contents.</param>
        /// <param name="fileExtension">The media file extension.</param>
        /// <returns>A SyndicationItem that describes the newly created resource.</returns>
        /// <exception cref="ArgumentNullException">Throws exception if collectionName is null/empty
        /// or mimeType is null/empty or media is null.</exception>
        protected SyndicationItem CreateMedia(string collectionName, string mimeType, byte[] media,
                                              string fileExtension)
        {
            if (string.IsNullOrEmpty(collectionName))
            {
                throw new ArgumentNullException("collectionName");
            }

            if (string.IsNullOrEmpty(mimeType))
            {
                throw new ArgumentNullException("mimeType");
            }

            if (null == media)
            {
                throw new ArgumentNullException("media");
            }

            AuthenticatedToken authenticatedToken = CoreHelper.GetAuthenticationToken();

            using (ZentityContext context = CoreHelper.CreateZentityContext())
            {
                if (!authenticatedToken.HasCreatePermission(context))
                {
                    throw new UnauthorizedException(Resources.ATOMPUB_UNAUTHORIZED);
                }

                ScholarlyWork resource = CreateScholarlyWork(collectionName);
                resource.DateModified = DateTime.Now;

                Core.File mediaResource = new Core.File();
                mediaResource.MimeType      = mimeType;
                mediaResource.FileExtension = string.IsNullOrEmpty(fileExtension) ?
                                              AtomPubHelper.GetFileExtension(mimeType) : fileExtension;
                context.AddToResources(mediaResource);
                context.SaveChanges();
                resource.Files.Add(mediaResource);

                MemoryStream mediaStream = ZentityAtomPubStoreWriter.GetMediaStream(media);
                context.UploadFileContent(mediaResource, mediaStream);
                mediaStream.Close();

                resource.GrantDefaultPermissions(context, authenticatedToken);
                mediaResource.GrantDefaultPermissions(context, authenticatedToken);

                context.SaveChanges();

                return(ZentityAtomPubStoreReader.GenerateSyndicationItem(this.BaseUri, resource));
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Calculates the ETag value for a specified resource.
        /// </summary>
        /// <param name="memberResourceId">Is of the resource.</param>
        /// <returns>string containing ETag value for the resource.</returns>
        internal static string CalculateETag(string memberResourceId)
        {
            using (ZentityContext context = CoreHelper.CreateZentityContext())
            {
                DateTime?dateModified = GetModifiedDate(memberResourceId);

                if (null == dateModified)
                {
                    throw new ResourceNotFoundException(Resources.ATOMPUB_RESOURCE_NOT_FOUND);
                }

                return(CalculateETag(memberResourceId, dateModified));
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Gets a SyndicationFeed containing resources of type collectionName.
        /// </summary>
        /// <param name="collectionName">The name of the resource type.</param>
        /// <param name="skip">The number of resources to skip from the start.</param>
        /// <param name="count">The number of resources to return.</param>
        /// <returns>A SyndicationFeed of resources of the specified type.</returns>
        /// <exception cref="ArgumentNullException">Throws exception if collectionName is null/empty.</exception>
        /// <exception cref="ArgumentException">Throws exception if skip value is negative or count value is negative.</exception>
        SyndicationFeed IAtomPubStoreReader.GetMembers(string collectionName, long skip, long count)
        {
            if (string.IsNullOrEmpty(collectionName))
            {
                throw new ArgumentNullException("collectionName");
            }

            if (0 > skip)
            {
                throw new ArgumentException(Resources.ATOMPUB_INVALID_VALUE, "skip");
            }
            if (0 > count)
            {
                throw new ArgumentException(Resources.ATOMPUB_INVALID_VALUE, "count");
            }

            int skipCount = (int)skip;
            int takeCount = (int)count;

            ResourceType collectionType = coreHelper.GetResourceType(collectionName);


            // Prepare a query to get a resource with specified Id and specified type.
            string commandText = string.Format(CultureInfo.InvariantCulture, AtomPubConstants.EsqlToGetAllResources,
                                               collectionType.FullName);
            AuthenticatedToken authenticatedToken = CoreHelper.GetAuthenticationToken();

            using (ZentityContext zentityContext = CoreHelper.CreateZentityContext())
            {
                ObjectQuery <ScholarlyWork> resourcesQuery = new ObjectQuery <ScholarlyWork>(commandText, zentityContext);
                List <ScholarlyWork>        resources      = resourcesQuery.Authorize("Read", zentityContext, authenticatedToken)
                                                             .OrderByDescending(resource => resource.DateModified)
                                                             .Skip(skipCount).Take(takeCount)
                                                             .ToList();

                List <SyndicationItem> syndicationItems = new List <SyndicationItem>();

                if (null != resources && 0 < resources.Count)
                {
                    foreach (ScholarlyWork resource in resources)
                    {
                        SyndicationItem syndicationItem = ZentityAtomPubStoreReader.GenerateSyndicationItem(this.BaseUri, resource);
                        syndicationItems.Add(syndicationItem);
                    }
                }

                return(new SyndicationFeed(syndicationItems));
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Retrieves a collection of all the resources owned by the author
        /// </summary>
        /// <typeparam name="T">Type of Resource which derive from
        /// <typeref name="Zentity.Core.Resource"/></typeparam>
        /// <param name="firstName">The associated author's first name</param>
        /// <param name="lastName">The associated author's last name</param>
        /// <param name="count">The number of resources that are to be retrieved</param>
        /// <param name="connectionString">Data storage connection string.</param>
        /// <returns>A collection of key value pairs of author and his associated resources</returns>
        internal static List <T> GetResourcesByAuthor <T>(string firstName,
                                                          string lastName,
                                                          ushort count,
                                                          string connectionString) where T : ScholarlyWorks.ScholarlyWork
        {
            if (string.IsNullOrEmpty(firstName))
            {
                throw new ArgumentNullException("firstName");
            }
            if (string.IsNullOrEmpty(lastName))
            {
                throw new ArgumentNullException("lastName");
            }
            if (0 >= count)
            {
                throw new ArgumentException(Properties.Resources.EXCEPTION_ARGUMENTINVALID, "count");
            }


            if (count > PlatformSettings.MaximumFeedCount)
            {
                count = PlatformSettings.MaximumFeedCount;
            }

            List <T> listOfResources = null;

            try
            {
                using (Core.ZentityContext zentityContext = CoreHelper.CreateZentityContext(connectionString))
                {
                    zentityContext.CommandTimeout = PlatformSettings.ConnectionTimeout;
                    listOfResources = zentityContext.People()
                                      .Where(author => author.FirstName == firstName &&
                                             author.LastName == lastName)
                                      .SelectMany(author => author.AuthoredWorks)
                                      .OfType <T>()
                                      .OrderByDescending(resource => resource.DateModified)
                                      .Take(count)
                                      .ToList();
                    LoadResources <T>(listOfResources);
                }
            }
            catch (ArgumentNullException)
            {
                throw;
            }

            return(listOfResources);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Gets the number of resources present in a collection.
        /// </summary>
        /// <param name="collectionName">The collection name.</param>
        /// <returns>Number of members present in the specified collection.</returns>
        long IAtomPubStoreReader.GetMembersCount(string collectionName)
        {
            Type collectionType = CoreHelper.GetSystemResourceType(collectionName);
            // Prepare a query to get a resource with specified Id and specified type.
            string commandText = string.Format(CultureInfo.InvariantCulture, AtomPubConstants.EsqlToGetAllResources,
                                               collectionType.FullName);
            AuthenticatedToken authenticatedToken = CoreHelper.GetAuthenticationToken();

            using (ZentityContext zentityContext = CoreHelper.CreateZentityContext())
            {
                ObjectQuery <ScholarlyWork> resourcesQuery = new ObjectQuery <ScholarlyWork>(commandText, zentityContext);
                return(Convert.ToInt64(resourcesQuery.Authorize("Read", zentityContext, authenticatedToken)
                                       .Count()));
            }
        }
Exemplo n.º 21
0
        /// <summary>
        ///     retrieves the when was first resource added to core
        /// </summary>
        /// <returns>datestamp of first resource added</returns>
        internal string GetEarliestdateStamp()
        {
            using (Core.ZentityContext zentityContext = CoreHelper.CreateZentityContext())
            {
                DateTime?earliestScholarlyWorkDateStamp = getEarliestDateStamp(zentityContext);

                if (earliestScholarlyWorkDateStamp.HasValue)
                {
                    return(earliestScholarlyWorkDateStamp.Value.ToUniversalTime().
                           ToString(MetadataProviderHelper.DateTimeGranularity, CultureInfo.InvariantCulture));
                }
                else
                {
                    return(string.Empty);
                }
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Checks if specified resource exist
        /// </summary>
        /// <param name="identifier"> resource identifier </param>
        /// <returns> boolean indicating whether resource exist or not </returns>
        internal bool CheckIfResourceExists(Guid identifier)
        {
            bool exists = false;

            using (Core.ZentityContext zentityContext = CoreHelper.CreateZentityContext())
            {
                var returnedResource = zentityContext.Resources
                                       .Where(resource => resource.Id == identifier)
                                       .FirstOrDefault();

                if (returnedResource != null &&
                    returnedResource.Authorize("Read", zentityContext, GetAuthenticationToken()))
                {
                    exists = true;
                }
            }

            return(exists);
        }
Exemplo n.º 23
0
        /// <summary>
        /// retrieves resource object specific to resource id
        /// </summary>
        /// <param name="resourceId">id for retrieving specific object</param>
        /// <returns>resource object</returns>
        internal Core.Resource GetResource(Guid resourceId)
        {
            Core.Resource coreResource = null;

            using (Core.ZentityContext zentityContext = CoreHelper.CreateZentityContext())
            {
                var returnedResource = zentityContext.Resources
                                       .Where(resource => resource.Id == resourceId)
                                       .FirstOrDefault();

                if (returnedResource != null &&
                    returnedResource.Authorize("Read", zentityContext, GetAuthenticationToken()))
                {
                    coreResource = LoadResource(returnedResource);
                }
            }

            return(coreResource);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Retrieves a collection of all the resources having with the specified label for the tag
        /// </summary>
        /// <typeparam name="T">Type of Resource which derive from
        /// <typeref name="Zentity.Core.Resource"/></typeparam>
        /// <param name="tagLabel">The associated tag label</param>
        /// <param name="count">The number of resources that are to be retrieved</param>
        /// <param name="connectionString">Data storage connection string.</param>
        /// <returns>A key value pair of tag and its resources</returns>
        internal static List <T> GetResourcesByCategory <T>(string tagLabel,
                                                            ushort count,
                                                            string connectionString) where T : ScholarlyWorks.ScholarlyWorkItem
        {
            if (string.IsNullOrEmpty(tagLabel))
            {
                throw new ArgumentNullException("tagLabel");
            }
            if (0 >= count)
            {
                throw new ArgumentException(Properties.Resources.EXCEPTION_ARGUMENTINVALID, "count");
            }

            if (count > PlatformSettings.MaximumFeedCount)
            {
                count = PlatformSettings.MaximumFeedCount;
            }

            List <T> listOfResources = null;

            try
            {
                using (Core.ZentityContext zentityContext = CoreHelper.CreateZentityContext(connectionString))
                {
                    zentityContext.CommandTimeout = PlatformSettings.ConnectionTimeout;
                    listOfResources = zentityContext.CategoryNodes()
                                      .Where(tag => tag.Title == tagLabel)
                                      .SelectMany(tag => tag.ScholarlyWorkItems)
                                      .OfType <T>()
                                      .OrderByDescending(resource => resource.DateModified)
                                      .Take(count)
                                      .ToList();
                    LoadResources <T>(listOfResources);
                }
            }

            catch (ArgumentNullException)
            {
                throw;
            }

            return(listOfResources);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Retrieves a collection of all the resources whose contributor's email Id has been specified
        /// </summary>
        /// <typeparam name="T">Type of Resource which derive from
        /// <typeref name="Zentity.Core.Resource"/></typeparam>
        /// <param name="emailId">The associated contributor's email id</param>
        /// <param name="count">The number of resources that are to be retrieved</param>
        /// <param name="connectionString">Data storage connection string.</param>
        /// <returns>A collection of key value pairs of author and his associated resources</returns>
        internal static List <T> GetResourcesByContributor <T>(string emailId,
                                                               ushort count, string connectionString) where T : ScholarlyWorks.ScholarlyWork
        {
            if (string.IsNullOrEmpty(emailId))
            {
                throw new ArgumentNullException("emailId");
            }
            if (0 >= count)
            {
                throw new ArgumentException(Properties.Resources.EXCEPTION_ARGUMENTINVALID, "count");
            }

            if (count > PlatformSettings.MaximumFeedCount)
            {
                count = PlatformSettings.MaximumFeedCount;
            }

            List <T> listOfResources = null;

            try
            {
                using (Core.ZentityContext zentityContext = CoreHelper.CreateZentityContext(connectionString))
                {
                    zentityContext.CommandTimeout = PlatformSettings.ConnectionTimeout;
                    listOfResources = zentityContext.Contacts()
                                      .Where(contributor => contributor.Email == emailId)
                                      .SelectMany(contributor => contributor.ContributionInWorks)
                                      .OfType <T>()
                                      .OrderByDescending(resource => resource.DateModified)
                                      .Take(count)
                                      .ToList();
                    LoadResources <T>(listOfResources);
                }
            }
            catch (ArgumentNullException)
            {
                throw;
            }

            return(listOfResources);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Gets the resource type hierarchy.
        /// </summary>
        /// <param name="resourceTypeInfo">The resource type info.</param>
        /// <returns>List of resource type by heirarchy.</returns>
        internal List <string> GetResourceTypeHierarchy(ResourceType resourceTypeInfo)
        {
            List <string> resourceTypeList = new List <string>();

            if (null == resourceTypeInfo)
            {
                return(resourceTypeList);
            }

            if (CoreHelper.resourceTypeHierarchy.ContainsKey(resourceTypeInfo.Name))
            {
                return(CoreHelper.resourceTypeHierarchy[resourceTypeInfo.Name]);
            }

            ResourceType orginalResourceType = resourceTypeInfo;

            resourceTypeList.Add(resourceTypeInfo.Name);

            using (Core.ZentityContext context = CoreHelper.CreateZentityContext(entityConnectionString))
            {
                while (resourceTypeInfo.BaseType != null)
                {
                    ResourceType resourceType = null;
                    foreach (ResourceType resType in CoreHelper.GetResourceTypes(context))
                    {
                        if ((resourceTypeInfo.BaseType.FullName.EndsWith(resType.Name, StringComparison.Ordinal) &&
                             resourceTypeInfo.BaseType.FullName.StartsWith(resType.Parent.NameSpace, StringComparison.Ordinal)))
                        {
                            resourceType = resType;
                            break;
                        }
                    }

                    resourceTypeInfo = resourceType;
                    resourceTypeList.Add(resourceTypeInfo.Name);
                }
            }
            CoreHelper.resourceTypeHierarchy.Add(orginalResourceType.Name, resourceTypeList);
            return(resourceTypeList);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Deletes the Resource.File for the specified resource.
        /// </summary>
        /// <param name="collectionName">The type of the resource.</param>
        /// <param name="memberResourceId">The Guid of the resource.</param>
        /// <returns>True if the operation succeeds, False otherwise.</returns>
        /// <exception cref="ArgumentNullException">Throws exception if collectionName is null/empty.</exception>
        /// <exception cref="ArgumentException">Throws exception if requested memberResourceId is not a unique identifier.</exception>
        bool IAtomPubStoreWriter.DeleteMedia(string collectionName, string memberResourceId)
        {
            if (string.IsNullOrEmpty(collectionName))
            {
                throw new ArgumentNullException("collectionName");
            }

            if (!AtomPubHelper.IsValidGuid(memberResourceId))
            {
                throw new ArgumentException(Resources.ATOMPUB_INVALID_RESOURCE_ID, "memberResourceId");
            }

            using (ZentityContext context = CoreHelper.CreateZentityContext())
            {
                Type   collectionType = CoreHelper.GetSystemResourceType(collectionName);
                string commandText    = string.Format(CultureInfo.InvariantCulture, AtomPubConstants.EsqlToGetFileContents,
                                                      collectionType.FullName);

                ObjectQuery <Core.File> query = new ObjectQuery <Core.File>(commandText, context);
                query.Parameters.Add(new ObjectParameter("Id", new Guid(memberResourceId)));

                Core.File mediaFile = query.FirstOrDefault();

                if (null == mediaFile)
                {
                    throw new ResourceNotFoundException(Resources.ATOMPUB_RESOURCE_NOT_FOUND);
                }

                if (!mediaFile.Authorize("Delete", context, CoreHelper.GetAuthenticationToken()))
                {
                    throw new UnauthorizedException(Resources.ATOMPUB_UNAUTHORIZED);
                }

                DeleteRelationships(context, mediaFile);
                context.DeleteObject(mediaFile);
                context.SaveChanges();
                return(true);
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Retrieves relationship of the resource
        /// </summary>
        private void RetrieveRelations()
        {
            if (levelOfStripping <= 0)
            {
                return;
            }

            List <Relationship> containedResources;

            using (ZentityContext context = CoreHelper.CreateZentityContext())
            {
                Resource resource = context.Resources
                                    .Where(res => res.Id == ResourceUri)
                                    .FirstOrDefault();

                if (resource == null ||
                    !resource.Authorize("Read", context, CoreHelper.GetAuthenticationToken()))
                {
                    return;
                }

                resource.RelationshipsAsSubject.Load();

                containedResources = resource.RelationshipsAsSubject.ToList();

                foreach (Relationship rel in containedResources)
                {
                    rel.ObjectReference.Load();
                    ObjectResourceIds.Add(rel.Object.Id);

                    Type objectType = rel.Object.GetType();

                    ObjectTypes.Add(objectType);

                    rel.PredicateReference.Load();
                    RelationUris.Add(rel.Predicate.Name);
                }
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Gets all the resource types that inherit from ScholarlyWork, including ScholarlyWork.
        /// </summary>
        /// <returns>An array of strings containing the resource type names.</returns>
        string[] IAtomPubStoreReader.GetCollectionNames()
        {
            List <string> resourceTypes = new List <string>();

            using (ZentityContext zentityContext = CoreHelper.CreateZentityContext())
            {
                resourceTypes = new List <string>();

                // Get all resource types which are derived from ScholarlyWork as
                // only ScholarlyWork type supports authors list.
                foreach (ResourceType typeInfo in CoreHelper.GetResourceTypes(zentityContext))
                {
                    if (AtomPubHelper.IsValidCollectionType(typeInfo.Name))
                    {
                        resourceTypes.Add(typeInfo.Name);
                    }
                }
            }

            return(resourceTypes
                   .OrderBy(name => name)
                   .ToArray());
        }
Exemplo n.º 30
0
        /// <summary>
        /// Deletes the specified resource.
        /// </summary>
        /// <param name="collectionName">The type of the resource.</param>
        /// <param name="memberResourceId">The Guid of the resource.</param>
        /// <returns>True if the operation succeeds, False otherwise.</returns>
        /// <exception cref="ArgumentNullException">Throws exception if collectionName is null/empty.</exception>
        /// <exception cref="ArgumentException">Throws exception if requested memberResourceId is not a unique identifier.</exception>
        bool IAtomPubStoreWriter.DeleteMember(string collectionName, string memberResourceId)
        {
            using (ZentityContext context = CoreHelper.CreateZentityContext())
            {
                ScholarlyWork resource = (ScholarlyWork)AtomPubHelper.GetMember(context, collectionName, memberResourceId, "Delete");

                // Load to delete all Core.File resource associated to requested scholarlywork.
                if (!resource.Files.IsLoaded)
                {
                    resource.Files.Load();
                }

                Zentity.Core.File[] resourceFiles = resource.Files.ToArray();

                for (int i = 0; i < resourceFiles.Length; i++)
                {
                    DeleteRelationships(context, resourceFiles[i]);
                    context.DeleteObject(resourceFiles[i]);
                }

                DeleteRelationships(context, resource);

                // Delete associated Resource propertes
                resource.ResourceProperties.Load();
                List <ResourceProperty> resProperties = resource.ResourceProperties.ToList();
                foreach (ResourceProperty property in resProperties)
                {
                    resource.ResourceProperties.Remove(property);
                    context.DeleteObject(property);
                }

                context.DeleteObject(resource);
                context.SaveChanges();
                return(true);
            }
        }