public IEnumerable <EVFitting> SelectFitsInShoppingList(string publicID, IImageResolver imageResolver) { EveShoppingContext contexto = new EveShoppingContext(); List <EVFitting> fittings = new List <EVFitting>(); IEnumerable <QFitting> qfittings = (from sl in contexto.eshShoppingLists join slf in contexto.eshShoppingListFittings on sl.shoppingListID equals slf.shoppingListID join f in contexto.eshFittings on slf.fittingID equals f.fittingID join it in contexto.invTypes on f.shipTypeID equals it.typeID join p in contexto.eshPrices on new { sl.tradeHubID, it.typeID } equals new { tradeHubID = p.solarSystemID, p.typeID } where sl.publicID == publicID select new QFitting { Description = f.description, PublicID = f.publicID, FittingID = f.fittingID, Name = f.name, ShipID = f.shipTypeID.Value, ShipName = f.invType.typeName, ShipVolume = f.shipVolume, Units = slf.units, ShipPrice = p.avg, Price = p.avg * slf.units, Volume = f.shipVolume * slf.units, InvType = it }); int tradeHubID = contexto.eshShoppingLists.Where(s => s.publicID == publicID).FirstOrDefault().tradeHubID; LogicaFittings logicaFittings = new LogicaFittings(); return(logicaFittings.MountFittingCommon(contexto, qfittings, imageResolver, tradeHubID)); }
private static void AddFittingHardwareToFittingSummary(IImageResolver imageResolver, EveShoppingContext contexto, EVFitting fit) { var qfittingHardwares = (from sl in contexto.eshShoppingLists join slf in contexto.eshShoppingListFittings on sl.shoppingListID equals slf.shoppingListID join f in contexto.eshFittings on slf.fittingID equals f.fittingID join fh in contexto.eshFittingHardwares on f.fittingID equals fh.fittingID join it in contexto.invTypes on fh.typeID equals it.typeID join mg in contexto.invMarketGroups on it.marketGroupID equals mg.marketGroupID join p in contexto.eshPrices on new { sl.tradeHubID, it.typeID } equals new { tradeHubID = p.solarSystemID, p.typeID } where f.fittingID == fit.ItemID orderby fh.slotID, fh.positionInSlot, fh.invType.typeName select new EVFittingHardware { ItemID = fh.typeID, GroupName = mg.marketGroupName, Name = it.typeName, TotalPrice = fh.units * p.avg, UnitPrice = fh.units, Slot = fh.slotID, SlotName = fh.eshFittingSlot.name, Units = fh.units, Volume = fh.units * it.volume.Value }); foreach (var item in qfittingHardwares) { item.ImageUrl32 = imageResolver.GetImageURL(item.ItemID); fit.FittingHardwares.Add(item); fit.TotalPrice += item.TotalPrice * fit.Units; fit.Volume += item.Volume * fit.Units; } }
public EVFitting SelectFitSummaryByPublicID(string fittingPublicId, IImageResolver imageResolver, int tradeHubID) { EveShoppingContext contexto = new EveShoppingContext(); EVFitting fit = (from f in contexto.eshFittings join it in contexto.invTypes on f.shipTypeID equals it.typeID join p in contexto.eshPrices on new { tradeHubID = tradeHubID, it.typeID } equals new { tradeHubID = tradeHubID, p.typeID } where f.publicID == fittingPublicId select new EVFitting { Description = f.description, ItemID = f.fittingID, Name = f.name, ShipID = f.shipTypeID.Value, ShipName = f.invType.typeName, ShipVolume = f.shipVolume, Units = 1, ShipPrice = p.avg, TotalPrice = p.avg, Volume = f.shipVolume, PublicID = f.publicID }).FirstOrDefault(); fit.ImageUrl32 = imageResolver.GetImageURL(fit.ShipID); LogicaFittings logicaFits = new LogicaFittings(); logicaFits.AddFittingHardwaresToFitting(contexto, imageResolver, tradeHubID, fit); //AddFittingHardwareToFittingSummary(imageResolver, contexto, fit); return(fit); }
public ImageService() { _grooveImageResolver = new GrooveImageResolver(); _lastFmImageResolver = new LastFmImageResolver(); _cacheService = Ioc.Resolve <CacheService>(); }
#pragma warning disable IDE1006 // Naming Styles /// <summary> /// Performs operations upon the current request. /// </summary> /// <param name="context">The current HTTP request context.</param> /// <returns>The <see cref="Task"/>.</returns> public async Task Invoke(HttpContext context) #pragma warning restore IDE1006 // Naming Styles { IDictionary <string, string> commands = this.requestParser.ParseRequestCommands(context); if (commands.Count > 0) { // Strip out any unknown commands. foreach (string command in new List <string>(commands.Keys)) { if (!this.knownCommands.Contains(command)) { commands.Remove(command); } } } await this.options.OnParseCommandsAsync.Invoke( new ImageCommandContext(context, commands, this.commandParser, this.parserCulture)); // Get the correct service for the request. IImageProvider provider = null; foreach (IImageProvider resolver in this.providers) { if (resolver.Match(context)) { provider = resolver; break; } } if ((commands.Count == 0 && provider?.ProcessingBehavior != ProcessingBehavior.All) || provider?.IsValidRequest(context) != true) { // Nothing to do. call the next delegate/middleware in the pipeline await this.next(context); return; } IImageResolver sourceImageResolver = await provider.GetAsync(context); if (sourceImageResolver is null) { // Log the error but let the pipeline handle the 404 // by calling the next delegate/middleware in the pipeline. var imageContext = new ImageContext(context, this.options); this.logger.LogImageResolveFailed(imageContext.GetDisplayUrl()); await this.next(context); return; } await this.ProcessRequestAsync( context, sourceImageResolver, new ImageContext(context, this.options), commands); }
public MarketItem SelectMarketItemByID(string publicID, int id, IImageResolver imageResolver) { EveShoppingContext context = new EveShoppingContext(); var query = (from sl in context.eshShoppingLists join slit in context.eshShoppingListInvTypes on sl.shoppingListID equals slit.shoppingListID join it in context.invTypes on slit.typeID equals it.typeID join p in context.eshPrices on new { sl.tradeHubID, slit.typeID } equals new { tradeHubID = p.solarSystemID, p.typeID } where sl.publicID == publicID && slit.typeID == id select new { ItemID = slit.typeID, Name = it.typeName, Units = slit.units, TotalPrice = p.avg * slit.units, Volume = it.volume.Value * slit.units, ItemType = it }); var qmi = query.FirstOrDefault(); MarketItem mi = new MarketItem() { ItemID = qmi.ItemID, Name = qmi.Name, Units = qmi.Units, TotalPrice = qmi.TotalPrice, UnitPrice = qmi.TotalPrice / qmi.Units, Volume = RepositorioItems.GetVolume(qmi.ItemType) * qmi.Units, ImageUrl32 = imageResolver != null?imageResolver.GetImageURL(qmi.ItemID) : string.Empty }; return(mi); }
public EVListSummary SelectGroupListSummaryPorPublicID(string publicID, IImageResolver imageResolver) { EveShoppingContext contexto = new EveShoppingContext(); eshGroupShoppingList shoppingList = contexto.eshGroupShoppingLists.Where(sl => sl.publicID == publicID).FirstOrDefault(); if (shoppingList == null) { return(null); } EVListSummary summary = new EVListSummary(); summary.Description = shoppingList.description; summary.Name = shoppingList.name; summary.PublicID = shoppingList.publicID; summary.ReadOnlyPublicID = null; summary.ShoppingListID = shoppingList.groupShoppingListID; Dictionary <int, EVFittingHardware> diccHwd = new Dictionary <int, EVFittingHardware>(); //por cada snapshot que tenemos asociado foreach (var snapshot in shoppingList.eshGroupShoppingListSnapshots) { summary.TotalVolume += snapshot.eshSnapshot.totalVolume; foreach (var item in snapshot.eshSnapshot.eshSnapshotInvTypes) { EVFittingHardware efth = null; if (diccHwd.ContainsKey(item.typeID)) { efth = diccHwd[item.typeID]; efth.Volume += item.volume.Value; efth.TotalPrice += item.unitPrice * item.units; efth.Units += item.units; } else { efth = new EVFittingHardware() { Name = item.invType.typeName, ItemID = item.typeID, Units = item.units, Volume = item.volume.Value, UnitVolume = item.volume.Value / item.units, TotalPrice = item.unitPrice * item.units, UnitPrice = item.unitPrice, ImageUrl32 = imageResolver.GetImageURL(item.typeID) }; diccHwd.Add(efth.ItemID, efth); } } } foreach (var item in diccHwd.Values) { summary.Items.Add(item); } return(summary); }
/// <summary> /// Initializes a new instance of the <see cref="MarkdownRenderer"/> class. /// </summary> /// <param name="document">The Document to Render.</param> /// <param name="linkRegister">The LinkRegister, <see cref="MarkdownTextBlock"/> will use itself.</param> /// <param name="imageResolver">The Image Resolver, <see cref="MarkdownTextBlock"/> will use itself.</param> /// <param name="codeBlockResolver">The Code Block Resolver, <see cref="MarkdownTextBlock"/> will use itself.</param> public MarkdownRenderer(MarkdownDocument document, ILinkRegister linkRegister, IImageResolver imageResolver, ICodeBlockResolver codeBlockResolver) : base(document) { LinkRegister = linkRegister; ImageResolver = imageResolver; CodeBlockResolver = codeBlockResolver; DefaultEmojiFont = new FontFamily("Segoe UI Emoji"); }
/// <summary> /// Initializes a new instance of the <see cref="MarkdownRenderer"/> class. /// </summary> /// <param name="document">The Document to Render.</param> /// <param name="linkRegister">The LinkRegister, <see cref="MarkdownTextBlock"/> will use itself.</param> /// <param name="imageResolver">The Image Resolver, <see cref="MarkdownTextBlock"/> will use itself.</param> /// <param name="codeBlockResolver">The Code Block Resolver, <see cref="MarkdownTextBlock"/> will use itself.</param> /// <param name="emojiInlineResolver">The Emoji Inline Resolver, <see cref="MarkdownTextBlock"/> will use itself.</param> public MarkdownRenderer(MarkdownDocument document, ILinkRegister linkRegister, IImageResolver imageResolver, ICodeBlockResolver codeBlockResolver, IEmojiInlineResolver emojiInlineResolver) : base(document) { LinkRegister = linkRegister; ImageResolver = imageResolver; CodeBlockResolver = codeBlockResolver; EmojiInlineResolver = emojiInlineResolver; DefaultEmojiFont = SystemFonts.MessageFontFamily; }
public static async Task loadGameContentAsync() { var pakIndex = await loadPakIndex(); if (pakIndex != null) { instance = new PakImageResolver(pakIndex); gameContentLoaded = true; } }
public void unloadGameContent() { //Clear the path saved in the registry RegistryTools.DeleteSetting(Constants.APPLICATION_NAME, Constants.PAK_FILE_LOCATION_REGISTRY_KEY); if (gameContentLoaded) { gameContentLoaded = false; instance = new LocalImageResolver(); } }
public static async Task loadGameContentAsync(string paksFolderPath) { var pakIndex = await loadPakIndex(paksFolderPath); if (pakIndex != null) { var pakImageResolver = new PakImageResolver(pakIndex, paksFolderPath); await pakImageResolver.loadPakFilesAsync(preloadBitmaps : false); instance = pakImageResolver; gameContentLoaded = true; } }
public async Task loadGameContentAsync(string paksFolderPath) { var pakIndex = await loadPakIndex(paksFolderPath); if (pakIndex == null) { throw new NullReferenceException($"PakIndex is null. Cannot Continue."); } var pakImageResolver = new PakImageResolver(pakIndex !, paksFolderPath); await pakImageResolver.loadPakFilesAsync(preloadBitmaps : false); instance = pakImageResolver; gameContentLoaded = true; RegistryTools.SaveSetting(Constants.APPLICATION_NAME, Constants.PAK_FILE_LOCATION_REGISTRY_KEY, paksFolderPath !); }
/// <summary> /// Performs operations upon the current request. /// </summary> /// <param name="context">The current HTTP request context</param> /// <returns>The <see cref="Task"/></returns> public async Task Invoke(HttpContext context) { IDictionary <string, string> commands = this.requestParser.ParseRequestCommands(context) .Where(kvp => this.knownCommands.Contains(kvp.Key)) .ToDictionary(p => p.Key, p => p.Value); this.options.OnValidate?.Invoke(new ImageValidationContext(context, commands, CommandParser.Instance)); if (!commands.Any()) { // Nothing to do. call the next delegate/middleware in the pipeline await this.next(context); return; } // Create a cache key based on all the components of the requested url string uri = $"{context.Request.Host.ToString().ToLowerInvariant()}/{context.Request.PathBase.ToString().ToLowerInvariant()}/{context.Request.Path}{QueryString.Create(commands)}"; string key = this.cacheHash.Create(uri, this.options.CachedNameLength); // Prevent identical requests from running at the same time // This reduces the overheads of unnecessary processing plus avoids file locks bool processRequest = true; using (await this.asyncKeyLock.LockAsync(key)) { // Get the correct service for the request. IImageResolver resolver = this.resolvers.FirstOrDefault(r => r.Match(context)); if (resolver == null || !await resolver.IsValidRequestAsync(context, this.logger)) { // Nothing to do. Call the next delegate/middleware in the pipeline processRequest = false; } if (processRequest) { CachedInfo info = await this.cache.IsExpiredAsync(context, key, DateTime.UtcNow.AddDays(-this.options.MaxCacheDays)); var imageContext = new ImageContext(context, this.options); if (info.Equals(default))
public eshSnapshot CreateStaticShoppingList(string publicID, string name, IImageResolver iresolver) { LogicaShoppingLists logica = new LogicaShoppingLists(); EVListSummary summ = logica.SelectListSummaryPorPublicID(publicID, iresolver); if (summ == null) { return(null); } eshSnapshot shot = new eshSnapshot(); shot.creationDate = System.DateTime.Now; shot.shoppingListID = summ.ShoppingListID; shot.totalPrice = summ.TotalPrice; shot.totalVolume = summ.TotalVolume; shot.publicID = Guid.NewGuid().ToString(); shot.name = (string.IsNullOrEmpty(name))? summ.Name:name; shot.description = summ.Description; foreach (var item in summ.Items) { if ((item.Units) > 0) { eshSnapshotInvType shotitem = new eshSnapshotInvType(); shotitem.typeID = item.ItemID; shotitem.unitPrice = item.UnitPrice; shotitem.units = item.Units; shotitem.volume = item.Volume; shot.eshSnapshotInvTypes.Add(shotitem); } } EveShoppingContext contexto = new EveShoppingContext(); contexto.eshSnapshots.Add(shot); contexto.SaveChanges(); return(shot); }
public IList <MarketItem> SelectMarketItemsEnShoppingList(string publicID, IImageResolver imageResolver) { EveShoppingContext context = new EveShoppingContext(); IList <MarketItem> miList = new List <MarketItem>(); var qlistaItems = (from sl in context.eshShoppingLists join slit in context.eshShoppingListInvTypes on sl.shoppingListID equals slit.shoppingListID join it in context.invTypes on slit.typeID equals it.typeID join p in context.eshPrices on new { sl.tradeHubID, slit.typeID } equals new { tradeHubID = p.solarSystemID, p.typeID } where sl.publicID == publicID select new { ItemID = slit.typeID, Name = it.typeName, Units = slit.units, TotalPrice = p.avg * slit.units, invType = it }); foreach (var item in qlistaItems) { MarketItem mi = new MarketItem() { ItemID = item.ItemID, Name = item.Name, Units = item.Units, TotalPrice = item.TotalPrice, UnitPrice = item.TotalPrice / item.Units, Volume = RepositorioItems.GetVolume(item.invType) * item.Units, ImageUrl32 = imageResolver != null?imageResolver.GetImageURL(item.ItemID) : string.Empty }; miList.Add(mi); } return(miList); }
public EVFitting SelectFitSummary(string publicID, int fittingID, IImageResolver imageResolver) { EveShoppingContext contexto = new EveShoppingContext(); eshShoppingList shlist = contexto.eshShoppingLists.Where(s => s.publicID == publicID).FirstOrDefault(); EVFitting fit = (from slf in contexto.eshShoppingListFittings join f in contexto.eshFittings on slf.fittingID equals f.fittingID join it in contexto.invTypes on f.shipTypeID equals it.typeID join p in contexto.eshPrices on new { tradeHubID = slf.eshShoppingList.tradeHubID, it.typeID } equals new { tradeHubID = p.solarSystemID, p.typeID } where slf.eshShoppingList.publicID == publicID && slf.fittingID == fittingID select new EVFitting { Description = f.description, ItemID = f.fittingID, Name = f.name, ShipID = f.shipTypeID.Value, ShipName = f.invType.typeName, ShipVolume = f.shipVolume, Units = slf.units, ShipPrice = p.avg, TotalPrice = p.avg * slf.units, Volume = f.shipVolume * slf.units, PublicID = f.publicID }).FirstOrDefault(); fit.ImageUrl32 = imageResolver.GetImageURL(fit.ShipID); //AddFittingHardwareToFittingSummary(imageResolver, contexto, fit); LogicaFittings logicafit = new LogicaFittings(); logicafit.AddFittingHardwaresToFitting(contexto, imageResolver, shlist.tradeHubID, fit); return(fit); }
/// <summary> /// Performs operations upon the current request. /// </summary> /// <param name="context">The current HTTP request context</param> /// <returns>The <see cref="Task"/></returns> public async Task Invoke(HttpContext context) { IDictionary <string, string> commands = this.uriParser.ParseUriCommands(context); this.options.OnValidate?.Invoke(new ImageValidationContext(context, commands, CommandParser.Instance)); if (!commands.Any() || !commands.Keys.Intersect(this.knownCommands).Any()) { // Nothing to do. call the next delegate/middleware in the pipeline await this.next(context); return; } // Create a cache key based on all the components of the requested url string uri = $"{context.Request.Host.ToString().ToLowerInvariant()}/{context.Request.PathBase.ToString().ToLowerInvariant()}/{context.Request.Path}{QueryString.Create(commands)}"; string key = CacheHash.Create(uri, this.options.Configuration); // Prevent identical requests from running at the same time // This reduces the overheads of unnecessary processing plus avoids file locks bool processRequest = true; using (await this.asyncKeyLock.LockAsync(key)) { // Get the correct service for the request. IImageResolver resolver = this.resolvers.FirstOrDefault(r => r.Match(context)); if (resolver == null || !await resolver.IsValidRequestAsync(context, this.logger)) { // Nothing to do. Call the next delegate/middleware in the pipeline processRequest = false; } if (processRequest) { CachedInfo info = await this.cache.IsExpiredAsync(context, key, DateTime.UtcNow.AddDays(-this.options.MaxCacheDays)); var imageContext = new ImageContext(context, this.options); if (info.Equals(default(CachedInfo))) { // Cache has tried to resolve the source image and failed // Log the error but let the pipeline handle the 404 this.logger.LogImageResolveFailed(imageContext.GetDisplayUrl()); processRequest = false; } if (processRequest) { if (!info.Expired) { // Image is a cached image. Return the correct response now. await this.SendResponse(imageContext, key, info.LastModifiedUtc, null, (int)info.Length); return; } // Not cached? Let's get it from the image resolver. byte[] inBuffer = null; byte[] outBuffer = null; MemoryStream outStream = null; try { inBuffer = await resolver.ResolveImageAsync(context, this.logger); if (inBuffer == null || inBuffer.Length == 0) { // Log the error but let the pipeline handle the 404 this.logger.LogImageResolveFailed(imageContext.GetDisplayUrl()); processRequest = false; } if (processRequest) { // No allocations here for inStream since we are passing the buffer. // TODO: How to prevent the allocation in outStream? Passing a pooled buffer won't let stream grow if needed. outStream = new MemoryStream(); using (var image = FormattedImage.Load(this.options.Configuration, inBuffer)) { image.Process(this.logger, this.processors, commands); this.options.OnBeforeSave?.Invoke(image); image.Save(outStream); } // Allow for any further optimization of the image. Always reset the position just in case. outStream.Position = 0; this.options.OnProcessed?.Invoke(new ImageProcessingContext(context, outStream, Path.GetExtension(key))); outStream.Position = 0; int outLength = (int)outStream.Length; // Copy the outstream to the pooled buffer. outBuffer = BufferDataPool.Rent(outLength); await outStream.ReadAsync(outBuffer, 0, outLength); DateTimeOffset cachedDate = await this.cache.SetAsync(key, outBuffer, outLength); await this.SendResponse(imageContext, key, cachedDate, outBuffer, outLength); } } catch (Exception ex) { // Log the error internally then rethrow. // We don't call next here, the pipeline will automatically handle it this.logger.LogImageProcessingFailed(imageContext.GetDisplayUrl(), ex); throw; } finally { outStream?.Dispose(); // Buffer should have been rented in IImageResolver BufferDataPool.Return(inBuffer); BufferDataPool.Return(outBuffer); } } } } if (!processRequest) { // Call the next delegate/middleware in the pipeline await this.next(context); } }
/// <summary> /// Performs operations upon the current request. /// </summary> /// <param name="context">The current HTTP request context.</param> /// <returns>The <see cref="Task"/>.</returns> public async Task Invoke(HttpContext context) { IDictionary <string, string> commands = this.requestParser.ParseRequestCommands(context) .Where(kvp => this.knownCommands.Contains(kvp.Key)) .ToDictionary(p => p.Key, p => p.Value); this.options.OnParseCommands?.Invoke(new ImageCommandContext(context, commands, CommandParser.Instance)); // Get the correct service for the request. IImageProvider provider = this.resolvers.FirstOrDefault(r => r.Match(context)); if (provider?.IsValidRequest(context) != true) { // Nothing to do. call the next delegate/middleware in the pipeline await this.next(context).ConfigureAwait(false); return; } // Create a cache key based on all the components of the requested url string uri = GetUri(context, commands); string key = this.cacheHash.Create(uri, this.options.CachedNameLength); bool processRequest = true; var imageContext = new ImageContext(context, this.options); IImageResolver resolvedImage = provider.Get(context); if (resolvedImage == null) { // Log the error but let the pipeline handle the 404 this.logger.LogImageResolveFailed(imageContext.GetDisplayUrl()); processRequest = false; } if (processRequest) { // Lock any reads when a write is being done for the same key to prevent potential file locks. using (await AsyncLock.ReaderLockAsync(key).ConfigureAwait(false)) { DateTime lastWriteTimeUtc = await resolvedImage.GetLastWriteTimeUtcAsync().ConfigureAwait(false); CachedInfo info = await this.cache.IsExpiredAsync(context, key, lastWriteTimeUtc, DateTime.UtcNow.AddDays(-this.options.MaxCacheDays)).ConfigureAwait(false); if (!info.Expired) { // We're pulling the image from the cache. IImageResolver cachedImage = this.cache.Get(key); using (Stream cachedBuffer = await cachedImage.OpenReadAsync().ConfigureAwait(false)) { // Image is a cached image. Return the correct response now. await this.SendResponse(imageContext, key, info.LastModifiedUtc, cachedBuffer).ConfigureAwait(false); } return; } } // Not cached? Let's get it from the image resolver. ChunkedMemoryStream outStream = null; try { if (processRequest) { // Enter a write lock which locks writing and any reads for the same request. // This reduces the overheads of unnecessary processing plus avoids file locks. using (await AsyncLock.WriterLockAsync(key).ConfigureAwait(false)) { // No allocations here for inStream since we are passing the raw input stream. // outStream allocation depends on the memory allocator used. outStream = new ChunkedMemoryStream(this.memoryAllocator); using (Stream inStream = await resolvedImage.OpenReadAsync().ConfigureAwait(false)) using (var image = FormattedImage.Load(this.options.Configuration, inStream)) { image.Process(this.logger, this.processors, commands); this.options.OnBeforeSave?.Invoke(image); image.Save(outStream); } // Allow for any further optimization of the image. Always reset the position just in case. outStream.Position = 0; this.options.OnProcessed?.Invoke(new ImageProcessingContext(context, outStream, commands, Path.GetExtension(key))); outStream.Position = 0; DateTimeOffset cachedDate = await this.cache.SetAsync(key, outStream).ConfigureAwait(false); await this.SendResponse(imageContext, key, cachedDate, outStream).ConfigureAwait(false); } } } catch (Exception ex) { // Log the error internally then rethrow. // We don't call next here, the pipeline will automatically handle it this.logger.LogImageProcessingFailed(imageContext.GetDisplayUrl(), ex); throw; } finally { outStream?.Dispose(); } } if (!processRequest) { // Call the next delegate/middleware in the pipeline await this.next(context).ConfigureAwait(false); } }
public SampleAppMarkdownRenderer(MarkdownDocument document, ILinkRegister linkRegister, IImageResolver imageResolver, ICodeBlockResolver codeBlockResolver) : base(document, linkRegister, imageResolver, codeBlockResolver) { LanguageRequested += SampleAppMarkdownRenderer_LanguageRequested; }
internal IEnumerable <EVFitting> MountFittingCommon(EveShoppingContext contexto, IEnumerable <QFitting> qfittings, IImageResolver imageResolver, int tradeHubID) { List <EVFitting> fittings = new List <EVFitting>(); foreach (var qfit in qfittings) { if (string.IsNullOrEmpty(qfit.PublicID)) { qfit.PublicID = Guid.NewGuid().ToString(); } EVFitting fit = new EVFitting { Description = qfit.Description, PublicID = qfit.PublicID, ItemID = qfit.FittingID, Name = qfit.Name, ShipID = qfit.ShipID, ShipName = qfit.ShipName, ShipVolume = qfit.ShipVolume, Units = qfit.Units, ShipPrice = qfit.ShipPrice, TotalPrice = qfit.Price, }; fit.ImageUrl32 = imageResolver != null?imageResolver.GetImageURL(qfit.ShipID) : string.Empty;; fit.ShipVolume = RepositorioItems.GetVolume(qfit.InvType); fit.Volume = fit.ShipVolume * fit.Units; fittings.Add(fit); AddFittingHardwaresToFitting(contexto, imageResolver, tradeHubID, fit); } return(fittings); }
private async Task ProcessRequestAsync(HttpContext context, bool processRequest, IImageResolver sourceImageResolver, ImageContext imageContext, IDictionary <string, string> commands) { // Create a cache key based on all the components of the requested url string uri = GetUri(context, commands); string key = this.cacheHash.Create(uri, this.options.CachedNameLength); ImageMetadata sourceImageMetadata = default; if (processRequest) { // Lock any reads when a write is being done for the same key to prevent potential file locks. using (await AsyncLock.ReaderLockAsync(key).ConfigureAwait(false)) { // Check to see if the cache contains this image sourceImageMetadata = await sourceImageResolver.GetMetaDataAsync().ConfigureAwait(false); IImageCacheResolver cachedImageResolver = await this.cache.GetAsync(key).ConfigureAwait(false); if (cachedImageResolver != null) { ImageCacheMetadata cachedImageMetadata = await cachedImageResolver.GetMetaDataAsync().ConfigureAwait(false); if (cachedImageMetadata != default) { // Has the cached image expired or has the source image been updated? if (cachedImageMetadata.SourceLastWriteTimeUtc == sourceImageMetadata.LastWriteTimeUtc && cachedImageMetadata.CacheLastWriteTimeUtc > DateTimeOffset.Now.AddDays(-this.options.MaxCacheDays)) { // We're pulling the image from the cache. using (Stream cachedBuffer = await cachedImageResolver.OpenReadAsync().ConfigureAwait(false)) { await this.SendResponseAsync(imageContext, key, cachedBuffer, cachedImageMetadata).ConfigureAwait(false); } return; } } } } // Not cached? Let's get it from the image resolver. ChunkedMemoryStream outStream = null; try { if (processRequest) { // Enter a write lock which locks writing and any reads for the same request. // This reduces the overheads of unnecessary processing plus avoids file locks. using (await AsyncLock.WriterLockAsync(key).ConfigureAwait(false)) { // No allocations here for inStream since we are passing the raw input stream. // outStream allocation depends on the memory allocator used. ImageCacheMetadata cachedImageMetadata = default; outStream = new ChunkedMemoryStream(this.memoryAllocator); using (Stream inStream = await sourceImageResolver.OpenReadAsync().ConfigureAwait(false)) using (var image = FormattedImage.Load(this.options.Configuration, inStream)) { image.Process(this.logger, this.processors, commands); this.options.OnBeforeSave?.Invoke(image); image.Save(outStream); // Check to see if the source metadata has a cachecontrol max-age value and use it to // override the default max age from our options. var maxAge = TimeSpan.FromDays(this.options.MaxBrowserCacheDays); if (!sourceImageMetadata.CacheControlMaxAge.Equals(TimeSpan.MinValue)) { maxAge = sourceImageMetadata.CacheControlMaxAge; } cachedImageMetadata = new ImageCacheMetadata( sourceImageMetadata.LastWriteTimeUtc, DateTime.UtcNow, image.Format.DefaultMimeType, maxAge); } // Allow for any further optimization of the image. Always reset the position just in case. outStream.Position = 0; string contentType = cachedImageMetadata.ContentType; string extension = this.formatUtilities.GetExtensionFromContentType(contentType); this.options.OnProcessed?.Invoke(new ImageProcessingContext(context, outStream, commands, contentType, extension)); outStream.Position = 0; // Save the image to the cache and send the response to the caller. await this.cache.SetAsync(key, outStream, cachedImageMetadata).ConfigureAwait(false); await this.SendResponseAsync(imageContext, key, outStream, cachedImageMetadata).ConfigureAwait(false); } } } catch (Exception ex) { // Log the error internally then rethrow. // We don't call next here, the pipeline will automatically handle it this.logger.LogImageProcessingFailed(imageContext.GetDisplayUrl(), ex); throw; } finally { outStream?.Dispose(); } } }
#pragma warning disable IDE1006 // Naming Styles /// <summary> /// Performs operations upon the current request. /// </summary> /// <param name="context">The current HTTP request context.</param> /// <returns>The <see cref="Task"/>.</returns> public async Task Invoke(HttpContext context) #pragma warning restore IDE1006 // Naming Styles { IDictionary <string, string> commands = this.requestParser.ParseRequestCommands(context); if (commands.Count > 0) { List <string> commandKeys = new List <string>(commands.Keys); foreach (string command in commandKeys) { if (!this.knownCommands.Contains(command)) { commands.Remove(command); } } } this.options.OnParseCommands?.Invoke(new ImageCommandContext(context, commands, CommandParser.Instance)); if (commands.Count == 0) { // Nothing to do. call the next delegate/middleware in the pipeline await this.next(context).ConfigureAwait(false); return; } // Get the correct service for the request. IImageProvider provider = null; foreach (IImageProvider resolver in this.providers) { if (resolver.Match(context)) { provider = resolver; break; } } if (provider?.IsValidRequest(context) != true) { // Nothing to do. call the next delegate/middleware in the pipeline await this.next(context).ConfigureAwait(false); return; } bool processRequest = true; IImageResolver sourceImageResolver = await provider.GetAsync(context).ConfigureAwait(false); if (sourceImageResolver == null) { // Log the error but let the pipeline handle the 404 var imageContext = new ImageContext(context, this.options); this.logger.LogImageResolveFailed(imageContext.GetDisplayUrl()); processRequest = false; } if (!processRequest) { // Call the next delegate/middleware in the pipeline await this.next(context).ConfigureAwait(false); return; } await this.ProcessRequestAsync(context, processRequest, sourceImageResolver, new ImageContext(context, this.options), commands) .ConfigureAwait(false); }
private async Task ProcessRequestAsync( HttpContext context, IImageResolver sourceImageResolver, ImageContext imageContext, IDictionary <string, string> commands) { // Create a cache key based on all the components of the requested url string uri = GetUri(context, commands); string key = this.cacheHash.Create(uri, this.options.CachedNameLength); // Check the cache, if present, not out of date and not requiring and update // we'll simply serve the file from there. ImageWorkerResult readResult = default; try { readResult = await this.IsNewOrUpdatedAsync(sourceImageResolver, imageContext, key); } finally { ReadWorkers.TryRemove(key, out Task <ImageWorkerResult> _); } if (!readResult.IsNewOrUpdated) { await this.SendResponseAsync(imageContext, key, readResult.CacheImageMetadata, readResult.Resolver); return; } // Not cached, or is updated? Let's get it from the image resolver. var sourceImageMetadata = readResult.SourceImageMetadata; // Enter an asynchronous write worker which prevents multiple writes and delays any reads for the same request. // This reduces the overheads of unnecessary processing. try { ImageWorkerResult writeResult = await WriteWorkers.GetOrAddAsync( key, async (key) => { RecyclableMemoryStream outStream = null; try { // Prevent a second request from starting a read during write execution. if (ReadWorkers.TryGetValue(key, out Task <ImageWorkerResult> readWork)) { await readWork; } ImageCacheMetadata cachedImageMetadata = default; outStream = new RecyclableMemoryStream(this.options.MemoryStreamManager); IImageFormat format; // 14.9.3 CacheControl Max-Age // Check to see if the source metadata has a CacheControl Max-Age value // and use it to override the default max age from our options. TimeSpan maxAge = this.options.BrowserMaxAge; if (!sourceImageMetadata.CacheControlMaxAge.Equals(TimeSpan.MinValue)) { maxAge = sourceImageMetadata.CacheControlMaxAge; } using (Stream inStream = await sourceImageResolver.OpenReadAsync()) { // No commands? We simply copy the stream across. if (commands.Count == 0) { await inStream.CopyToAsync(outStream); outStream.Position = 0; format = await Image.DetectFormatAsync(this.options.Configuration, outStream); } else { using var image = FormattedImage.Load(this.options.Configuration, inStream); image.Process( this.logger, this.processors, commands, this.commandParser, this.parserCulture); await this.options.OnBeforeSaveAsync.Invoke(image); image.Save(outStream); format = image.Format; } } // Allow for any further optimization of the image. outStream.Position = 0; string contentType = format.DefaultMimeType; string extension = this.formatUtilities.GetExtensionFromContentType(contentType); await this.options.OnProcessedAsync.Invoke(new ImageProcessingContext(context, outStream, commands, contentType, extension)); outStream.Position = 0; cachedImageMetadata = new ImageCacheMetadata( sourceImageMetadata.LastWriteTimeUtc, DateTime.UtcNow, contentType, maxAge, outStream.Length); // Save the image to the cache and send the response to the caller. await this.cache.SetAsync(key, outStream, cachedImageMetadata); // Remove any resolver from the cache so we always resolve next request // for the same key. CacheResolverLru.TryRemove(key); // Place the resolver in the lru cache. (IImageCacheResolver ImageCacheResolver, ImageCacheMetadata ImageCacheMetadata)cachedImage = await CacheResolverLru.GetOrAddAsync( key, async k => { IImageCacheResolver resolver = await this.cache.GetAsync(k); ImageCacheMetadata metadata = default; if (resolver != null) { metadata = await resolver.GetMetaDataAsync(); } return(resolver, metadata); }); return(new ImageWorkerResult(cachedImage.ImageCacheMetadata, cachedImage.ImageCacheResolver)); } catch (Exception ex) { // Log the error internally then rethrow. // We don't call next here, the pipeline will automatically handle it this.logger.LogImageProcessingFailed(imageContext.GetDisplayUrl(), ex); throw; } finally { await this.StreamDisposeAsync(outStream); } }); await this.SendResponseAsync(imageContext, key, writeResult.CacheImageMetadata, writeResult.Resolver); } finally { // As soon as we have sent a response from a writer the result is available from a reader so we remove this task. // Any existing awaiters will continue to await. WriteWorkers.TryRemove(key, out Task <ImageWorkerResult> _); } }
public IList <AssetImported> ImportAssetsForListDelta(string publicId, string assets, IImageResolver imageResolver) { ImportItemListFromAssets importer = new ImportItemListFromAssets(); IDictionary <string, AssetImported> diccassets = importer.ImportFrom(assets); List <AssetImported> salida = new List <AssetImported>(); EVListSummary summ = this.SelectListSummaryPorPublicID(publicId, imageResolver, true); foreach (var item in summ.Items) { if (diccassets.ContainsKey(item.Name)) { AssetImported ai = diccassets[item.Name]; ai.Id = item.ItemID; ai.ImageUrl32 = item.ImageUrl32; ai.Units *= -1; salida.Add(ai); } } return(salida); }
public eshSnapshot CreateStaticShoppingListFromGroup(string groupPublicID, string name, IImageResolver iresolver) { LogicaGroupLists logica = new LogicaGroupLists(); EVListSummary ev = logica.SelectGroupListSummaryPorPublicID(groupPublicID, iresolver); eshSnapshot snap = new eshSnapshot(); if (ev == null) { return(null); } snap.name = ev.Name; snap.description = ev.Description; snap.totalVolume = ev.TotalVolume; snap.totalPrice = ev.TotalPrice; snap.publicID = Guid.NewGuid().ToString(); snap.creationDate = System.DateTime.Now; foreach (var item in ev.Items) { eshSnapshotInvType sit = new eshSnapshotInvType(); sit.typeID = item.ItemID; sit.unitPrice = item.UnitPrice; sit.units = item.Units; sit.volume = item.Volume; snap.eshSnapshotInvTypes.Add(sit); } return(snap); }
public MapViewRenderer() { markers = new TwoWayDictionary <Marker, GMaps.Model.Marker>(new LambdaEqualityComparer <GMaps.Model.Marker>((m1, m2) => m1.Id == m2.Id)); tileOverlays = new TwoWayDictionary <TileOverlay, GMaps.Model.TileOverlay>(new LambdaEqualityComparer <GMaps.Model.TileOverlay>((m1, m2) => m1.Id == m2.Id)); imageResolver = AppShell.ShellCore.Container.GetInstance <IImageResolver>(); }
private async Task ProcessRequestAsync( HttpContext context, IImageResolver sourceImageResolver, ImageContext imageContext, IDictionary <string, string> commands) { // Create a cache key based on all the components of the requested url string uri = GetUri(context, commands); string key = this.cacheHash.Create(uri, this.options.CachedNameLength); // Check the cache, if present, not out of date and not requiring and update // we'll simply serve the file from there. (bool newOrUpdated, ImageMetadata sourceImageMetadata) = await this.IsNewOrUpdatedAsync(sourceImageResolver, imageContext, key); if (!newOrUpdated) { return; } // Not cached? Let's get it from the image resolver. RecyclableMemoryStream outStream = null; // Enter a write lock which locks writing and any reads for the same request. // This reduces the overheads of unnecessary processing plus avoids file locks. await WriteWorkers.GetOrAdd( key, _ => new Lazy <Task>( async() => { try { // Prevent a second request from starting a read during write execution. if (ReadWorkers.TryGetValue(key, out Lazy <Task <(bool, ImageMetadata)> > readWork)) { await readWork.Value; } ImageCacheMetadata cachedImageMetadata = default; outStream = new RecyclableMemoryStream(this.options.MemoryStreamManager); IImageFormat format; // 14.9.3 CacheControl Max-Age // Check to see if the source metadata has a CacheControl Max-Age value // and use it to override the default max age from our options. TimeSpan maxAge = this.options.BrowserMaxAge; if (!sourceImageMetadata.CacheControlMaxAge.Equals(TimeSpan.MinValue)) { maxAge = sourceImageMetadata.CacheControlMaxAge; } using (Stream inStream = await sourceImageResolver.OpenReadAsync()) { // No commands? We simply copy the stream across. if (commands.Count == 0) { await inStream.CopyToAsync(outStream); outStream.Position = 0; format = await Image.DetectFormatAsync(this.options.Configuration, outStream); } else { using var image = FormattedImage.Load(this.options.Configuration, inStream); image.Process( this.logger, this.processors, commands, this.commandParser, this.parserCulture); await this.options.OnBeforeSaveAsync.Invoke(image); image.Save(outStream); format = image.Format; } } // Allow for any further optimization of the image. outStream.Position = 0; string contentType = format.DefaultMimeType; string extension = this.formatUtilities.GetExtensionFromContentType(contentType); await this.options.OnProcessedAsync.Invoke(new ImageProcessingContext(context, outStream, commands, contentType, extension)); outStream.Position = 0; cachedImageMetadata = new ImageCacheMetadata( sourceImageMetadata.LastWriteTimeUtc, DateTime.UtcNow, contentType, maxAge, outStream.Length); // Save the image to the cache and send the response to the caller. await this.cache.SetAsync(key, outStream, cachedImageMetadata); // Remove the resolver from the cache so we always resolve next request // for the same key. CacheResolverLru.TryRemove(key); await this.SendResponseAsync(imageContext, key, cachedImageMetadata, outStream, null); } catch (Exception ex) { // Log the error internally then rethrow. // We don't call next here, the pipeline will automatically handle it this.logger.LogImageProcessingFailed(imageContext.GetDisplayUrl(), ex); throw; } finally { await this.StreamDisposeAsync(outStream); WriteWorkers.TryRemove(key, out Lazy <Task> _); } }, LazyThreadSafetyMode.ExecutionAndPublication)).Value; }
public EVListSummary SelectListSummaryPorPublicID(string publicID, IImageResolver imageResolver, bool includeEmpty = true) { EveShoppingContext contexto = new EveShoppingContext(); eshShoppingList shoppingList = contexto.eshShoppingLists.Where(sl => sl.publicID == publicID).FirstOrDefault(); if (shoppingList == null) { return(null); } EVListSummary summary = new EVListSummary(); summary.Description = shoppingList.description; summary.Name = shoppingList.name; summary.PublicID = shoppingList.publicID; summary.ReadOnlyPublicID = shoppingList.readOnlypublicID; summary.ShoppingListID = shoppingList.shoppingListID; IEnumerable <EVFitting> fittings = this.SelectFitsInShoppingList(publicID, imageResolver); Dictionary <int, EVFittingHardware> diccHwd = new Dictionary <int, EVFittingHardware>(); //add ships foreach (var fit in fittings) { EVFittingHardware fw = null; if (diccHwd.ContainsKey(fit.ShipID)) { fw = diccHwd[fit.ShipID]; fw.Units += fit.Units; fw.Volume += fit.Units * fit.ShipVolume; fw.TotalPrice += fit.ShipPrice * fit.Units; } else { fw = new EVFittingHardware { Name = fit.ShipName, ItemID = fit.ShipID, Units = fit.Units, Volume = fit.ShipVolume * fit.Units, UnitVolume = fit.ShipVolume, TotalPrice = fit.ShipPrice * fit.Units, UnitPrice = fit.ShipPrice, ImageUrl32 = imageResolver != null?imageResolver.GetImageURL(fit.ShipID) : string.Empty }; diccHwd.Add(fw.ItemID, fw); } } //add fitted hardware foreach (var fit in fittings) { foreach (var fw in fit.FittingHardwares) { if (diccHwd.ContainsKey(fw.ItemID)) { EVFittingHardware fwd = diccHwd[fw.ItemID]; fwd.Units += fw.Units * fit.Units; fwd.Volume += fw.Volume * fit.Units; fwd.TotalPrice += fw.TotalPrice * fit.Units; //fw.UnitPrice = fw.TotalPrice; } else { fw.Units *= fit.Units; fw.Volume *= fit.Units; fw.TotalPrice *= fit.Units; if (fit.Units != 0) { fw.UnitVolume = fw.Volume / fw.Units; fw.UnitPrice = fw.TotalPrice / fw.Units; } else { fw.UnitVolume = fw.Volume; fw.UnitPrice = fw.TotalPrice; } diccHwd.Add(fw.ItemID, fw); } } } //add market items IEnumerable <MarketItem> marketItems = this.SelectMarketItemsEnShoppingList(publicID, imageResolver); foreach (var mi in marketItems) { if (diccHwd.ContainsKey(mi.ItemID)) { EVFittingHardware fwd = diccHwd[mi.ItemID]; fwd.Units += mi.Units; fwd.Volume += mi.Volume; fwd.TotalPrice += mi.TotalPrice; } else { EVFittingHardware fwd = new EVFittingHardware(); fwd.ImageUrl32 = mi.ImageUrl32; fwd.ItemID = mi.ItemID; fwd.Name = mi.Name; fwd.TotalPrice = mi.TotalPrice; fwd.UnitPrice = mi.UnitPrice; fwd.Units = mi.Units; fwd.Volume = mi.Volume; fwd.UnitVolume = mi.Volume / mi.Units; diccHwd.Add(fwd.ItemID, fwd); } } // Update summary changes IEnumerable <eshShoppingListSummInvType> summInvs = contexto.eshShoppingListSummInvTypes.Where(sls => sls.shoppingListID == summary.ShoppingListID); foreach (var summInv in summInvs) { if (!diccHwd.ContainsKey(summInv.typeID)) { //if the item is not in the items dictionary, it doesnt exist anymore in the list, so we delete the delta contexto.eshShoppingListSummInvTypes.Remove(summInv); } else { EVFittingHardware fwd = diccHwd[summInv.typeID]; if ((summInv.delta < 0) && (summInv.delta * -1 > fwd.Units)) { summInv.delta = (short)(fwd.Units * -1); } fwd.TotalPrice += summInv.delta * fwd.UnitPrice; fwd.Volume += (fwd.Volume / fwd.Units) * summInv.delta; fwd.Units += summInv.delta; fwd.Delta = summInv.delta; } } foreach (var item in diccHwd.Values) { if (includeEmpty || (item.Units > 0)) { summary.Items.Add(item); summary.TotalPrice += item.TotalPrice; summary.TotalVolume += item.Volume; } } contexto.SaveChanges(); return(summary); }
public EVFitting SetUnitsToFitInShoppingList(string publicID, int fittingID, int units, IImageResolver imageResolver) { EveShoppingContext contexto = new EveShoppingContext(); //guardamos los cambios eshShoppingListFitting slfit = contexto.eshShoppingListFittings.Where(slf => slf.fittingID == fittingID && slf.eshShoppingList.publicID == publicID).FirstOrDefault(); if (slfit == null) { throw new ApplicationException(Messages.err_fittingNoExiste); } if (units < 1) { units = 1; } slfit.units = units; RepositorioShoppingLists repo = new RepositorioShoppingLists(); repo.ShoppingListUpdated(slfit.shoppingListID, contexto); contexto.SaveChanges(); //obtenemos la fitting return(this.SelectFitSummary(publicID, fittingID, imageResolver)); }