示例#1
0
        /// <summary>
        /// Called when [deleting].
        /// </summary>
        protected override void OnDeleting()
        {
            base.OnDeleting();

            CatalogRelationDto catalogRelationDto = CatalogContext.Current.GetCatalogRelationDto(PrimaryKeyId.ToString());

            if (catalogRelationDto.CatalogItemAsset.Count > 0)
            {
                for (int i = 0; i < catalogRelationDto.CatalogItemAsset.Count; i++)
                {
                    catalogRelationDto.CatalogItemAsset[i].Delete();
                }

                if (catalogRelationDto.HasChanges())
                {
                    CatalogContext.Current.SaveCatalogRelationDto(catalogRelationDto);
                }
            }

            // Clean Up BlobStorage
            BlobStorageProvider provider = BlobStorage.Providers[BlobStorageProvider];

            if (provider != null)
            {
                BlobInfo blobInfo = provider.GetInfo((Guid)BlobUid);
                if (blobInfo != null)
                {
                    provider.ReleaseStream(blobInfo);
                }
            }
        }
示例#2
0
        /// <summary>
        /// Copies the specified folder element.
        /// </summary>
        /// <param name="folderElement">The folder element.</param>
        /// <param name="newParentId">The parent id.</param>
        public static void Copy(FolderElement folderElement, int parentId)
        {
            FolderElement newElement = null;

            BlobInfo blobInfo    = folderElement.GetBlobInfo();
            BlobInfo blobInfoNew = (BlobInfo)blobInfo.Clone();

            blobInfoNew.Uid = Guid.NewGuid();

            BlobStorageProvider provider = BlobStorage.Providers[folderElement.BlobStorageProvider];

            using (Stream srcStream = provider.ReadStream(blobInfo))
            {
                using (Stream dstStream = provider.CreateStream(blobInfoNew))
                {
                    BlobStreamHelper.WriteToStream(dstStream, srcStream, 0, srcStream.Length);
                    provider.CommitStream(blobInfoNew);
                }
            }

            newElement         = (FolderElement)folderElement.Clone();
            newElement.BlobUid = blobInfoNew.Uid;
            newElement.Save();

            Move(newElement, parentId);
        }
示例#3
0
        public async Task <IList <string> > Put(string filepath)
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                Console.WriteLine(Request.Content.Headers.ContentType.ToString());
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            try
            {
                CloudBlobContainer container = await GetBlobContainer();

                BlobStorageProvider provider = new BlobStorageProvider(container, filepath);
                await Request.Content.ReadAsMultipartAsync(provider);

                ServerUtils.LogTelemetryEvent(User.Identity.Name, "UploadImage");

                return(provider.Urls);
            }
            catch (Exception e)
            {
                return(new List <string>()
                {
                    e.Message
                });
            }
        }
示例#4
0
        /// <summary>
        /// Creates the specified parent id.
        /// </summary>
        /// <param name="parentId">The parent id.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="srcStream">The SRC stream.</param>
        /// <returns></returns>
        public static FolderElement Create(int parentId, string fileName,
                                           Stream srcStream, Guid progressUid)
        {
            FolderElement retVal   = new FolderElement();
            BlobInfo      blobInfo = new BlobInfo(Guid.NewGuid());

            retVal.ParentId = parentId;

            //Try recognize provider from config setings
            BlobStorageProvider provider = BlobStorage.Provider;
            String providerName;
            String contentType = Mediachase.Ibn.Blob.ContentTypeResolver.ContentType.ResolveByPath(fileName);
            long   fileSize    = srcStream.Length;

            if (TryRecognizeStorageProvider(retVal, fileName, contentType,
                                            fileSize, out providerName))
            {
                provider = BlobStorage.Providers[providerName];
            }

            blobInfo.FileName    = fileName;
            blobInfo.Provider    = provider.Name;
            blobInfo.Created     = DateTime.UtcNow;
            blobInfo.ContentSize = fileSize;
            blobInfo.ContentType = contentType;
            //Content type assigned by provider

            //Save blob info to storage
            using (Stream dstStream = provider.CreateStream(blobInfo))
            {
                //BlobStreamHelper.WriteToStream(dstStream, srcStream, 0, fileSize);
                WriteToStream(dstStream, srcStream, 0, fileSize, progressUid);
            }

            provider.CommitStream(blobInfo);

            retVal.BlobStorageProvider = provider.Name;
            retVal.BlobUid             = blobInfo.Uid;
            retVal.Created             = DateTime.UtcNow;
            retVal.Name = blobInfo.FileName;
            if (retVal.Properties.Contains("ContentSize"))
            {
                retVal.Properties["ContentSize"].Value = (Int32)blobInfo.ContentSize;
            }
            if (retVal.Properties.Contains("ContentType"))
            {
                retVal.Properties["ContentType"].Value = blobInfo.ContentType;
            }

            //try
            IFolderElementExtension folderEl = GetCfgFolderElementExtension(blobInfo);

            if (folderEl != null)
            {
                folderEl.Process(retVal);
            }

            retVal.Save();
            return(retVal);
        }
        /// <summary>
        /// Processes the specified element.
        /// </summary>
        /// <param name="element">The element.</param>
        public void Process(FolderElement element)
        {
            element.Card = cardName;
            BlobInfo blobInfo = element.GetBlobInfo();

            if (blobInfo != null)
            {
                BlobStorageProvider provider = BlobStorage.Providers[blobInfo.Provider];
                if (provider != null)
                {
                    using (Stream stream = provider.ReadStream(blobInfo))
                    {
                        try
                        {
                            Image img = Image.FromStream(stream);
                            element.Properties["Width"].Value  = img.Width;
                            element.Properties["Height"].Value = img.Height;
                        }
                        catch (ArgumentException)
                        {
                        }
                    }
                }
            }
        }
