/// <summary>
        /// Verify the rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;

            var    qs      = HttpUtility.ParseQueryString(context.Destination.Query);
            string qExpand = qs["$expand"];

            if (!string.IsNullOrEmpty(qExpand))
            {
                JObject jo      = JObject.Parse(context.ResponsePayload);
                var     version = JsonParserHelper.GetPayloadODataVersion(jo);

                var        edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
                EntityType et;
                edmxHelper.TryGetItem(context.EntityTypeFullName, out et);

                var branches = ResourcePathHelper.GetBranchedSegments(qExpand);
                foreach (var paths in branches)
                {
                    var    navStack           = ODataUriAnalyzer.GetNavigationStack(et, paths).ToArray();
                    bool[] targetIsCollection = (from n in navStack select n.RelationshipMultiplicity == RelationshipMultiplicity.Many).ToArray();

                    // to verify each single entity type expanded along the navigation path to have proper properties
                    TestResult result = null;
                    for (int i = 0; i < paths.Length; i++)
                    {
                        string jSchema = null;

                        if (!targetIsCollection[i])
                        {
                            var    etShort = navStack[i].GetEntityType().FullName.GetLastSegment();
                            string jsET    = JsonSchemaHelper.GetSchemaForEntityType(etShort, context.MetadataDocument);
                            string jsCore  = string.Format(@"""{0}"" : {1}", paths[i], jsET);
                            jSchema = JsonSchemaHelper.GetJsonSchema(paths, i, version, jsCore, targetIsCollection);

                            passed = JsonParserHelper.ValidateJson(jSchema, context.ResponsePayload, out result);
                            if (!passed.Value)
                            {
                                break;
                            }
                        }
                    }

                    if (!passed.Value)
                    {
                        info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, result != null ? result.LineNumberInError : -1);
                        break;
                    }
                }
            }

            return(passed);
        }
        /// <summary>
        /// Builds the uri for purpose of probing the empty feed based on the base uri string.
        /// </summary>
        /// <param name="context">The service context object</param>
        /// <returns>Uri object if a meaningful prober can be constructed; null otherwise </returns>
        private static Uri ConstructProbeUri(ServiceContext context)
        {
            int safetyTopping = 20;
            Uri result        = null;

            // find out how many entries in the base feed
            Uri uriFeedCount = new Uri(context.DestinationBasePath + "/$count");
            var resp         = WebHelper.Get(uriFeedCount, Constants.AcceptHeaderAtom, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);

            if (resp.StatusCode.HasValue && resp.StatusCode.Value == System.Net.HttpStatusCode.OK && !string.IsNullOrEmpty(resp.ResponsePayload))
            {
                string payload = resp.ResponsePayload.Trim();
                int    count   = 0;
                if (Int32.TryParse(payload, out count) && count >= 0)
                {
                    int countToSkip = count + safetyTopping;
                    Uri uriBaseFeed = new Uri(context.DestinationBasePath);
                    ResourcePathHelper pathHelper = new ResourcePathHelper(uriBaseFeed);
                    pathHelper.AddQueryOption("$skip", countToSkip.ToString(CultureInfo.InvariantCulture));

                    result = new Uri(pathHelper.Product);
                }
            }

            return(result);
        }
        /// <summary>
        /// Verify the code rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;

            var     edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            var     segments   = ResourcePathHelper.GetPathSegments(context);
            UriType uriType;
            var     target = edmxHelper.GetTargetType(segments, out uriType);

            // to check this rule only when returned resource is a ComplexType
            if (uriType == UriType.URI3 || uriType == UriType.URI12)
            {
                JObject    jo      = JObject.Parse(context.ResponsePayload);
                var        version = JsonParserHelper.GetPayloadODataVersion(jo);
                string     name    = (uriType == UriType.URI3) ? ((EdmProperty)target).Name : ((ComplexType)target).Name;
                string     jsCore  = string.Format(fmtoreSchema, name);
                string     jSchema = JsonSchemaHelper.WrapJsonSchema(jsCore, version);
                TestResult testResult;
                passed = JsonParserHelper.ValidateJson(jSchema, context.ResponsePayload, out testResult);
                if (passed.HasValue && !passed.Value)
                {
                    info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, testResult != null ? testResult.LineNumberInError : -1);
                }
            }

            return(passed);
        }
        /// <summary>
        /// Verifies the semantic rule
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out paramater to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool passed = true;

            info = null;

            // get the first segment after the service root URI
            string path;

            if (ResourcePathHelper.IsOneSegmentPath(context, out path))
            {
                if (RegexInUri.IsURI2(path, XElement.Parse(context.MetadataDocument)))
                {
                    if (context.PayloadType != RuleEngine.PayloadType.Entry)
                    {
                        passed = false;
                        info   = new ExtensionRuleViolationInfo("error payload type expected", context.Destination, context.PayloadType.ToString());
                    }
                }
            }

            return(passed);
        }
        /// <summary>
        /// Asynchronously saves the folder image with the specified path to the specified directory.
        /// </summary>
        /// <param name="nativeSystemId">The native system id of the path.</param>
        /// <param name="path">Path to the image to save.</param>
        /// <param name="saveDirectory">Directory to save the image.</param>
        /// <returns>A <see cref="Task"/> that completes when the image has been saved.</returns>
        protected async Task <bool> TrySaveFolderImage(string nativeSystemId, ResourcePath path, string saveDirectory)
        {
            string savePath = Path.Combine(saveDirectory, "Folder." + ResourcePathHelper.GetFileName(path.ToString()));

            try
            {
                if (File.Exists(savePath))
                {
                    return(false);
                }

                using (IResourceAccessor accessor = new ResourceLocator(nativeSystemId, path).CreateAccessor())
                    if (accessor is IFileSystemResourceAccessor fsra)
                    {
                        using (Stream ms = fsra.OpenRead())
                            using (FileStream fs = File.OpenWrite(savePath))
                                await ms.CopyToAsync(fs).ConfigureAwait(false);
                        return(true);
                    }
            }
            catch (Exception ex)
            {
                // Decoding of invalid image data can fail, but main MediaItem is correct.
                Logger.Warn("{0}: Error saving folder image to path '{1}'", ex, _metadata.Name, savePath);
            }
            return(false);
        }
示例#6
0
        /// <summary>
        /// Verifies the semantic rule
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            info = null;
            bool?passed = null;

            var     edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            var     segments   = ResourcePathHelper.GetPathSegments(context);
            UriType uriType;
            var     target = edmxHelper.GetTargetType(segments, out uriType);

            if (uriType == UriType.URI3)
            {
                ComplexType complexType = (ComplexType)((EdmProperty)target).TypeUsage.EdmType;
                XElement    payload     = XElement.Parse(context.ResponsePayload);
                passed = VerifyComplexType(payload, complexType, context.Destination, out info);
            }
            else if (uriType == UriType.URI4 || uriType == UriType.URI5)
            {
                PrimitiveType propertyType = (PrimitiveType)((EdmProperty)target).TypeUsage.EdmType;
                XElement      property     = XElement.Parse(context.ResponsePayload);
                passed = VerifyValueByPrimitiveType(property.Value, propertyType.FullName);
                if (!passed.Value)
                {
                    passed = false;
                    info   = new ExtensionRuleViolationInfo("invalid formatted value for type " + propertyType.FullName, context.Destination, property.Value);
                }
            }

            return(passed);
        }
        /// <summary>
        /// Verify the code rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;

            var     segments   = ResourcePathHelper.GetPathSegments(context).ToArray();
            var     edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            UriType uriType;
            var     target = edmxHelper.GetTargetType(segments, out uriType);

            if (uriType == UriType.URI4 || uriType == UriType.URI5)
            {
                string  property = segments.LastOrDefault(s => !s.StartsWith("$"));
                JObject jo       = JObject.Parse(context.ResponsePayload);
                var     version  = JsonParserHelper.GetPayloadODataVersion(jo);

                string     coreSchema = string.Format(fmtCore, property);
                string     jSchema    = JsonSchemaHelper.WrapJsonSchema(coreSchema, version);
                TestResult testResult;
                passed = JsonParserHelper.ValidateJson(jSchema, context.ResponsePayload, out testResult);
                if (passed.HasValue && !passed.Value)
                {
                    info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, testResult != null ? testResult.LineNumberInError : -1);
                }
            }

            return(passed);
        }
示例#8
0
        /// <summary>
        /// Fills the image combo with the names of icons collectins (folders)
        /// </summary>
        public void FillCollectionCombo()
        {
            cboIconCollection.Items.Clear();

            cboIconCollection.Enabled = false;
            chkScaleIcons.Enabled     = false;

            var path = ResourcePathHelper.GetIconsPath();

            var folders = GetIconFolders(path);

            if (folders == null || folders.Length == 0)
            {
                return;
            }

            foreach (string folder in folders)
            {
                if (Directory.GetFiles(folder).Any(item => item.ToLower().EndsWith(".png")))
                {
                    string name = folder.Substring(path.Length);
                    cboIconCollection.Items.Add(name);
                }
            }

            bool enabled = cboIconCollection.Items.Count > 0;

            cboIconCollection.Enabled = enabled;
            chkScaleIcons.Enabled     = enabled;
        }
        /// <summary>
        /// Reads all tag images and caches them in the <see cref="IFanArtCache"/> service.
        /// </summary>
        /// <param name="mediaItemLocator"><see cref="IResourceLocator>"/> that points to the file.</param>
        /// <param name="mediaItemId">Id of the media item.</param>
        /// <param name="title">Title of the media item.</param>
        /// <returns><see cref="Task"/> that completes when the images have been cached.</returns>
        protected async Task ExtractFanArt(IResourceLocator mediaItemLocator, Guid mediaItemId, string title, IDictionary <Guid, IList <MediaItemAspect> > aspects)
        {
            try
            {
                //File based access
                using (IResourceAccessor mediaItemAccessor = mediaItemLocator.CreateAccessor())
                    using (LocalFsResourceAccessorHelper rah = new LocalFsResourceAccessorHelper(mediaItemAccessor))
                        using (rah.LocalFsResourceAccessor.EnsureLocalFileSystemAccess())
                        {
                            if (MKV_EXTENSIONS.Contains(ResourcePathHelper.GetExtension(mediaItemLocator.NativeResourcePath.FileName)))
                            {
                                await ExtractMkvFanArt(rah.LocalFsResourceAccessor, mediaItemId, title).ConfigureAwait(false);
                            }
                            if (MP4_EXTENSIONS.Contains(ResourcePathHelper.GetExtension(mediaItemLocator.NativeResourcePath.FileName)))
                            {
                                await ExtractTagFanArt(rah.LocalFsResourceAccessor, mediaItemId, title).ConfigureAwait(false);
                            }

                            //Don't create thumbs if they already exist or if it is a movie (they use posters)
                            var thumbs = ServiceRegistration.Get <IFanArtCache>().GetFanArtFiles(mediaItemId, FanArtTypes.Thumbnail);
                            if (!thumbs.Any() && !aspects.ContainsKey(ThumbnailLargeAspect.ASPECT_ID) && !aspects.ContainsKey(MovieAspect.ASPECT_ID))
                            {
                                await ExtractThumbnailFanArt(rah.LocalFsResourceAccessor, mediaItemId, title, aspects);
                            }
                        }
            }
            catch (Exception ex)
            {
                Logger.Warn("VideoFanArtHandler: Exception while reading MKV tag images for '{0}'", ex, mediaItemLocator.NativeResourcePath);
            }
        }
        /// <summary>
        /// Gets all collection folder images and caches them in the <see cref="IFanArtCache"/> service.
        /// </summary>
        /// <param name="mediaItemLocator"><see cref="IResourceLocator>"/> that points to the file.</param>
        /// <param name="collectionMediaItemId">Id of the series media item.</param>
        /// <param name="title">Title of the media item.</param>
        /// <returns><see cref="Task"/> that completes when the images have been cached.</returns>
        protected async Task ExtractCollectionFolderFanArt(IResourceLocator mediaItemLocator, Guid collectionMediaItemId, string title)
        {
            var collectionDirectory         = ResourcePathHelper.Combine(mediaItemLocator.NativeResourcePath, "../../");
            var centralCollectionDirectory  = ResourcePathHelper.Combine(mediaItemLocator.NativeResourcePath, "../../../" + MOVIESET_FANART_FOLDER);
            var centralCollectionDirectory2 = ResourcePathHelper.Combine(mediaItemLocator.NativeResourcePath, "../../" + MOVIESET_FANART_FOLDER);
            var movieDirectory = ResourcePathHelper.Combine(mediaItemLocator.NativeResourcePath, "../");

            try
            {
                FanArtPathCollection paths = new FanArtPathCollection();
                using (IResourceAccessor accessor = new ResourceLocator(mediaItemLocator.NativeSystemId, centralCollectionDirectory).CreateAccessor())
                    paths.AddRange(GetCollectionFolderFanArt(accessor as IFileSystemResourceAccessor));
                using (IResourceAccessor accessor = new ResourceLocator(mediaItemLocator.NativeSystemId, centralCollectionDirectory2).CreateAccessor())
                    paths.AddRange(GetCollectionFolderFanArt(accessor as IFileSystemResourceAccessor));
                using (IResourceAccessor accessor = new ResourceLocator(mediaItemLocator.NativeSystemId, collectionDirectory).CreateAccessor())
                    paths.AddRange(GetCollectionFolderFanArt(accessor as IFileSystemResourceAccessor));
                using (IResourceAccessor accessor = new ResourceLocator(mediaItemLocator.NativeSystemId, movieDirectory).CreateAccessor())
                    paths.AddRange(GetMovieFolderCollectionFanArt(accessor as IFileSystemResourceAccessor));
                await SaveFolderImagesToCache(mediaItemLocator.NativeSystemId, paths, collectionMediaItemId, title).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Logger.Warn("MovieFanArtHandler: Exception while reading folder images for '{0}'", ex, collectionDirectory);
            }
        }
        /// <summary>
        /// Checks whether a property is mapped in the entity type definition
        /// </summary>
        /// <param name="meta">The metadata document</param>
        /// <param name="entityType">The entity type</param>
        /// <param name="propertyName">The property</param>
        /// <param name="mappedTarget">Output parameter of mapped target path</param>
        /// <returns>flag of proerty being mapped</returns>
        private static bool PropertyIsMapped(XElement meta, string entityType, string propertyName, out string mappedTarget)
        {
            const string tmplXPath2EntityType = @"//*[local-name()='EntityType' and @Name = '{0}']";
            const string tmplXPath2Property   = @"./*[local-name()='Property' and @Name='{0}']";

            string typeShortName = ResourcePathHelper.GetBaseName(entityType);

            mappedTarget = null;

            string xPath2EntityType = string.Format(tmplXPath2EntityType, typeShortName);
            var    nodeEntityType   = meta.XPathSelectElement(xPath2EntityType, ODataNamespaceManager.Instance);

            string xpath2prop   = string.Format(tmplXPath2Property, propertyName);
            var    nodeProperty = nodeEntityType.XPathSelectElement(xpath2prop);

            if (nodeProperty != null)
            {
                string attrFC_KeepInContent = nodeProperty.GetAttributeValue("m:FC_KeepInContent", ODataNamespaceManager.Instance);
                if (!string.IsNullOrEmpty(attrFC_KeepInContent))
                {
                    mappedTarget = nodeProperty.GetAttributeValue("m:FC_TargetPath", ODataNamespaceManager.Instance);
                    return(!Convert.ToBoolean(attrFC_KeepInContent));
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                string baseType = nodeEntityType.GetAttributeValue("BaseType");
                return(PropertyIsMapped(meta, baseType, propertyName, out mappedTarget));
            }
        }
        /// <summary>
        /// Verifies the semantic rule
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            info = null;
            bool?  passed             = null;
            string odataVersionString = "DataServiceVersion";

            if (context.Version == ODataVersion.V4)
            {
                odataVersionString = "OData-Version";
            }

            //to get the DSV defined in metadata document
            XElement meta  = XElement.Parse(context.MetadataDocument);
            string   xpath = @"//*[local-name()='DataServices' and @m:DataServiceVersion]";
            var      ds    = meta.XPathSelectElement(xpath, ODataNamespaceManager.Instance);

            if (ds != null)
            {
                string dsvInResp = context.ResponseHttpHeaders.GetHeaderValue(odataVersionString);
                string dsvInMeta = ds.GetAttributeValue("m:DataServiceVersion", ODataNamespaceManager.Instance);

                if (!string.IsNullOrEmpty(dsvInResp) && !string.IsNullOrEmpty(dsvInMeta))
                {
                    string dsv     = GetBiggerDSV(ResourcePathHelper.GetMajorHeaderValue(dsvInMeta), ResourcePathHelper.GetMajorHeaderValue(dsvInResp));
                    var    headers = new List <KeyValuePair <string, string> > {
                        new KeyValuePair <string, string>(odataVersionString, dsv + VersionClientUserAgent)
                    };

                    var resp = WebResponseHelper.GetWithHeaders(context.Destination,
                                                                context.PayloadFormat == RuleEngine.PayloadFormat.Json,
                                                                headers,
                                                                RuleEngineSetting.Instance().DefaultMaximumPayloadSize,
                                                                context);

                    //to approximate with checking with status code and responded DSV
                    if (context.HttpStatusCode != resp.StatusCode)
                    {
                        passed = false;
                        info   = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, resp.StatusCode.ToString());
                    }
                    else
                    {
                        var DsvOld = context.ResponseHttpHeaders.GetHeaderValue(odataVersionString);
                        var DsvNew = resp.ResponseHeaders.GetHeaderValue(odataVersionString);
                        passed = DsvOld == DsvNew;
                        if (!passed.Value)
                        {
                            info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, resp.ResponsePayload);
                        }
                    }
                }
            }

            return(passed);
        }
示例#13
0
        /// <summary>
        /// Verify the code rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;

            var path     = context.DestinationBasePath.Substring(context.ServiceBaseUri.AbsoluteUri.Length);
            var segments = ResourcePathHelper.GetPathSegments(path).ToArray();

            if (segments.Length > 0)
            {
                string lastSeg = segments[segments.Length - 1];
                if (lastSeg.Equals("$value", StringComparison.Ordinal))
                {
                    var ct = context.ResponseHttpHeaders.GetContentTypeValue();
                    HttpHeaderRegexVerifier verifier = new HttpHeaderRegexVerifier("Content-Type", "\\s*text/plain\\b.*");
                    TestResult tr;
                    passed = verifier.Verify(context, out tr);
                    if (passed.HasValue && !passed.Value)
                    {
                        info = new ExtensionRuleViolationInfo("unexpected Content-Type header value", context.Destination, ct);
                    }
                }
            }

            return(passed);
        }
        /// <summary>
        /// Gets all season folder images and caches them in the <see cref="IFanArtCache"/> service.
        /// </summary>
        /// <param name="mediaItemLocator"><see cref="IResourceLocator>"/> that points to the file.</param>
        /// <param name="seasonMediaItemId">Id of the season media item.</param>
        /// <param name="title">Title of the media item.</param>
        /// <param name="seasonNumber">Season number.</param>
        /// <param name="actors">Collection of actor ids and names.</param>
        /// <returns><see cref="Task"/> that completes when the images have been cached.</returns>
        protected async Task ExtractSeasonFolderFanArt(IResourceLocator mediaItemLocator, Guid seasonMediaItemId, string title, int?seasonNumber, IList <Tuple <Guid, string> > actors)
        {
            var seasonDirectory = ResourcePathHelper.Combine(mediaItemLocator.NativeResourcePath, "../");

            try
            {
                FanArtPathCollection paths = null;
                IList <ResourcePath> potentialActorImages = null;
                using (IResourceAccessor accessor = new ResourceLocator(mediaItemLocator.NativeSystemId, seasonDirectory).CreateAccessor())
                    if (accessor is IFileSystemResourceAccessor fsra)
                    {
                        paths = GetSeasonFolderFanArt(fsra, seasonNumber);
                        //See if there's an actor fanart directory and try and get any actor fanart
                        if (actors != null && actors.Count > 0 && fsra.ResourceExists(".actors"))
                        {
                            using (IFileSystemResourceAccessor actorsDirectory = fsra.GetResource(".actors"))
                                potentialActorImages = LocalFanartHelper.GetPotentialFanArtFiles(actorsDirectory);
                        }
                    }

                if (paths != null)
                {
                    await SaveFolderImagesToCache(mediaItemLocator.NativeSystemId, paths, seasonMediaItemId, title).ConfigureAwait(false);
                }
                if (potentialActorImages != null)
                {
                    await SavePersonFolderImages(mediaItemLocator.NativeSystemId, potentialActorImages, actors).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                Logger.Warn("SeriesFanArtHandler: Exception while reading folder images for '{0}'", ex, seasonDirectory);
            }
        }
示例#15
0
        /// <summary>
        /// Verify rule logic
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out parameter to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;
            string odataVersionString = "DataServiceVersion";

            if (context.Version == ODataVersion.V4)
            {
                odataVersionString = "OData-Version";
            }

            if (!ToElevateResponseVersion(context))
            {
                // for any entity type in the response payload
                // to get its type definition and check if it has any property mapping
                HashSet <string> entityTypes = new HashSet <string>();
                const string     xpath       = @"//*[local-name()='category' and @term]";
                XElement         payload     = XElement.Parse(context.ResponsePayload);
                var ets = payload.XPathSelectElements(xpath, ODataNamespaceManager.Instance);
                foreach (var et in ets)
                {
                    entityTypes.Add(et.GetAttributeValue("term"));
                }

                bool hasPropertyMapping = false;

                if (entityTypes.Any())
                {
                    XElement meta = XElement.Parse(context.MetadataDocument);
                    foreach (var et in entityTypes)
                    {
                        hasPropertyMapping = ResourcePathHelper.HasPropertyMapping(meta, et);
                        if (hasPropertyMapping)
                        {
                            break;
                        }
                    }
                }

                if (!hasPropertyMapping)
                {
                    var    dsvInResp    = context.ResponseHttpHeaders.GetHeaderValue(odataVersionString);
                    var    majorVersion = ResourcePathHelper.GetMajorHeaderValue(dsvInResp);
                    Double version      = Convert.ToDouble(majorVersion);
                    passed = version == 1.0;
                    if (!passed.Value)
                    {
                        info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, dsvInResp);
                    }
                }
            }

            return(passed);
        }
示例#16
0
        /// <summary>
        /// Tries to find an album nfo-file for the given <param name="mediaFsra"></param>
        /// </summary>
        /// <param name="miNumber">Unique number for logging purposes</param>
        /// <param name="mediaFsra">FileSystemResourceAccessor for which we search an album nfo-file</param>
        /// <param name="albumNfoFsra">FileSystemResourceAccessor of the album nfo-file or <c>null</c> if no album nfo-file was found</param>
        /// <returns><c>true</c> if an album nfo-file was found, otherwise <c>false</c></returns>
        protected bool TryGetAlbumNfoSResourceAccessor(long miNumber, IFileSystemResourceAccessor mediaFsra, out IFileSystemResourceAccessor albumNfoFsra)
        {
            albumNfoFsra = null;

            // Determine the directory, in which we look for the album nfo-file
            // We cannot use mediaFsra.GetResource, because for ChainedResourceProviders the parent directory
            // may be located in the ParentResourceProvider. For details see the comments for the ResourcePathHelper class.

            // First get the ResourcePath of the parent directory
            // The parent directory is
            // - for an IFilesystemResourceAcessor pointing to a file:
            //   the directory in which the file is located;
            // - for an IFilesystemResourceAcessor pointing to a root directory of a ChainedResourceProvider (e.g. in case of a DVD iso-file):
            //   the directory in which the file that was unfolded by the ChainedResourceProvider is located;
            // - for an IFilesystemResourceAcessor pointing to any other directory (e.g. DVD directories):
            //   the parent directory of such directory.
            var albumNfoDirectoryResourcePath = ResourcePathHelper.Combine(mediaFsra.CanonicalLocalResourcePath, "../");

            _debugLogger.Info("[#{0}]: album nfo-directory: '{1}'", miNumber, albumNfoDirectoryResourcePath);

            // Then try to create an IFileSystemResourceAccessor for this directory
            IResourceAccessor albumNfoDirectoryRa;

            albumNfoDirectoryResourcePath.TryCreateLocalResourceAccessor(out albumNfoDirectoryRa);
            var albumNfoDirectoryFsra = albumNfoDirectoryRa as IFileSystemResourceAccessor;

            if (albumNfoDirectoryFsra == null)
            {
                _debugLogger.Info("[#{0}]: Cannot extract metadata; album nfo-directory not accessible'", miNumber, albumNfoDirectoryResourcePath);
                if (albumNfoDirectoryRa != null)
                {
                    albumNfoDirectoryRa.Dispose();
                }
                return(false);
            }

            // Finally try to find an episode nfo-file in that directory
            using (albumNfoDirectoryFsra)
            {
                var albumNfoFileNames = GetAlbumNfoFileNames();
                foreach (var albumNfoFileName in albumNfoFileNames)
                {
                    if (albumNfoDirectoryFsra.ResourceExists(albumNfoFileName))
                    {
                        _debugLogger.Info("[#{0}]: album nfo-file found: '{1}'", miNumber, albumNfoFileName);
                        albumNfoFsra = albumNfoDirectoryFsra.GetResource(albumNfoFileName);
                        return(true);
                    }
                    else
                    {
                        _debugLogger.Info("[#{0}]: album nfo-file '{1}' not found; checking next possible file...", miNumber, albumNfoFileName);
                    }
                }
            }

            _debugLogger.Info("[#{0}]: Cannot extract metadata; No album nfo-file found", miNumber);
            return(false);
        }
        /// <summary>
        /// Verify the code rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out parameter to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;

            //1-get the data service namespace name (try 1st property?)
            string dsns = ResourcePathHelper.GetDataServiceNamespace(XElement.Parse(context.ResponsePayload));

            //2-get names of the properties of the involved entity type
            // ensure they are all unique to protect from repetitive type inheritance declarations in metadata documents
            string[] propertyNames = XmlHelper.GetProperties(context.MetadataDocument, context.EntityTypeShortName).Distinct().ToArray();

            if (context.Projection)
            {
                List <string> aa      = new List <string>();
                var           queries = HttpUtility.ParseQueryString(context.Destination.Query);
                var           qSelect = queries["$select"];
                var           selects = qSelect.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var sel in selects)
                {
                    var propName = propertyNames.FirstOrDefault(x => sel.Equals(x, StringComparison.OrdinalIgnoreCase));
                    if (!string.IsNullOrEmpty(propName))
                    {
                        aa.Add(propName);
                    }
                }
                propertyNames = aa.ToArray();
            }

            //3-craft the rng
            StringBuilder sb = new StringBuilder();

            foreach (var p in propertyNames)
            {
                sb.AppendFormat(rngProperty, p);
            }
            string schema = string.Format(rngSchema, dsns, sb.ToString());

            //4-surrender it under rng validator
            RngVerifier verifier = new RngVerifier(schema);
            TestResult  result;

            passed = verifier.Verify(context, out result);

            if (passed.Value)
            {
                info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, result.LineNumberInError);
            }

            return(passed);
        }
        /// <summary>
        /// Gets the raw value of the property of the entry
        /// </summary>
        /// <param name="context">The context object which directly or indirectly points to an entry </param>
        /// <param name="property">The property name</param>
        /// <returns>The raw value returned from the remote service</returns>
        private static string GetRawValueOfProperty(ServiceContext context, string property, ServiceContext ctx)
        {
            var edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            var segments   = ResourcePathHelper.GetPathSegments(context);
            var segs       = ResourcePathHelper.GetEntryUriSegments(segments.Take(segments.Count() - 1), edmxHelper);
            Uri uriEntry   = new Uri(context.ServiceBaseUri, string.Join("/", segs) + "/");

            return(GetProperty(uriEntry, property, ctx));
        }
示例#19
0
        /// <summary>
        /// Gets all artist folder images and caches them in the <see cref="IFanArtCache"/> service.
        /// </summary>
        /// <param name="nativeSystemId">The native system id of the media item.</param>
        /// <param name="albumDirectory"><see cref="ResourcePath>"/> that points to the album directory.</param>
        /// <param name="albumMediaItemId">Id of the media item.</param>
        /// <param name="title">Title of the media item.</param>
        /// <param name="artists">List of artists.</param>
        /// <returns><see cref="Task"/> that completes when the images have been cached.</returns>
        protected async Task ExtractArtistFolderFanArt(string nativeSystemId, ResourcePath albumDirectory, IList <Tuple <Guid, string> > artists)
        {
            if (artists == null || artists.Count == 0)
            {
                return;
            }

            //Get the file's directory
            var artistDirectory = ResourcePathHelper.Combine(albumDirectory, "../");

            try
            {
                var artist = artists.FirstOrDefault(a => string.Compare(a.Item2, artistDirectory.FileName, StringComparison.OrdinalIgnoreCase) == 0);
                if (artist == null)
                {
                    artist = artists[0];
                }

                //See if we've already processed this artist
                if (!AddToCache(artist.Item1))
                {
                    return;
                }

                //Get all fanart paths in the current directory
                FanArtPathCollection paths = new FanArtPathCollection();
                using (IResourceAccessor accessor = new ResourceLocator(nativeSystemId, artistDirectory).CreateAccessor())
                {
                    foreach (var path in GetArtistFolderFanArt(accessor as IFileSystemResourceAccessor))
                    {
                        paths.AddRange(path.Key, path.Value);
                    }
                }

                //Find central artist information folder
                ResourcePath centralArtistFolderPath = LocalFanartHelper.GetCentralPersonFolder(artistDirectory, CentralPersonFolderType.AudioArtists);
                if (centralArtistFolderPath != null)
                {
                    // First get the ResourcePath of the central directory
                    var artistFolderPath = ResourcePathHelper.Combine(centralArtistFolderPath, $"{LocalFanartHelper.GetSafePersonFolderName(artist.Item2)}/");
                    using (IResourceAccessor accessor = new ResourceLocator(nativeSystemId, artistFolderPath).CreateAccessor())
                    {
                        foreach (var path in GetArtistFolderFanArt(accessor as IFileSystemResourceAccessor))
                        {
                            paths.AddRange(path.Key, path.Value);
                        }
                    }
                }

                //Save the fanart to the IFanArtCache service
                await SaveFolderImagesToCache(nativeSystemId, paths, artist.Item1, artist.Item2).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Logger.Warn("AudioFanArtHandler: Exception while reading folder images for '{0}'", ex, artistDirectory);
            }
        }
示例#20
0
        /// <summary>
        /// Verifies the semantic rule
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            info = null;
            bool passed = true;

            // if query option of $expand is present, rule shall be verified
            // get the leftmost navigation property of expand query option
            var    qs      = HttpUtility.ParseQueryString(context.Destination.Query);
            string qExpand = qs["$expand"];

            if (!string.IsNullOrEmpty(qExpand))
            {
                var        edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
                EntityType et;
                edmxHelper.TryGetItem(context.EntityTypeFullName, out et);

                var     segments = ResourcePathHelper.GetPathSegments(context);
                UriType uriType;
                var     target = edmxHelper.GetTargetType(segments, out uriType);
                bool    isColletcionResource = uriType == UriType.URI1 || uriType == UriType.URI_CollEt;

                var branches = ResourcePathHelper.GetBranchedSegments(qExpand);
                foreach (var paths in branches)
                {
                    var    navStack           = ODataUriAnalyzer.GetNavigationStack(et, paths).ToArray();
                    bool[] targetIsCollection = (from n in navStack select n.RelationshipMultiplicity == RelationshipMultiplicity.Many).ToArray();

                    string rngCore = @"<ref name=""anyContent"" />";
                    for (int i = paths.Length - 1; i >= 0; i--)
                    {
                        rngCore = targetIsCollection[i] ? GetRngOfInlineFeed(paths[i], rngCore) : GetRngOfInlineEntry(paths[i], rngCore);
                    }

                    // construct the desired srng schema and verify
                    string rngSchema = isColletcionResource
                        ? string.Format(formatRngOfColl, rngCore, RngCommonPattern.CommonPatterns)
                        : string.Format(formatRngSingle, rngCore, RngCommonPattern.CommonPatterns);

                    RngVerifier verifier = new RngVerifier(rngSchema);
                    TestResult  result;
                    passed = verifier.Verify(context, out result);
                    if (!passed)
                    {
                        info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, result.LineNumberInError);
                        break;
                    }
                }
            }

            return(passed);
        }
示例#21
0
        private void UpdateIconsList()
        {
            var path = ResourcePathHelper.GetIconsPath() + cboIconCollection.Text;

            iconControl1.ChooseIconCellSize(path);

            UpdateCopyrightMessage(path);

            iconControl1.FilePath = path;
        }
        public void ItShouldComputeTheResourcePath()
        {
            var path = ResourcePathHelper.ComputeBasePath(Assembly, BaseName);

            var expectedPath = BaseName
                               .Replace(Assembly.GetName().Name + ".", string.Empty, StringComparison.Ordinal)
                               .Replace('.', '/');

            Assert.Equal(expectedPath, path);
        }
示例#23
0
        /// <summary>
        /// Verify the code rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;

            var     segments   = ResourcePathHelper.GetPathSegments(context).ToArray();
            var     edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            UriType uriType;
            var     target = edmxHelper.GetTargetType(segments, out uriType);

            if (uriType == UriType.URI4 || uriType == UriType.URI5)
            {
                passed = false;
                string  targetType = ((EdmProperty)target).TypeUsage.EdmType.FullName;
                string  property   = segments.LastOrDefault(s => !s.StartsWith("$"));
                JObject jo         = JObject.Parse(context.ResponsePayload);
                var     inner      = jo.ReachInnerToken();
                if (inner.Type == JTokenType.Object)
                {
                    JObject innerObj = (JObject)inner;
                    if (innerObj.Properties() != null && innerObj.Properties().Count() == 1)
                    {
                        var    value        = innerObj.Properties().First().Value;
                        string valueLiteral = value.ToString();

                        IEdmType type = EdmTypeManager.GetEdmType(targetType);

                        bool isValidJsonData = type.IsGoodInJsonWith(valueLiteral);
                        if (isValidJsonData)
                        {
                            passed = true;
                        }
                        else
                        {
                            // target type may allow null
                            //TODO: allow null only when the target type is nullable
                            passed = valueLiteral.Equals("null", StringComparison.Ordinal);
                        }
                    }
                }
            }

            if (passed.HasValue && !passed.Value)
            {
                info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, -1);
            }

            return(passed);
        }
        ///<inheritdoc/>
        public async ValueTask <IReadOnlyDictionary <string, string>?> TryLoadAsync(
            HttpHostedJsonLocalizationOptions options,
            Assembly assembly,
            string baseName,
            CultureInfo cultureInfo)
        {
            if (assembly == null)
            {
                throw new ArgumentNullException(nameof(assembly));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var assemblyName = assembly.GetName().Name;

            var rootPath = (options.ApplicationAssembly == assembly)
                ? string.Empty
                : $"_content/{assemblyName}/";

            if (!string.IsNullOrEmpty(options.ResourcesPath))
            {
                rootPath = $"{rootPath}{options.ResourcesPath}/";
            }

            var basePath = $"{rootPath}{ResourcePathHelper.ComputeBasePath(assembly, baseName)}";

            return(await CultureInfoHelper.WalkThoughCultureInfoParentsAsync(cultureInfo,
                                                                             cultureName =>
            {
                var uri = string.IsNullOrEmpty(cultureName)
                    ? new Uri($"{basePath}.json", UriKind.Relative)
                    : new Uri($"{basePath}{options.CultureSeparator}{cultureName}.json", UriKind.Relative);

                this.logger.LogDebug($"Loading static assets data from {uri}");

                lock (Cache)
                {
                    if (!Cache.TryGetValue(uri, out var loadingTask))
                    {
                        loadingTask = TryLoadFromUriAsync(uri, options.JsonSerializerOptions);
                        Cache.Add(uri, loadingTask);
                    }
                    else if (loadingTask.IsFaulted)
                    {
                        loadingTask = TryLoadFromUriAsync(uri, options.JsonSerializerOptions);
                        Cache[uri] = loadingTask;
                    }
                    return loadingTask;
                }
            })
                   .ConfigureAwait(false));
        }
        /// <summary>
        /// Verifies the semantic rule
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out paramater to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool passed = true;

            info = null;

            // check there is only one segement in the relative path (after the service root uri)
            // ensure the segment is a URI-2
            string path;

            if (ResourcePathHelper.IsOneSegmentPath(context, out path))
            {
                if (RegexInUri.IsURI2(path, XElement.Parse(context.MetadataDocument)))
                {
                    // fetch the .../$count resource
                    Uri target = new Uri(context.DestinationBasePath + "/$count");
                    var resp   = WebResponseHelper.GetWithHeaders(
                        target,
                        false,  // $count response cannot be application/json Content-Type
                        null,
                        RuleEngineSetting.Instance().DefaultMaximumPayloadSize,
                        context);

                    if (resp.StatusCode.HasValue)
                    {
                        var  code = resp.StatusCode.Value;
                        bool isNonExistentCode = (code == System.Net.HttpStatusCode.NotFound) || (code == System.Net.HttpStatusCode.Gone);
                        if (isNonExistentCode)
                        {
                            passed = true;
                        }
                        else
                        {
                            passed = false;
                            info   = new ExtensionRuleViolationInfo("unexpected status code", target, code.ToString());
                        }
                    }
                    else
                    {
                        passed = false;
                        info   = new ExtensionRuleViolationInfo("no status code", target, null);
                    }
                }
            }

            return(passed);
        }
        /// <summary>
        /// Verify the rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;

            var    qs        = HttpUtility.ParseQueryString(context.Destination.Query);
            string qExpand   = qs["$expand"];
            var    branches  = ResourcePathHelper.GetBranchedSegments(qExpand);
            var    brHeaders = from br in branches select br.FirstOrDefault();

            // to get collection of navigatio properties which is not expanded
            List <string> navProps = new List <string>();
            XElement      meta     = XElement.Parse(context.MetadataDocument);
            const string  fmtXPathToTypeProperty = "//*[local-name()='Schema' and @Namespace='{0}']/*[local-name()='EntityType' and @Name='{1}']/*[local-name()='NavigationProperty' and @Name]";
            string        xpath = string.Format(fmtXPathToTypeProperty, ResourcePathHelper.GetNamespaceName(context.EntityTypeFullName), ResourcePathHelper.GetBaseName(context.EntityTypeFullName));
            var           nodes = meta.XPathSelectElements(xpath);

            foreach (var n in nodes)
            {
                var name = ResourcePathHelper.GetBaseName(n.Attribute("Name").Value);
                if (!brHeaders.Any(x => x.Equals(name, StringComparison.Ordinal)))
                {
                    navProps.Add(name);
                }
            }

            if (navProps.Count() > 0)
            {
                JObject jo      = JObject.Parse(context.ResponsePayload);
                var     version = JsonParserHelper.GetPayloadODataVersion(jo);

                var    propSchemas    = navProps.Select(x => string.Format(fmtCore, x));
                string coreProperties = string.Join("\r\n,", propSchemas);
                string CoreObject     = string.Format(fmtObj, coreProperties);
                string jSchema        = JsonSchemaHelper.WrapJsonSchema(CoreObject, version);

                TestResult result;
                passed = JsonParserHelper.ValidateJson(jSchema, context.ResponsePayload, out result);
                if (!passed.HasValue)
                {
                    info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, result != null ? result.LineNumberInError : -1);
                }
            }

            return(passed);
        }
 public string CreateRootDirectory(string rootDirectoryName)
 {
     lock (_syncObj)
     {
         ResourcePath rootPath = RootPath;
         if (rootPath == null)
         {
             return(null);
         }
         _dokanExecutor.RootDirectory.AddResource(rootDirectoryName, new VirtualRootDirectory(rootDirectoryName));
         return(ResourcePathHelper.Combine(rootPath.Serialize(), rootDirectoryName));
     }
 }
示例#28
0
        /// <summary>
        /// Loads categories for output point shapefile.
        /// </summary>
        private static bool LoadSymbology(IFeatureSet fs)
        {
            string filename = ResourcePathHelper.GetStylesPath() + "GeosValidationErrors.xml";

            if (!File.Exists(filename))
            {
                Logger.Current.Warn("Failed to find XML with symbology for error type: " + filename);
                return(false);
            }

            string xml = File.ReadAllText(filename);

            return(fs.Categories.Deserialize(xml));
        }
示例#29
0
        /// <summary>
        /// Returns the path to the specified style file, in case the file doesn't exist - creates it.
        /// </summary>
        private static string GetFilename(SchemeTarget type)
        {
            string path = ResourcePathHelper.GetStylesPath();

            switch (type)
            {
            case SchemeTarget.Vector:
                return(path + "colorschemes.xml");

            case SchemeTarget.Charts:
                return(path + "chartcolorsxml");
            }
            return(string.Empty);
        }
示例#30
0
        /// <summary>
        /// Main process method for the InnerBlock
        /// </summary>
        /// <remarks>
        /// - SingleResources are just passed to the next DataflowBlock
        /// - If it's not a SingleResource
        ///   - it finds all the files in the current directory,
        ///   - in case of a RefreshImport
        ///     - it deletes all the files in the MediaLibrary that do not exist anymore in the filesystem,
        ///     - it stores the DateOfLastImport of all the files in the <see cref="PendingImportResourceNewGen"/>
        /// </remarks>
        /// <param name="importResource"><see cref="PendingImportResourceNewGen"/> to be processed</param>
        /// <returns>
        /// a HashSet of <see cref="PendingImportResourceNewGen"/>s containing the current <see cref="PendingImportResource"/>
        /// after processing as well as <see cref="PendingImportResourceNewGen"/>s for all files in the current directory
        /// </returns>
        private async Task <IEnumerable <PendingImportResourceNewGen> > ProcessChanges(PendingImportResourceNewGen importResource)
        {
            var result = new HashSet <PendingImportResourceNewGen> {
                importResource
            };

            try
            {
                if (ImportJobInformation.JobType == ImportJobType.Refresh)
                {
                    // ReSharper disable once PossibleInvalidOperationException
                    IEnumerable <MediaItem> mediaItems = await GetUpdatableMediaItems(PROVIDERRESOURCE_IMPORTER_MIA_ID_ENUMERATION, null);

                    if (mediaItems != null)
                    {
                        foreach (MediaItem mi in mediaItems)
                        {
                            IList <MultipleMediaItemAspect> providerAspects = null;
                            if (MediaItemAspect.TryGetAspects(mi.Aspects, ProviderResourceAspect.Metadata, out providerAspects))
                            {
                                ResourcePath      path        = ResourcePath.Deserialize(providerAspects[0].GetAttributeValue <String>(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH));
                                Guid?             directoryId = providerAspects[0].GetAttributeValue <Guid?>(ProviderResourceAspect.ATTR_PARENT_DIRECTORY_ID);
                                IResourceAccessor ra;
                                if (path.TryCreateLocalResourceAccessor(out ra) && ra is IFileSystemResourceAccessor)
                                {
                                    IFileSystemResourceAccessor f   = ra as IFileSystemResourceAccessor;
                                    string       dirPath            = ResourcePathHelper.GetDirectoryName(ra.Path);
                                    ResourcePath dirRa              = ResourcePath.BuildBaseProviderPath(ra.ParentProvider.Metadata.ResourceProviderId, dirPath);
                                    PendingImportResourceNewGen pir = new PendingImportResourceNewGen(dirRa, f, ToString(), ParentImportJobController, directoryId, mi.MediaItemId);
                                    pir.DateOfLastImport = DateTime.MinValue; //Force update
                                    result.Add(pir);
                                }
                            }
                        }
                    }
                }
                return(result);
            }
            catch (TaskCanceledException)
            {
                return(result);
            }
            catch (Exception ex)
            {
                ServiceRegistration.Get <ILogger>().Warn("ImporterWorker.{0}.{1}: Error while processing {2}", ex, ParentImportJobController, ToString(), importResource);
                importResource.IsValid = false;
                return(result);
            }
        }