public byte[] GetBinaryByUrl(string url)
        {
            string encodedUrl = HttpUtility.UrlPathEncode(url); // ?? why here? why now?


            IList      metas      = null;
            BinaryMeta binaryMeta = null;

            if (this.PublicationId == 0)
            {
                metas = BinaryMetaFactory.GetMetaByUrl(encodedUrl);
                if (metas.Count == 0)
                {
                    throw new BinaryNotFoundException();
                }
                binaryMeta = metas[0] as BinaryMeta;
            }
            else
            {
                binaryMeta = BinaryMetaFactory.GetMetaByUrl(this.PublicationId, encodedUrl);
                if (binaryMeta == null)
                {
                    throw new BinaryNotFoundException();
                }
            }
            TcmUri uri = new TcmUri(binaryMeta.PublicationId, binaryMeta.Id, 16, 0);

            Tridion.ContentDelivery.DynamicContent.BinaryFactory factory = new BinaryFactory();

            BinaryData binaryData = string.IsNullOrEmpty(binaryMeta.VariantId) ? factory.GetBinary(uri.ToString()) : factory.GetBinary(uri.ToString(), binaryMeta.VariantId);

            return(binaryData == null ? null : binaryData.Bytes);
        }
        public byte[] GetBinaryByUri(string uri)
        {
            Tridion.ContentDelivery.DynamicContent.BinaryFactory factory = new BinaryFactory();
            BinaryData binaryData = factory.GetBinary(uri.ToString());

            return(binaryData == null ? null : binaryData.Bytes);
        }
Ejemplo n.º 3
0
        public void FindBinaryWithoutExtension()
        {
            IBinary binary = BinaryFactory.FindBinary("/media/image");

            Assert.IsNotNull(binary);
            Assert.IsTrue(binary.BinaryData.Length > 100, "byte array is too small, something went wrong");
        }