示例#6
0
        /// <summary>
        /// Gets the URL.
        /// </summary>
        /// <param name="downloadProfile">The download profile.</param>
        /// <returns></returns>
        public String GetUrl()
        {
            StringBuilder       retVal   = new StringBuilder();
            BlobStorageProvider provider =
                BlobStorage.Providers[this.BlobStorageProvider];

            if ((provider != null) && (this.BlobUid != null))
            {
                // eliminate calls to blobinfo
                //BlobInfo blobInfo = provider.GetInfo((Guid)this.BlobUid);
                //if (blobInfo != null)
                {
                    retVal.Append(GetElementPath("/"));
                    retVal.Append(this.Name);
                    //Read from config add or not HandlerExtension
                    String addHandlerExt = ConfigurationManager.AppSettings["LibraryHandlerExtension"];
                    if (!String.IsNullOrEmpty(addHandlerExt))
                    {
                        retVal.Append(addHandlerExt);
                    }
                }
            }

            return(retVal.ToString());
        }
示例#7
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
            Activity        reply     = activity.CreateReply("Please send your selfie, to participate in the rating.");

            if (activity.Type == ActivityTypes.Message)
            {
                if (activity.Attachments != null && activity.Attachments.Count > 0)
                {
                    var photo = activity.Attachments[0];
                    if (!photo.ContentType.Contains("webp"))
                    {
                        BlobStorageProvider blobProvider = new BlobStorageProvider();
                        var          imageBlob           = blobProvider.SaveImage(photo.ContentUrl, photo.ContentType);
                        FaceProvider faceProvider        = new FaceProvider();
                        var          faces = await faceProvider.GetFaces(imageBlob.Uri.AbsoluteUri);

                        if (faces != null)
                        {
                            reply = activity.CreateReply($"Thanks for your rating! See more results here: http://akvelonrating.azurewebsites.net/");
                            await ImageProcessingService.GetService().Process(imageBlob, faces);

                            var attachments = new List <Attachment>();
                            attachments.Add(new Attachment()
                            {
                                ContentUrl  = imageBlob.Uri.AbsoluteUri,
                                ContentType = photo.ContentType,
                                Name        = photo.Name
                            });
                            reply.Attachments = attachments;
                        }
                        else
                        {
                            await imageBlob.DeleteAsync();

                            reply = activity.CreateReply($"Sorry. Faces were not found.");
                        }
                    }
                    else
                    {
                        reply = activity.CreateReply($"I'm not sure, that you look like this... Please send your selfie, to participate in the rating.");
                    }
                }
                else
                {
                    if (activity.Text.ToLower().Contains("start") || activity.Text.ToLower().Contains("help"))
                    {
                        reply = activity.CreateReply("Hello! I'm Akvelon Emotional Rating bot! I am receiving the photo (selfie) and I am making an assessment of the event in accordance with the emotions on selfie. Send your foto, to participate in the rating.");
                    }
                }
            }

            await connector.Conversations.ReplyToActivityAsync(reply);

            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
示例#8
0
 protected virtual void SaveImage(string imageUrl, Image image, ImageFormat format)
 {
     using (var blobStream = BlobStorageProvider.OpenWrite(imageUrl))
         using (var stream = new MemoryStream())
         {
             image.Save(stream, format);
             stream.Position = 0;
             stream.CopyTo(blobStream);
         }
 }
示例#9
0
        protected virtual async Task <Image> LoadImageAsync(string imageUrl)
        {
            using (var blobStream = BlobStorageProvider.OpenRead(imageUrl))
                using (var stream = new MemoryStream())
                {
                    await blobStream.CopyToAsync(stream);

                    var result = Image.FromStream(stream);
                    return(result);
                }
        }
示例#10
0
        private void SaveImage(CloudBlockBlob imageBlob, Image image)
        {
            BlobStorageProvider blobProvider = new BlobStorageProvider();

            using (Stream stream = new MemoryStream())
            {
                image.Save(stream, ImageFormat.Jpeg);
                stream.Position = 0;
                blobProvider.UpdateBlob(imageBlob, stream);
            }
        }
示例#11
0
        /// <inheritdoc />
        public override bool HasSameLocation(BlobStorageProvider other)
        {
            var otherAureProvider = other as AzureBlobStorageProvider;

            if (otherAureProvider != null)
            {
                return(this.connectionString.Equals(otherAureProvider.connectionString, StringComparison.OrdinalIgnoreCase) &&
                       this.containerName.Equals(otherAureProvider.containerName, StringComparison.OrdinalIgnoreCase) &&
                       this.rootUrl.Equals(otherAureProvider.rootUrl, StringComparison.OrdinalIgnoreCase));
            }

            return(base.HasSameLocation(other));
        }
示例#12
0
        public async Task Put()
        {
            if (!Request.Content.IsMimeMultipartContent("form-data"))
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
            }

            var provider = new BlobStorageProvider(_container);
            await Request.Content.ReadAsMultipartAsync(provider);

            var context = GlobalHost.ConnectionManager.GetHubContext <Hubs.Gallery>();

            context.Clients.All.newPhotosReceived(provider.Urls);
        }
示例#13
0
        /// <summary>
        /// 将获取到的数据写到Blob中
        /// </summary>
        /// <returns></returns>
        private static async Task AddDataToBlobAsync()
        {
            Console.WriteLine("处理小额购买用户");
            string maxPurchaseAmount = ConfigurationManager.AppSettings["MaxPurchaseAmount"];

            Console.WriteLine("当前处理小额为0-" + maxPurchaseAmount + "(包含)分的购买订单用户");
            int i;

            if (!Int32.TryParse(ConfigurationManager.AppSettings["BlobIndex"], out i))
            {
                Console.WriteLine("配置信息中的BlobIndex请输入数字");
                return;
            }
            Console.WriteLine("BlobIndex从" + i + "开始");
            Console.WriteLine("请确定信息,是否继续? y/ n");
            string key = Console.ReadLine();

            if (key != "y")
            {
                return;
            }
            List <AllocationTransfer> allocationTransfers = await GetWaitingAssetAndPurchaseOrderAsync(maxPurchaseAmount);

            CloudBlobContainer blobContainer = await BlobStorageProvider.InitAsync();

            int count = 0;

            foreach (var allocationTransferItem in allocationTransfers)
            {
                if (allocationTransferItem.YemUserProductDtos.Any())
                {
                    await BlobStorageProvider.WriteStateToBlob(blobContainer, "JinYinMao.Business.Assets.Grains.Actors.SmallSyncAssetPoolActor/" + i, allocationTransferItem.ToJson());

                    count++;
                    i++;
                }
            }
            Console.WriteLine("总共处理条数:" + count);
        }
        /// <inheritdoc />
        public override bool HasSameLocation(BlobStorageProvider other)
        {
            var otherAureProvider = other as AzureBlobStorageProvider;
            if (otherAureProvider != null)
                return this.connectionString.Equals(otherAureProvider.connectionString, StringComparison.OrdinalIgnoreCase) &&
                    this.containerName.Equals(otherAureProvider.containerName, StringComparison.OrdinalIgnoreCase) &&
                    this.rootUrl.Equals(otherAureProvider.rootUrl, StringComparison.OrdinalIgnoreCase);

            return base.HasSameLocation(other);
        }