Ejemplo n.º 4
0
        public void FindBinaryPublishedNoDateAndAlreadyOnFS()
        {
            ((TridionBinaryProvider)BinaryFactory.BinaryProvider).GeneratedImageWidth  = 300;
            ((TridionBinaryProvider)BinaryFactory.BinaryProvider).GeneratedImageHeight = 400;
            int currentBinaryExpiration = TestConfiguration.OverrideBinaryExpiration;

            TestConfiguration.OverrideBinaryExpiration = 0;

            IBinary binary = BinaryFactory.FindBinary("nodate");

            Assert.IsNotNull(binary);
            Assert.IsTrue(binary.BinaryData.Length > 100, "byte array is too small, something went wrong");
            Assert.IsFalse(string.IsNullOrEmpty(binary.Id), "binary.Id is missing");
            Image img = GetImageFromBytes(binary.BinaryData);

            Assert.IsTrue(img.Width == 300);
            Assert.IsTrue(img.Height == 400);

            // change the generated image dimensions in the provider
            // this should NOT affect the results because the binary should be cached
            ((TridionBinaryProvider)BinaryFactory.BinaryProvider).GeneratedImageWidth  = 400;
            ((TridionBinaryProvider)BinaryFactory.BinaryProvider).GeneratedImageHeight = 200;

            binary = BinaryFactory.FindBinary("nodate");
            Assert.IsNotNull(binary);
            Assert.IsTrue(binary.BinaryData.Length > 100, "byte array is too small, something went wrong");
            Assert.IsFalse(string.IsNullOrEmpty(binary.Id), "binary.Id is missing");
            img = GetImageFromBytes(binary.BinaryData);
            Assert.IsTrue(img.Width == 400);
            Assert.IsTrue(img.Height == 200);

            ResetImageDimensions();
            TestConfiguration.OverrideBinaryExpiration = currentBinaryExpiration;
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Main worker method reads binary from Broker and stores it in file-system
        /// </summary>
        /// <returns></returns>
        public bool ProcessRequest(HttpRequest request)
        {
            string urlPath = request.Url.AbsolutePath.Replace("/BinaryData", "");

            LoggerService.Debug("Start processing " + urlPath);
            Dimensions dimensions = null;

            urlPath = StripDimensions(urlPath, out dimensions);

            String   physicalPath      = request.PhysicalPath;
            string   cacheKey          = GetCacheKey(urlPath);
            DateTime?lastPublishedDate = CacheAgent.Load(cacheKey) as DateTime?;


            if (lastPublishedDate == null)
            {
                DateTime lpb = BinaryFactory.FindLastPublishedDate(urlPath);
                if (lpb != DateTime.MinValue.AddSeconds(1)) // this is the secret code for 'does not exist'
                {
                    lastPublishedDate = new DateTime?(lpb);
                    CacheAgent.Store(cacheKey, "Binary", lastPublishedDate);
                }
            }
            if (lastPublishedDate != null)
            {
                if (File.Exists(physicalPath))
                {
                    FileInfo fi = new FileInfo(physicalPath);
                    if (fi.Length > 0)
                    {
                        DateTime fileModifiedDate = File.GetLastWriteTime(physicalPath);
                        if (fileModifiedDate.CompareTo(lastPublishedDate) >= 0)
                        {
                            LoggerService.Debug("binary {0} is still up to date, no action required", urlPath);
                            return(true);
                        }
                    }
                }
            }

            // the normal situation (where a binary is still in Tridion and it is present on the file system already and it is up to date) is now covered
            // Let's handle the exception situations.
            IBinary binary = null;

            try
            {
                BinaryFactory.TryFindBinary(urlPath, out binary);
            }
            catch (BinaryNotFoundException)
            {
                LoggerService.Debug("Binary with url {0} not found", urlPath);
                // binary does not exist in Tridion, it should be removed from the local file system too
                if (File.Exists(physicalPath))
                {
                    DeleteFile(physicalPath);
                }
                return(false);
            }
            return(WriteBinaryToFile(binary, physicalPath, dimensions));
        }
Ejemplo n.º 6
0
        public List <BaseObject> BinarySerialize(ApplicationDataContext applicationDataContext)
        {
            BinaryFactory    factory    = new BinaryFactory("Бинарная");
            BinarySerializer serializer = (BinarySerializer)factory.CreateSerializer();
            string           BinarySerealizedObjects = serializer.Serialize(applicationDataContext.Objects);

            return(serializer.Deserialize(BinarySerealizedObjects));
        }
Ejemplo n.º 7
0
        public void FindBinary()
        {
            IBinary binary = BinaryFactory.FindBinary("/media/image.png");

            Assert.IsNotNull(binary);
            Assert.IsTrue(binary.BinaryData.Length > 100, "byte array is too small, something went wrong");
            Assert.IsFalse(string.IsNullOrEmpty(binary.Id), "binary.Id is missing");
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Gets the cached local file for a given URL path.
        /// </summary>
        /// <param name="urlPath">The URL path.</param>
        /// <param name="localization">The Localization.</param>
        /// <returns>The path to the local file.</returns>
        internal string GetCachedFile(string urlPath, Localization localization)
        {
            string baseDir       = AppDomain.CurrentDomain.BaseDirectory;
            string localFilePath = $"{baseDir}/{localization.BinaryCacheFolder}/{urlPath}";

            using (new Tracer(urlPath, localization, localFilePath))
            {
                Dimensions dimensions;
                urlPath = StripDimensions(urlPath, out dimensions);
                string publicationUri = localization.GetCmUri();

                DateTime lastPublishedDate = SiteConfiguration.CacheProvider.GetOrAdd(
                    urlPath,
                    CacheRegions.BinaryPublishDate,
                    () => GetBinaryLastPublishDate(urlPath, publicationUri)
                    );

                if (lastPublishedDate != DateTime.MinValue)
                {
                    if (File.Exists(localFilePath))
                    {
                        if (localization.LastRefresh.CompareTo(lastPublishedDate) < 0)
                        {
                            //File has been modified since last application start but we don't care
                            Log.Debug("Binary with URL '{0}' is modified, but only since last application restart, so no action required", urlPath);
                            return(localFilePath);
                        }
                        FileInfo fi = new FileInfo(localFilePath);
                        if (fi.Length > 0)
                        {
                            DateTime fileModifiedDate = File.GetLastWriteTime(localFilePath);
                            if (fileModifiedDate.CompareTo(lastPublishedDate) >= 0)
                            {
                                Log.Debug("Binary with URL '{0}' is still up to date, no action required", urlPath);
                                return(localFilePath);
                            }
                        }
                    }
                }

                // Binary does not exist or cached binary is out-of-date
                BinaryMeta binaryMeta = GetBinaryMeta(urlPath, publicationUri);
                if (binaryMeta == null)
                {
                    // Binary does not exist in Tridion, it should be removed from the local file system too
                    if (File.Exists(localFilePath))
                    {
                        CleanupLocalFile(localFilePath);
                    }
                    throw new DxaItemNotFoundException(urlPath, localization.Id);
                }
                BinaryFactory binaryFactory = new BinaryFactory();
                BinaryData    binaryData    = binaryFactory.GetBinary(GetPublicationId(publicationUri), binaryMeta.Id, binaryMeta.VariantId);

                WriteBinaryToFile(binaryData.Bytes, localFilePath, dimensions);
                return(localFilePath);
            }
        }
Ejemplo n.º 9
0
        public void ResizeImageToWidth()
        {
            IBinary binary = BinaryFactory.FindBinary("/media/image_w160.png");

            Assert.IsNotNull(binary);
            Assert.IsTrue(binary.BinaryData.Length > 100, "byte array is too small, something went wrong");
            Assert.IsFalse(string.IsNullOrEmpty(binary.Id), "binary.Id is missing");
            Image img = GetImageFromBytes(binary.BinaryData);

            Assert.IsTrue(img.Width == 160);
            Assert.IsTrue(img.Height == 55);
        }
Ejemplo n.º 10
0
        public void FindAndStoreBinaryWithoutExtension()
        {
            string p = Path.Combine(Path.GetTempPath(), "DD4TMockWebRoot");

            if (!Directory.Exists(p))
            {
                Directory.CreateDirectory(p);
            }
            bool result = BinaryFactory.FindAndStoreBinary("/media/image", Path.Combine(p, "image"));

            Assert.IsTrue(result, "FindAndStoreBinary returned false");
            Assert.IsTrue(File.Exists(Path.Combine(p, "image")), "binary file was not created properly");
        }
Ejemplo n.º 11
0
        public Tuple <byte[], string> GetBinary(ILocalization localization, int binaryId)
        {
            BinaryMeta binaryMeta = GetBinaryMeta(localization, binaryId);

            if (binaryMeta == null)
            {
                throw new DxaItemNotFoundException(binaryId.ToString(), localization.Id);
            }
            BinaryFactory binaryFactory = new BinaryFactory();
            BinaryData    binaryData    = binaryFactory.GetBinary(int.Parse(localization.Id), binaryMeta.Id, binaryMeta.VariantId);

            return(new Tuple <byte[], string>(binaryData.Bytes, binaryMeta.Path));
        }
Ejemplo n.º 12
0
        public Tuple <byte[], string> GetBinary(ILocalization localization, string urlPath)
        {
            // Binary does not exist or cached binary is out-of-date
            BinaryMeta binaryMeta = GetBinaryMeta(localization, urlPath);

            if (binaryMeta == null)
            {
                throw new DxaItemNotFoundException(urlPath, localization.Id);
            }
            BinaryFactory binaryFactory = new BinaryFactory();
            BinaryData    binaryData    = binaryFactory.GetBinary(int.Parse(localization.Id), binaryMeta.Id, binaryMeta.VariantId);

            return(new Tuple <byte[], string>(binaryData.Bytes, binaryMeta.Path));
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Arithmetic operation with two of arguments from two of text box.
 /// </summary>
 /// <param name="sender">
 /// Pressing button activates the event
 /// </param>
 /// <param name="e">
 /// Arguments are being sended
 /// </param>
 private void BinaryOperation(object sender, EventArgs e)
 {
     try
     {
         var calculatorName = ((Button)sender).Name.Substring(6);
         var calculator     = BinaryFactory.CreateBinaryCalculator(calculatorName);
         ValidateAndConvert validateConvert = new ValidateAndConvert();
         var firstArgument  = validateConvert.doubleValidate(txtFirst.Text);
         var secondArgument = validateConvert.doubleValidate(txtSecond.Text);
         txtResult.Text = calculator.Calculate(firstArgument, secondArgument).ToString();
     }
     catch (Exception ex)
     {
         MessageBox.Show("Error: " + ex.ToString());
     }
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Gets the cached local file for a given binary Id.
        /// </summary>
        /// <param name="binaryId">The binary Id.</param>
        /// <param name="localization">The Localization.</param>
        /// <returns>The path to the local file.</returns>
        internal string GetCachedFile(int binaryId, ILocalization localization)
        {
            string baseDir       = AppDomain.CurrentDomain.BaseDirectory;
            string localFilePath = $"{baseDir}/{localization.BinaryCacheFolder}";

            using (new Tracer(binaryId, localization, localFilePath))
            {
                string publicationUri = localization.GetCmUri();

                if (!localization.IsXpmEnabled)
                {
                    try
                    {
                        string[] files = Directory.GetFiles(localFilePath, $"{binaryId}_*",
                                                            SearchOption.TopDirectoryOnly);
                        if (files.Length > 0)
                        {
                            localFilePath = files[0];
                            if (IsCached(() => GetBinaryLastPublishDate(binaryId, localization), localFilePath,
                                         localization))
                            {
                                return(localFilePath);
                            }
                        }
                    }
                    catch (Exception)
                    {
                        // Our binary cache folder probably doesn't exist.
                    }
                }

                // Binary does not exist or cached binary is out-of-date
                BinaryMeta binaryMeta = GetBinaryMeta(binaryId, localization);
                if (binaryMeta == null)
                {
                    throw new DxaItemNotFoundException(binaryId.ToString(), localization.Id);
                }
                BinaryFactory binaryFactory = new BinaryFactory();
                BinaryData    binaryData    = binaryFactory.GetBinary(GetPublicationId(publicationUri), binaryMeta.Id, binaryMeta.VariantId);
                string        ext           = Path.GetExtension(binaryMeta.Path) ?? "";
                localFilePath = $"{localFilePath}/{localization.Id}-{binaryId}{ext}";
                WriteBinaryToFile(binaryData.Bytes, localFilePath, null);
                return(localFilePath);
            }
        }
Ejemplo n.º 15
0
        public void BinaryCacheIsInvalidated()
        {
            MockMessageProvider messageProvider = new MockMessageProvider();

            messageProvider.Start();
            ((DefaultCacheAgent)((FactoryBase)BinaryFactory).CacheAgent).Subscribe(messageProvider);

            ResetImageDimensions();
            TestConfiguration.OverrideBinaryExpiration = 180;
            IBinary binary = BinaryFactory.FindBinary("/media/image.png");

            Assert.IsNotNull(binary);
            Assert.IsTrue(binary.BinaryData.Length > 100, "byte array is too small, something went wrong");
            Assert.IsFalse(string.IsNullOrEmpty(binary.Id), "binary.Id is missing");
            Image img = GetImageFromBytes(binary.BinaryData);

            Assert.IsTrue(img.Width == 320);
            Assert.IsTrue(img.Height == 110);

            ICacheEvent cacheEvent = new CacheEvent()
            {
                Key        = "1:2",
                RegionPath = "Binaries",
                Type       = 0
            };

            messageProvider.BroadcastCacheEvent(cacheEvent);

            // change the generated image dimensions in the provider
            // this should NOT affect the results because the binary should be cached
            ((TridionBinaryProvider)BinaryFactory.BinaryProvider).GeneratedImageWidth  = 400;
            ((TridionBinaryProvider)BinaryFactory.BinaryProvider).GeneratedImageHeight = 200;

            binary = BinaryFactory.FindBinary("/media/image.png");
            Assert.IsNotNull(binary);
            Assert.IsTrue(binary.BinaryData.Length > 100, "byte array is too small, something went wrong");
            Assert.IsFalse(string.IsNullOrEmpty(binary.Id), "binary.Id is missing");
            img = GetImageFromBytes(binary.BinaryData);
            Assert.IsTrue(img.Width == 400);
            Assert.IsTrue(img.Height == 200);

            ResetImageDimensions();
        }
Ejemplo n.º 16
0
        internal static IBinaryFactory GetBinaryFactory(Localization localization)
        {
            lock (_binaryFactories)
            {
                IBinaryFactory binaryFactory;
                if (!_binaryFactories.TryGetValue(localization.LocalizationId, out binaryFactory))
                {
                    IPublicationResolver     publicationResolver     = new PublicationResolver(localization);
                    IProvidersCommonServices providersCommonServices = new ProvidersCommonServices(publicationResolver, _logger, _config);
                    IFactoryCommonServices   factoryCommonServices   = new FactoryCommonServices(publicationResolver, _logger, _config, CreateCacheAgent());
                    binaryFactory = new BinaryFactory(
                        new TridionBinaryProvider(providersCommonServices),
                        factoryCommonServices);
                    _binaryFactories.Add(localization.LocalizationId, binaryFactory);
                }

                return(binaryFactory);
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Gets the cached local file for a given URL path.
        /// </summary>
        /// <param name="urlPath">The URL path.</param>
        /// <param name="localization">The Localization.</param>
        /// <returns>The path to the local file.</returns>
        internal string GetCachedFile(string urlPath, ILocalization localization)
        {
            string baseDir       = AppDomain.CurrentDomain.BaseDirectory;
            string localFilePath = $"{baseDir}/{urlPath}";

            if (File.Exists(localFilePath))
            {
                // If our resource exists on the filesystem we can assume static content that is
                // manually added to web application.
                return(localFilePath);
            }
            // Attempt cache location with fallback to retrieval from CIL. Note we don't check cache
            // when running under XPM
            localFilePath = $"{baseDir}/{localization.BinaryCacheFolder}/{urlPath}";
            using (new Tracer(urlPath, localization, localFilePath))
            {
                Dimensions dimensions;
                urlPath = StripDimensions(urlPath, out dimensions);
                string publicationUri = localization.GetCmUri();
                if (!localization.IsXpmEnabled && File.Exists(localFilePath))
                {
                    if (IsCached(() => GetBinaryLastPublishDate(urlPath, publicationUri), localFilePath, localization))
                    {
                        return(localFilePath);
                    }
                }

                // Binary does not exist or cached binary is out-of-date
                BinaryMeta binaryMeta = GetBinaryMeta(urlPath, publicationUri);
                if (binaryMeta == null)
                {
                    throw new DxaItemNotFoundException(urlPath, localization.Id);
                }
                BinaryFactory binaryFactory = new BinaryFactory();
                BinaryData    binaryData    = binaryFactory.GetBinary(GetPublicationId(publicationUri), binaryMeta.Id, binaryMeta.VariantId);

                WriteBinaryToFile(binaryData.Bytes, localFilePath, dimensions);
                return(localFilePath);
            }
        }
Ejemplo n.º 18
0
        public void FindBinaryPublishedStaleAndAlreadyOnFS()
        {
            if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("APPVEYOR_BUILD_FOLDER")))
            {
                return; // for some unknown reason, this test fails on AppVeyor (we need to look into this but it has a low prio)
            }

            ((TridionBinaryProvider)BinaryFactory.BinaryProvider).GeneratedImageWidth  = 300;
            ((TridionBinaryProvider)BinaryFactory.BinaryProvider).GeneratedImageHeight = 400;
            int currentBinaryExpiration = TestConfiguration.OverrideBinaryExpiration;

            TestConfiguration.OverrideBinaryExpiration = 0;

            IBinary binary = BinaryFactory.FindBinary("/media/image2.png");

            Assert.IsNotNull(binary);
            Assert.IsTrue(binary.BinaryData.Length > 100, "byte array is too small, something went wrong");
            Assert.IsFalse(string.IsNullOrEmpty(binary.Id), "binary.Id is missing");
            Image img = GetImageFromBytes(binary.BinaryData);

            Assert.IsTrue(img.Width == 300, "width is not 300 when image is retrieved for the first time");
            Assert.IsTrue(img.Height == 400, "height is not 400 when image is retrieved for the first time");

            // change the generated image dimensions in the provider
            // this should NOT affect the results because the binary should be cached
            ((TridionBinaryProvider)BinaryFactory.BinaryProvider).GeneratedImageWidth  = 400;
            ((TridionBinaryProvider)BinaryFactory.BinaryProvider).GeneratedImageHeight = 200;

            binary = BinaryFactory.FindBinary("/media/image2.png");
            Assert.IsNotNull(binary, "binary is null");
            Assert.IsTrue(binary.BinaryData.Length > 100, "byte array is too small, something went wrong");
            Assert.IsFalse(string.IsNullOrEmpty(binary.Id), "binary.Id is missing");
            img = GetImageFromBytes(binary.BinaryData);
            Assert.IsTrue(img.Width == 400, "width is not 400 when image is retrieved for the second time");
            Assert.IsTrue(img.Height == 200, "height is not 200 when image is retrieved for the second time");

            ResetImageDimensions();
            TestConfiguration.OverrideBinaryExpiration = currentBinaryExpiration;
        }
        /// <summary>
        /// Gets the cached local file for a given URL path.
        /// </summary>
        /// <param name="urlPath">The URL path.</param>
        /// <param name="localization">The Localization.</param>
        /// <returns>The path to the local file.</returns>
        internal string GetCachedFile(string urlPath, Localization localization)
        {
            string localFilePath = GetFilePathFromUrl(urlPath, localization);
            using (new Tracer(urlPath, localization, localFilePath))
            {
                Dimensions dimensions;
                urlPath = StripDimensions(urlPath, out dimensions);
                int publicationId = Convert.ToInt32(localization.LocalizationId);

                DateTime lastPublishedDate = SiteConfiguration.CacheProvider.GetOrAdd(
                    urlPath,
                    CacheRegions.BinaryPublishDate,
                    () => GetBinaryLastPublishDate(urlPath, publicationId)
                    );

                if (lastPublishedDate != DateTime.MinValue)
                {
                    if (File.Exists(localFilePath))
                    {
                        if (localization.LastRefresh.CompareTo(lastPublishedDate) < 0)
                        {
                            //File has been modified since last application start but we don't care
                            Log.Debug("Binary with URL '{0}' is modified, but only since last application restart, so no action required", urlPath);
                            return localFilePath;
                        }
                        FileInfo fi = new FileInfo(localFilePath);
                        if (fi.Length > 0)
                        {
                            DateTime fileModifiedDate = File.GetLastWriteTime(localFilePath);
                            if (fileModifiedDate.CompareTo(lastPublishedDate) >= 0)
                            {
                                Log.Debug("Binary with URL '{0}' is still up to date, no action required", urlPath);
                                return localFilePath;
                            }
                        }
                    }
                }

                // Binary does not exist or cached binary is out-of-date
                BinaryMeta binaryMeta = GetBinaryMeta(urlPath, publicationId);
                if (binaryMeta == null)
                {
                    // Binary does not exist in Tridion, it should be removed from the local file system too
                    if (File.Exists(localFilePath))
                    {
                        CleanupLocalFile(localFilePath);
                    }
                    throw new DxaItemNotFoundException(urlPath, localization.LocalizationId);
                }
                BinaryFactory binaryFactory = new BinaryFactory();
                BinaryData binaryData = binaryFactory.GetBinary(publicationId, binaryMeta.Id, binaryMeta.VariantId);

                WriteBinaryToFile(binaryData.Bytes, localFilePath, dimensions);
                return localFilePath;
            }
        }
        public byte[] GetBinaryByUrl(string url)
        {
            string encodedUrl = HttpUtility.UrlPathEncode(url); // ?? why here? why now?


            IList metas = null;
            BinaryMeta binaryMeta = null;
            if (this.PublicationId == 0)
            {
                metas = BinaryMetaFactory.GetMetaByUrl(encodedUrl);
                if (metas.Count == 0)
                {
                    throw new BinaryNotFoundException();
                }
                binaryMeta = metas[0] as BinaryMeta;
            }
            else
            {
                binaryMeta = BinaryMetaFactory.GetMetaByUrl(this.PublicationId, encodedUrl);
                if (binaryMeta == null)
                    throw new BinaryNotFoundException();
            }
            TcmUri uri = new TcmUri(binaryMeta.PublicationId,binaryMeta.Id,16,0);

            Tridion.ContentDelivery.DynamicContent.BinaryFactory factory = new BinaryFactory();

            BinaryData binaryData = string.IsNullOrEmpty(binaryMeta.VariantId) ? factory.GetBinary(uri.ToString()) : factory.GetBinary(uri.ToString(),binaryMeta.VariantId);
            return binaryData == null ? null : binaryData.Bytes;
        }
 public byte[] GetBinaryByUri(string uri)
 {
     Tridion.ContentDelivery.DynamicContent.BinaryFactory factory = new BinaryFactory();
     BinaryData binaryData = factory.GetBinary(uri.ToString());
     return binaryData == null ? null : binaryData.Bytes;
 }
Ejemplo n.º 22
0
        public void ProcessRequest(HttpContext context)
        {
            IBinary binary = null;

            string url   = context.Request.Path;
            Cache  cache = HttpContext.Current.Cache;

            if (cache[url] != null)
            {
                binary = (IBinary)cache[url];
            }
            else
            {
                binary = BinaryFactory.FindBinary(context.Request.Path);
                int cacheSetting = Convert.ToInt32(ConfigurationManager.AppSettings[BinaryHandlerCachingKey]);
                cache.Insert(url, binary, null, DateTime.Now.AddSeconds(cacheSetting), TimeSpan.Zero);
            }

            string etagDate     = "\"" + binary.LastPublishedDate.ToString("s", DateTimeFormatInfo.InvariantInfo) + "\"";
            string incomingEtag = context.Request.Headers["If-None-Match"];

            context.Response.Cache.SetETag(etagDate);
            context.Response.Cache.SetCacheability(HttpCacheability.Public);

            if (etagDate.Equals(incomingEtag))
            {
                context.Response.StatusCode = 304;
                return;
            }

            var localPath = ConvertUrl(context.Request.Path, context);

            if (binary == null)
            {
                // there appears to be no binary present in Tridion
                // now we must check if there is still an (old) cached copy on the local file system
                object fileLock = LockFile(binary.Url);
                lock (fileLock)
                {
                    RemoveFromDB(binary);

                    lock (locks)
                    {
                        locks.Remove(binary.Url);
                    }
                }

                // that's all for us, the file is not on the FS, so
                // the default FileHandler will cause a 404 exception
                context.Response.StatusCode = 404;
                context.Response.End();
                return;
            }

            using (var db = new BinariesEntities())
            {
                bool     exists  = false;
                var      binData = db.Binaries.Where(bin => bin.ComponentUri == binary.Id).FirstOrDefault();
                TimeSpan ts      = TimeSpan.Zero;
                if (binData != null)
                {
                    ts     = binary.LastPublishedDate.Subtract(binData.LastPublishedDate);
                    exists = true;
                }

                if (!exists || ts.TotalMilliseconds > 0)
                {
                    WriteToDb(binary);
                }
            }

            FillResponse(context.Response, binary);
        }
Ejemplo n.º 23
0
        public void BinaryFactoryTest(Type type, string name)
        {
            Type resultType = BinaryFactory.CreateBinaryCalculator(name).GetType();

            Assert.AreEqual(type, resultType);
        }