示例#15
0
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"></see> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"></see> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public void ProcessRequest(HttpContext context)
        {
            string libPath = HttpUtility.UrlDecode(context.Request.Url.AbsolutePath);
            string appPath = context.Request.ApplicationPath;

            appPath = appPath.TrimEnd(new char[] { '/' });

            if (!String.IsNullOrEmpty(appPath))
            {
                libPath = libPath.Substring(appPath.Length + 1);
            }

            int index = libPath.LastIndexOf('/');

            if (index != -1)
            {
                String elemName = libPath.Substring(index + 1);
                //remove iis extension from element name
                elemName = elemName.Substring(0, elemName.LastIndexOf('.'));
                libPath  = libPath.Substring(0, index);
                FolderElement[] elements = FolderElement.GetElementsByPath(libPath);

                if (elements != null)
                {
                    foreach (FolderElement element in elements)
                    {
                        /*
                         * if (provider is PublicDiskStorageProvider)
                         *  downloadProfile = BaseBlobProfile.GetAccessProfileByCfgName("iis");
                         * */

                        if (elemName.Equals(element.Name, StringComparison.InvariantCultureIgnoreCase))
                        {
                            try
                            {
                                //"open" - is DonwloadProfile in Web.config
                                BaseBlobProfile downloadProfile = BaseBlobProfile.GetAccessProfileByCfgName("open");

                                //If public disk provider then redirect
                                BlobStorageProvider provider = BlobStorage.Providers[element.BlobStorageProvider];

                                BlobInfo blobInfo     = element.GetBlobInfo();
                                string   profileName  = String.Empty;
                                string   providerName = String.Empty;
                                if (FolderElement.TryRecognizeStorageProvider(element, blobInfo.FileName, blobInfo.ContentType, blobInfo.ContentSize, out providerName, out profileName))
                                {
                                    if (!String.IsNullOrEmpty(profileName))
                                    {
                                        downloadProfile = BaseBlobProfile.GetAccessProfileByCfgName(profileName);
                                    }
                                }

                                String filterName = context.Request[FolderElement.filterParam];

                                //Download filter impl
                                if (!String.IsNullOrEmpty(filterName))
                                {
                                    DownloadFilterBase filter = DownloadFilterBase.GetFilterByCfgName(filterName);
                                    if (filter != null)
                                    {
                                        filter.Initialize(context.Request.Params);
                                        //subscribe to filter event
                                        downloadProfile.FilterEvent += filter.ProcessFilter;
                                    }
                                }

                                //Begin download
                                downloadProfile.ProcessRequest(context, blobInfo);
                            }
                            catch (BlobDownloadException e)
                            {
                                if (e.Code == 204) //No content
                                {
                                    context.Response.ClearContent();
                                    context.Response.AddHeader("Content-Length", "0");
                                }
                                //throw new HttpException(e.Code, e.Message);
                                context.Response.StatusCode        = e.Code;
                                context.Response.StatusDescription = e.Message;
                            }
                        }
                    }
                }
            }
        }
示例#16
0
    /// <summary>
    /// Binds the data.
    /// </summary>
    private void BindData()
    {
        if (DataSource == null)
        {
            this.Visible = false;
            return;
        }

        List <ItemAsset> assets = new List <ItemAsset>();

        if (!String.IsNullOrEmpty(GroupName))
        {
            foreach (ItemAsset asset in DataSource)
            {
                if (asset.GroupName.Equals(GroupName))
                {
                    assets.Add(asset);
                }
            }
        }
        else
        {
            foreach (ItemAsset asset in DataSource)
            {
                assets.Add(asset);
            }
        }

        this.Visible = true;

        List <FolderElement> elements = new List <FolderElement>();

        foreach (ItemAsset asset in assets)
        {
            if (asset.AssetType.Equals("file"))
            {
                FolderElement[] myElements = FolderElement.List <FolderElement>(FolderElement.GetAssignedMetaClass(), new FilterElement[] { new FilterElement("FolderElementId", FilterElementType.Equal, asset.AssetKey) });
                if (myElements.Length > 0)
                {
                    elements.Add(myElements[0]);
                }
            }
            else
            {
                FolderElement[] myElements = FolderElement.List <FolderElement>(FolderElement.GetAssignedMetaClass(), new FilterElement[] { new FilterElement("ParentId", FilterElementType.Equal, asset.AssetKey) });
                if (myElements.Length > 0)
                {
                    foreach (FolderElement myElement in myElements)
                    {
                        elements.Add(myElement);
                    }
                }
            }
        }

        DataTable table = new DataTable();

        table.Columns.Add(new DataColumn("ID", typeof(string)));
        table.Columns.Add(new DataColumn("Name", typeof(string)));
        table.Columns.Add(new DataColumn("Size", typeof(string)));
        table.Columns.Add(new DataColumn("Url", typeof(string)));
        table.Columns.Add(new DataColumn("Filename", typeof(string)));
        table.Columns.Add(new DataColumn("Icon", typeof(string)));
        table.Columns.Add(new DataColumn("Created", typeof(DateTime)));

        foreach (FolderElement element in elements)
        {
            DataRow newRow = table.NewRow();

            newRow["ID"]   = element.PrimaryKeyId.ToString();
            newRow["Name"] = element.Name;

            BlobStorageProvider prov = BlobStorage.Providers[element.BlobStorageProvider];
            BlobInfo            info = prov.GetInfo(new Guid(element.BlobUid.ToString()));

            newRow["FileName"] = info.FileName;
            newRow["Url"]      = String.Format("~{0}", element.GetUrl()); //DownloadFileUrlBuilder.GetUrl("iis", info);
            newRow["Icon"]     = CommonHelper.GetIcon(info.FileName);
            newRow["Created"]  = info.Created;
            newRow["Size"]     = CommerceHelper.ByteSizeToStr(info.ContentSize);

            table.Rows.Add(newRow);
        }

        DownloadsList.DataSource = table;
        DownloadsList.DataBind();
    }
示例#17
0
        public async Task TestStorageRemove(Type storageProviderType)
        {
            IStorageProvider store;

            switch (storageProviderType.Name)
            {
            case nameof(BlobStorageProvider):
                var blobServiceClient = new BlobServiceClient("UseDevelopmentStorage=true");
                var container         = blobServiceClient.GetBlobContainerClient("globalcache");
                await container.CreateIfNotExistsAsync();

                store = new BlobStorageProvider(container);
                break;

            case nameof(FileStorageProvider):
                store = new FileStorageProvider();
                break;

            default:
                throw new NotSupportedException($"{nameof(storageProviderType)} is not supported");
            }

            var id1 = new CacheId("remove", 1);
            var id2 = new CacheId("remove", 2);

            // Write two values
            var val1 = await OpenReadWriteAsync(id1, onWrite : stream => {
                stream.WriteByte(1);
                return(Task.FromResult(1));
            });

            var val2 = await OpenReadWriteAsync(id2, onWrite : stream => {
                stream.WriteByte(2);
                return(Task.FromResult(2));
            });

            // Clear 1 value
            Assert.True(await store.RemoveAsync(id1), "id1 should have been removed");
            await CheckRemoved(id1, 1);

            // Check 2 still exists
            Assert.Equal(val2, await OpenReadWriteAsync(id2, onRead: stream => Task.FromResult(stream.ReadByte())));

            // Clear ALL values
            Assert.True(await store.RemoveAsync(CacheId.ForCategory("remove")), "id1 and id2 should have been removed");
            await CheckRemoved(id2, 2);

            async Task CheckRemoved(CacheId id, byte notExpected)
            {
                try
                {
                    using var cts = new CancellationTokenSource();

                    cts.CancelAfter(TimeSpan.FromMilliseconds(20));

                    var value = await OpenReadWriteAsync(
                        id,
                        onRead : stream => Task.FromResult(stream.ReadByte()),
                        cancellationToken : cts.Token
                        );

                    if (value == notExpected)
                    {
                        throw new Exception($"Item {id} should have been removed");
                    }
                }
                catch (TaskCanceledException)
                {
                    // Pass
                }
            }

            async Task <T> OpenReadWriteAsync <T>(CacheId id,
                                                  Func <Stream, Task <T> >?onWrite    = null,
                                                  Func <Stream, Task <T> >?onRead     = null,
                                                  CancellationToken cancellationToken = default)
示例#18
0
        public async Task TestStorageConcurrence(Type storageProviderType)
        {
            IStorageProvider store;

            switch (storageProviderType.Name)
            {
            case nameof(BlobStorageProvider):
                var blobServiceClient = new BlobServiceClient("UseDevelopmentStorage=true");
                var container         = blobServiceClient.GetBlobContainerClient("globalcache");
                await container.CreateIfNotExistsAsync();

                store = new BlobStorageProvider(container);
                break;

            case nameof(FileStorageProvider):
                store = new FileStorageProvider();
                break;

            default:
                throw new NotSupportedException($"{nameof(storageProviderType)} is not supported");
            }

            var id     = new CacheId("concurrence", 1);
            var str    = "hello world" + Guid.NewGuid();
            var writes = 0;

            await store.RemoveAsync(id);

            await Task.WhenAll(new []
            {
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                store.RemoveAsync(id),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                store.RemoveAsync(id),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                store.RemoveAsync(id),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
                GetOrCreateAsync().ContinueWith(task => Assert.Equal(str, task.Result)),
            });

            // await store.RemoveAsync(id);

            async Task <string> GetOrCreateAsync()
            {
                var retries = new RetryHelper(1, 500, totalMaxDelay: TimeSpan.FromSeconds(60));

                do
                {
                    if (await store.TryOpenRead(id) is Stream readStream)
                    {
                        using (readStream)
                        {
                            using var sr = new StreamReader(readStream);

                            return(await sr.ReadToEndAsync());
                        }
                    }

                    if (await store.TryOpenWrite(id) is StreamWithCompletion writeStream)
                    {
                        using (writeStream)
                        {
                            // !!!!Expensive data generation here!!!!
                            await writeStream.WriteAsync(Encoding.Default.GetBytes(str !));

                            Interlocked.Increment(ref writes);
                            // !!!!
                        }

                        await writeStream;
                        return(str !);
                    }

                    if (await retries.DelayAsync().ConfigureAwait(false) == false)
                    {
                        throw new TimeoutException();
                    }
                }while (true);
            }
        }
        public async Task TestStoreSerializers(Type serializerType, Type storageProviderType)
        {
            IStorageProvider store;

            if (!(Activator.CreateInstance(serializerType) is ISerializationProvider serializer))
            {
                throw new Exception($"{serializerType} is not a serialization provider");
            }

            switch (storageProviderType.Name)
            {
            case nameof(BlobStorageProvider):
                var blobServiceClient = new BlobServiceClient("UseDevelopmentStorage=true");
                var container         = blobServiceClient.GetBlobContainerClient("globalcache");
                await container.CreateIfNotExistsAsync();

                store = new BlobStorageProvider(container);
                break;

            case nameof(FileStorageProvider):
                store = new FileStorageProvider();
                break;

            default:
                throw new NotSupportedException($"{nameof(storageProviderType)} is not supported");
            }

            var id = new CacheId(serializerType.Name, 5);
            await store.RemoveAsync(id);

            // Write data
            var written = await OpenReadWriteAsync(id, onWrite : async stream =>
            {
                // Open database and query data
                var items = new List <string>();

                await foreach (var item in GetData())
                {
                    items.Add(item);
                }

                await serializer.SerializeToStreamAsync(items, stream);

                return(items);
            });

            Assert.NotNull(written);
            Assert.NotEmpty(written);

            // Read data
            var read = await OpenReadWriteAsync(id, onRead : async stream =>
                                                await serializer.DeserializeFromStreamAsync <List <string> >(stream)
                                                );

            Assert.NotNull(read);
            Assert.Equal(written.Count, read.Count);

            for (var i = 0; i < written.Count; ++i)
            {
                Assert.Equal(written[i], read[i]);
            }

            async IAsyncEnumerable <string> GetData()
            {
                for (var i = 0; i < 1000; ++i)
                {
                    await Task.Yield();

                    yield return($"Item {i}");
                }
            }

            async Task <T> OpenReadWriteAsync <T>(CacheId id,
                                                  Func <Stream, Task <T> >?onWrite    = null,
                                                  Func <Stream, Task <T> >?onRead     = null,
                                                  CancellationToken cancellationToken = default)
示例#20
0
 private Image LoadImage(string uri)
 {
     return(Image.FromStream(BlobStorageProvider.GetStreamFromUrl(uri)));
 }
示例#21
0
        protected virtual bool Exists(string imageUrl)
        {
            var blobInfo = BlobStorageProvider.GetBlobInfo(imageUrl);

            return(blobInfo != null);
        }
示例#22
0
 /// <summary>
 /// Processes the request.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="blobInfo">The BLOB info.</param>
 public override void ProcessRequest(HttpContext context, BlobInfo blobInfo)
 {
     this._blobInfo = blobInfo;
     this._provider = BlobStorage.Providers[blobInfo.Provider];
     this.ProcessRequest(context);
 }