public FileManagerService(IWebsite website, IFileStorage fileStorage, IStorageItemRepository storageItemRepository, ITransactionManager transactionManager) { this._fileStorage = fileStorage; this._website = website; this._transactionManager = transactionManager; this._storageItemRepository = storageItemRepository; }
public TaskController(IGenericRepository<Task> taskRepository, IGenericRepository<Project> projectRepository, IGenericRepository<User> userRepository, IFileStorage fileStorage) { _taskRepository = taskRepository; _projectRepository = projectRepository; _userRepository = userRepository; _fileStorage = fileStorage; }
public AdminController(IFileStorage fileStorage, IMessagePublisher messagePublisher, IOrganizationRepository organizationRepository, IQueue<EventPost> eventPostQueue, IQueue<WorkItemData> workItemQueue) { _fileStorage = fileStorage; _messagePublisher = messagePublisher; _organizationRepository = organizationRepository; _eventPostQueue = eventPostQueue; _workItemQueue = workItemQueue; }
public AzureIndulgenceEmailer(IFileStorage fileStorage, ILog log) { _fileStorage = fileStorage; _log = log; }
public NHibernateIndulgeMeService(ISession session, IIndulgenceGenerator indulgenceGenerator, IFileStorage fileStorage, ITweeter tweeter) { _session = session; _indulgenceGenerator = indulgenceGenerator; _fileStorage = fileStorage; _tweeter = tweeter; }
public SystemHealthChecker(ICacheClient cacheClient, IElasticClient elasticClient, IFileStorage storage, IQueue<StatusMessage> queue, IMessageBus messageBus) { _cacheClient = cacheClient; _elasticClient = elasticClient; _storage = storage; _queue = queue; _messageBus = messageBus; }
internal static int Main(IFileStorage fileSystem, IScriptProvider provider, string[] args) { if (fileSystem == null) { throw new ArgumentNullException("No file system was provided.", "fileSystem"); } if (args == null) { throw new ArgumentNullException("No args were provided.", "args"); } if (args.Length == 0) { Console.WriteLine("Usage:\tSolutionTransform <Script Name or Path> <Other Arguments>"); Console.WriteLine("\t\tSolutionTransform <Script Name or Path> --help"); Console.WriteLine("\t\t\tfor script argument help"); Console.WriteLine("\t\t\tNote that paths nearly always have to be absolute."); ReportScripts(provider); return 0; } var file = provider.AllScripts.FirstOrDefault(s => s.Name.Equals(args[0], StringComparison.InvariantCultureIgnoreCase)); if (file == null) { Console.WriteLine("Could not find script named '{0}'.", args[0]); ReportScripts(provider); return 1; } return file.Execute(args, fileSystem); }
//инициализация public FileQueriesBase(IFileStorage fileStorage , ImageSettings settings) { FileStorage = fileStorage; Settings = settings; UploadImagePipeline = new UploadImagePipeline(fileStorage); }
public RavenFileRepository(IDocumentSession documentSession, IFileStorage fileStorage, IUserIdentity userIdentity, ILog logger) { _documentSession = DIHelper.VerifyParameter(documentSession); _fileStorage = DIHelper.VerifyParameter(fileStorage); _userIdentity = DIHelper.VerifyParameter(userIdentity); _logger = DIHelper.VerifyParameter(logger); }
public NotepadViewModel(IFileStorage fileStorage) { _fileStorage = fileStorage; Filename = "test.txt"; Contents = "Hello, World!"; }
/// <summary> /// Конструктор по умолчанию /// </summary> /// <param name="engine"></param> public VcsStoragePersister(IFileStorage engine) { Engine = engine; Abilities = FileStorageAbilities.Vcs; _logger = new VcsStorageLogger(Engine); _mapper = new VcsStorageMapper(Engine); }
public int Execute(IEnumerable<string> args, IFileStorage fileSystem) { try { var interpreter = new Boo.Lang.Interpreter.InteractiveInterpreter2(); var parser = new BooCommandLineParser(interpreter, args.ToArray()); var api10 = new Api(parser, fileSystem); // api10.Parameters(); interpreter.SetValue("api10", api10); CompilerContext context; try { context = interpreter.Eval(content); } catch (TargetInvocationException ex) { if (ex.InnerException == null) { throw ex.InnerException; } throw; } foreach (var e in context.Errors) { Console.WriteLine(e.ToString()); } if (context.Errors.Count != 0) { return 2; } } catch (NonErrorTerminationException) { return 0; } catch (Exception ex) { WriteException(Console.Out, ex); return 1; } return 0; }
public static Repository.Model.File FilePut(this Repository.Logic.Repository repository, IFileStorage storage, string localFilePath, Encoding encoding) { using (var fileStream = System.IO.File.OpenRead(localFilePath)) { var fileName = System.IO.Path.GetFileName(localFilePath); return repository.FilePut(storage, fileStream, fileName, encoding); } }
public PersistedDictionary(string path, IFileStorage fileStorage, IJsonSerializer serializer, int delay = 250) { _fileStorage = fileStorage; _serializer = serializer; _path = path; _delay = delay; Changed += OnChanged; _timer = new Timer(OnSaveTimer, null, -1, -1); }
public CachingFileStorage(IFileStorage cachedStorage, string cacheDir, ICacheSupervisor cacheSupervisor) { _cachedStorage = cachedStorage; _cacheSupervisor = cacheSupervisor; _streamCacheDir = cacheDir + Java.IO.File.Separator + "OfflineCache" + Java.IO.File.Separator; if (!Directory.Exists(_streamCacheDir)) Directory.CreateDirectory(_streamCacheDir); }
/// <summary> /// Populate DB with retailers. /// </summary> /// <param name="context"> /// The context. /// </param> /// <param name="fileStorage"> /// The file storage. /// </param> public static void Populate(ShopAnyWareSql context, IFileStorage fileStorage) { var path = fileStorage.MapPath("~/App_Data/retailers.xls"); var retailersExcel = ExcelHelper.LoadRetailersFromExcelFile(path); var retailers = retailersExcel.Select(r => new Retailer(r.Url)).ToList(); var retailers2 = retailers.Where(r => string.IsNullOrWhiteSpace(r.Url) == false).ToList(); retailers2.ForEach(r => context.Retailers.Add(r)); context.SaveChanges(); }
public EventPostsJob(IQueue<EventPost> queue, EventParserPluginManager eventParserPluginManager, EventPipeline eventPipeline, IMetricsClient metricsClient, IOrganizationRepository organizationRepository, IProjectRepository projectRepository, IFileStorage storage) { _queue = queue; _eventParserPluginManager = eventParserPluginManager; _eventPipeline = eventPipeline; _metricsClient = metricsClient; _organizationRepository = organizationRepository; _projectRepository = projectRepository; _storage = storage; }
public SolutionFile(FilePath solutionPath, IFileStorage fileSystem, IEnumerable<string> preamble, IEnumerable<SolutionChapter> chapters) { if (solutionPath == null) { throw new ArgumentNullException("solutionPath"); } this.solutionPath = solutionPath; this.fileSystem = fileSystem; this.preamble = preamble.ToList(); this.chapters = chapters.ToList(); }
public AvatarImageQueries(IFileStorage fileStorage, AvatarImageSettings settings) : base(fileStorage, settings) { Settings = settings; foreach (ImageTargetParameters item in settings.Targets) { item.PathCreator.UrlBase = fileStorage.GetBaseUrl(); } }
public ContentVersionStorage(IFileStorage istorage = null) { if (istorage == null) { istorage = new ZipStorage("fv.zip"); } this.storage = istorage; PopulateContents(); }
//инициализация public CommentImageQueries(IFileStorage fileStorage, IImageSettingsFactory settingsFactory) : base(fileStorage, null) { Settings = settingsFactory.GetSettings(Constants.IMAGE_SETTINGS_NAME_COMMENT); foreach (ImageTargetParameters item in Settings.Targets) { item.PathCreator.UrlBase = fileStorage.GetBaseUrl(); } }
//инициализация public DemoContentModule(ICommonLogger logger , PreviewImageQueries previewImageQueries, IFileStorage fileStorage , MongoDbConnectionSettings mongoSettings, DemoContentSettings settings) { _logger = logger; _previewQueries = previewImageQueries; _fileStorage = fileStorage; _settings = settings; _context = new MongoDbContext(mongoSettings); }
public static async Task<string> EnqueueAsync(this IQueue<EventPost> queue, EventPostInfo data, IFileStorage storage, bool shouldArchive = true, CancellationToken cancellationToken = default(CancellationToken)) { string path = $"q\\{Guid.NewGuid().ToString("N")}.json"; if (!await storage.SaveObjectAsync(path, data, cancellationToken).AnyContext()) return null; return await queue.EnqueueAsync(new EventPost { FilePath = path, ShouldArchive = shouldArchive }).AnyContext(); }
public ProfileService( IUnitOfWorkFactory unitOfWorkFactory, IFileStorage fileStorage, ISessionManager sessionManager, ProfileChangesNotificator profileChangesNotificator) : base(unitOfWorkFactory) { _fileStorage = fileStorage; _sessionManager = sessionManager; _profileChangesNotificator = profileChangesNotificator; }
public DefaultEventQueue(ExceptionlessConfiguration config, IExceptionlessLog log, ISubmissionClient client, IFileStorage fileStorage, IJsonSerializer serializer, TimeSpan? processQueueInterval, TimeSpan? queueStartDelay) { _log = log; _config = config; _client = client; _storage = fileStorage; _serializer = serializer; if (processQueueInterval.HasValue) _processQueueInterval = processQueueInterval.Value; _queueTimer = new Timer(OnProcessQueue, null, queueStartDelay ?? TimeSpan.FromSeconds(10), _processQueueInterval); }
public static IEnumerable<Model.Picture> RersizeTo(Repository.Model.File fromFile, Repository.Logic.Repository repository, IFileStorage storage, Model.PictureType[] toType) { if (fromFile == null) throw new ArgumentNullException(nameof(fromFile)); if (repository == null) throw new ArgumentNullException(nameof(repository)); if (storage == null) throw new ArgumentNullException(nameof(storage)); toType = toType ?? typeof(Model.PictureType) .GetEnumValues() .Cast<Model.PictureType>() .ToArray(); var toSizes = toType .Select(i => new { PictureType = i, Size = GetSize(i) }) .Where(i => i.Size != null) .ToArray(); if (toSizes.Any()) using (var fileStream = storage.FileGet(fromFile.FileId)) using (var originalImage = Bitmap.FromStream(fileStream)) { var pictures = toSizes.Select(t => { var newWidth = (t.Size.Width == 0) ? originalImage.Width : t.Size.Width; var newHeight = (t.Size.Height == 0) ? originalImage.Height : t.Size.Height; using (var resizedbitmap = ResizeBitmap(originalImage, newWidth, newHeight)) using (var newPictureStream = new MemoryStream()) { resizedbitmap.Save(newPictureStream, originalImage.RawFormat); newPictureStream.Seek(0, SeekOrigin.Begin); var dbFile = repository.FilePut(storage, newPictureStream, t.PictureType.ToString() + fromFile.FileName); var picture = repository.New<Repository.Model.Picture>(); picture.File = dbFile; picture.FileId = dbFile.FileId; picture.Height = newWidth; picture.Width = newHeight; picture.PictureType = (Repository.Model.PictureType)(int)t.PictureType; repository.Add(picture); return AutoMapper.Mapper.Map<Model.Picture>(picture); } }).ToArray(); return pictures; } return Enumerable.Empty<Model.Picture>(); }
public CacheStorage(IFileStorage storage) { __Storage = storage; var s = !__Storage.FileExists(MAP_FILE) ? __Storage.CreateFile(MAP_FILE) : __Storage.OpenFile(MAP_FILE, FileMode.Open); var serializer = new JsonSerializer { Formatting = Formatting.Indented }; using (var file = new JsonTextReader(new StreamReader(s))) { __AudioDict = serializer.Deserialize<Dictionary<long, JsonAudioModel>>(file) ?? new Dictionary<long, JsonAudioModel>(); } foreach (var jsonAudioModel in __AudioDict) { if (!__AudioIdList.ContainsKey(jsonAudioModel.Value.UserId)) __AudioIdList.Add(jsonAudioModel.Value.UserId, new SortedList<int, long>()); __AudioIdList[jsonAudioModel.Value.UserId].Add(jsonAudioModel.Value.Index, jsonAudioModel.Key); } if (__Storage.FileExists(USERID_FILE)) { try { using (var file = new StreamReader(__Storage.OpenFile(USERID_FILE, FileMode.Open))) { __UserId = file.ReadToEnd(); } } catch { //Ќичего не делать, последнего сохраненного алиаса не будет. } } if (__Storage.FileExists(AILASTOID_FILE)) { try { using (var file = new JsonTextReader(new StreamReader(__Storage.OpenFile(AILASTOID_FILE, FileMode.Open)))) { __AliasMap = serializer.Deserialize<Dictionary<string, JsonUserModel>>(file); } } catch { //Ќичего не делать, карты алиасов не будет. } } }
public static RoyaltyRepository.Models.File FilePut(this RoyaltyRepository.Repository repository, IFileStorage storage, Stream streamToUpload, string fileName, Encoding encoding = null) { var repFile = repository.NewFile((f) => { f.FileName = fileName; f.MimeType = MimeTypes.GetMimeTypeFromFileName(fileName); }); var fileInfo = storage.FilePut(repFile.FileUID, streamToUpload, fileName); repFile.OriginalFileName = fileInfo.Name; repFile.FileSize = fileInfo.Length; repFile.Encoding = encoding; return repFile; }
public static Repository.Model.File FilePut(this Repository.Logic.Repository repository, IFileStorage storage, IEnumerable<string> lines, Encoding encoding, string fileName) { using (var stream = new System.IO.MemoryStream()) using (var writer = new System.IO.StreamWriter(stream, encoding)) { lines.SelectMany(str => str.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)) .ToList() .ForEach(s => writer.WriteLine(s)); writer.Flush(); var file = FilePut(repository, storage, stream, fileName); file.Encoding = encoding; return file; } }
public ChatService( ISessionManager sessionManager, ISettings settings, IFileStorage fileStorage, ProfileChangesNotificator profileChangesNotificator, IUnitOfWorkFactory unitOfWorkFactory) : base(unitOfWorkFactory) { _sessionManager = sessionManager; _settings = settings; _fileStorage = fileStorage; _profileChangesNotificator = profileChangesNotificator; _sessionManager.AuthenticatedUserConnected += SessionManagerOnAuthenticatedUserConnected; _sessionManager.AuthenticatedUserDisconnected += SessionManagerOnAuthenticatedUserDisconnected; }
public IntegrationArchiver(IFileStorage fileStorage, IProcessLogger logger, IIntegrationSettings settings) { _fileStorage = fileStorage; _logger = logger; _settings = settings; }
public async Task <AddBadgePayload> AddBadgeAsync( AddBadgeInput input, [ScopedService] DatabaseContext context, [Service] IFileStorage fileStorage, CancellationToken cancellationToken) { if (input.BadgeImage == null) { return(new AddBadgePayload( new [] { new UserError("No badge image provided.", BadgeErrorCodes.BADGE_IMAGE_NOT_PROVIDED) } )); } var badge = new Badge { Name = input.Name, Description = input.Description, EventId = input.EventId }; var badgeEntity = await context.Badges.AddAsync(badge, cancellationToken); var uploadTasks = new List <Task <string> >(); try { int[] imageSizes = { 32, 64, 128, 256 }; using var ingredientImage = await Image.LoadAsync(input.BadgeImage !.OpenReadStream()); foreach (var size in imageSizes) { var image = await Images.ImageToPngMemoryStream(ingredientImage, size, size); var destinationKey = $"badges/{badgeEntity.Entity.Id}.{size}.png"; uploadTasks.Add(fileStorage.UploadFileFromStream(image, destinationKey)); } } catch { return(new AddBadgePayload( new [] { new UserError("Failed to upload badge image.", CommonErrorCodes.IMAGE_UPLOAD_FAILED) } )); } var t = Task.WhenAll(uploadTasks); try { t.Wait(cancellationToken); } catch { return(new AddBadgePayload( new [] { new UserError("Failed to upload badge image.", CommonErrorCodes.IMAGE_UPLOAD_FAILED) } )); } await context.SaveChangesAsync(cancellationToken); return(new AddBadgePayload(badgeEntity.Entity)); }
public EventPostsJob(IQueue <EventPost> queue, EventParserPluginManager eventParserPluginManager, EventPipeline eventPipeline, IMetricsClient metricsClient, IOrganizationRepository organizationRepository, IProjectRepository projectRepository, IFileStorage storage, ILoggerFactory loggerFactory = null) : base(queue, loggerFactory) { _eventParserPluginManager = eventParserPluginManager; _eventPipeline = eventPipeline; _metricsClient = metricsClient; _organizationRepository = organizationRepository; _projectRepository = projectRepository; _storage = storage; AutoComplete = false; }
public static void Enqueue(this IFileStorage storage, string queueName, Event ev, IJsonSerializer serializer) { storage.SaveObject(String.Concat(queueName, "\\q\\", Guid.NewGuid().ToString("N"), ".0.json"), ev, serializer); }
public DownloadGeoIPDatabaseJob(ICacheClient cacheClient, IFileStorage storage, ILoggerFactory loggerFactory = null) : base(loggerFactory) { _storage = storage; _lockProvider = new ThrottlingLockProvider(cacheClient, 1, TimeSpan.FromDays(1)); }
public ActorsController(ApplicationDBContext context, IMapper mapper, IFileStorage fileStorage) : base(context, mapper) { this.context = context; this.mapper = mapper; this.fileStorage = fileStorage; }
public static T GetObject <T>(this IFileStorage storage, string path, IJsonSerializer serializer) { string json = storage.GetFileContents(path); return(serializer.Deserialize <T>(json)); }
public AttachmentService(IFileStorage fileStorage, AppDbContext db, IUserService userService) { _db = db; _fileStorage = fileStorage; _userService = userService; }
public static Task <bool> SaveObjectAsync <T>(this IFileStorage storage, string path, T data, CancellationToken cancellationToken = default(CancellationToken)) { string json = JsonConvert.SerializeObject(data); return(storage.SaveFileAsync(path, new MemoryStream(Encoding.UTF8.GetBytes(json ?? String.Empty)), cancellationToken)); }
public PlacesController(ApplicationDbContext context, IMapper mapper, IFileStorage fileStorage) { this.context = context; this.mapper = mapper; this.fileStorage = fileStorage; }
public BuferHandlersWrapper( IClipboardBuferService clipboardBuferService, IBuferContextMenuGenerator buferContextMenuGenerator, IBuferSelectionHandlerFactory buferSelectionHandlerFactory, IFileStorage fileStorage, IBufermanHost bufermanHost, IProgramSettingsGetter settingsGetter, IProgramSettingsSetter settingsSetter, IEnumerable<IBufermanPlugin> plugins, IBufer bufer) { this._settingsGetter = settingsGetter; this._settingsSetter = settingsSetter; this._clipboardBuferService = clipboardBuferService; this._bufermanHost = bufermanHost; this._bufer = bufer; this._buferSelectionHandlerFactory = buferSelectionHandlerFactory; this._fileStorage = fileStorage; var formats = this._bufer.ViewModel.Clip.GetFormats(); string buferTitle = null; var clipFiles = this._bufer.ViewModel.Clip.GetData(DataFormats.FileDrop) as string[]; if (clipFiles != null && clipFiles.Length > 0) { var firstFile = clipFiles.First(); var onlyFolders = clipFiles.Select(f => this._fileStorage.GetFileAttributes(f).HasFlag(FileAttributes.Directory)) .All(f => f); if (clipFiles.Length == 1) { buferTitle = this._MakeSpecialBuferText( firstFile.Length < settingsGetter.MaxFilePathLengthForBuferTitle ? firstFile : (onlyFolders ? Resource.FolderBufer : Resource.FileBufer));// TODO (m) these resources are duplicated in BuferMAN.Application project } else { buferTitle = this._MakeSpecialBuferText($"{(onlyFolders ? Resource.FoldersBufer : Resource.FilesBufer)} ({clipFiles.Length})"); } } else { if (formats.Contains(ClipboardFormats.CUSTOM_IMAGE_FORMAT) || formats.Contains(ClipboardFormats.FILE_CONTENTS_FORMAT)) { this._bufer.ApplyFontStyle(FontStyle.Italic | FontStyle.Bold); } } string buferText = buferTitle ?? this._bufer.ViewModel.TextRepresentation; if (string.IsNullOrWhiteSpace(buferText)) { this._bufer.ApplyFontStyle(FontStyle.Italic | FontStyle.Bold); this._bufer.ViewModel.IsChangeTextAvailable = false; if (buferText == null) { if (formats.Any(f => string.Equals(f, ClipboardFormats.VISUAL_STUDIO_PROJECT_ITEMS, StringComparison.InvariantCultureIgnoreCase))) { buferText = "<< VISUAL STUDIO project items >>"; } else { buferText = Resource.NotTextBufer; // TODO (l) maybe track such cases and/or ask user to send info (at least formats list) of this bufer? // Or user can think of some name for this combination of formats } } else { buferText = this._MakeSpecialBuferText($"{buferText.Length} {Resource.WhiteSpaces}"); this._bufer.ViewModel.TooltipTitle = buferText; } } this._bufer.ViewModel.DefaultBackColor = this._bufer.BackColor; buferText = buferText.Trim(); this._bufer.SetText(buferText); this._bufer.ViewModel.OriginBuferTitle = buferText; this._bufer.SetMouseOverToolTip(this._bufer.ViewModel.TextRepresentation); this._bufer.ViewModel.TooltipTitle = this._bufer.ViewModel.TooltipTitle ?? buferTitle; if (!string.IsNullOrWhiteSpace(this._bufer.ViewModel.TooltipTitle)) { this._bufer.MouseOverTooltip.ToolTipTitle = this._bufer.ViewModel.TooltipTitle; this._bufer.FocusTooltip.ToolTipTitle = this._bufer.ViewModel.TooltipTitle; } IBuferTypeMenuGenerator buferTypeMenuGenerator = null; if (Uri.TryCreate(this._bufer.ViewModel.OriginBuferTitle, UriKind.Absolute, out var uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps)) { buferTypeMenuGenerator = new HttpUrlBuferMenuGenerator(this._bufer.ViewModel.OriginBuferTitle, this._settingsGetter, this._settingsSetter); } else { var files = this._bufer.ViewModel.Clip.GetData(DataFormats.FileDrop) as string[]; if (files != null && files.Length > 0) { var firstFile = files.First(); if (files.Length == 1) { buferTypeMenuGenerator = new FileBuferMenuGenerator(firstFile); } } } if (formats.Contains(ClipboardFormats.CUSTOM_IMAGE_FORMAT)) { var image = this._bufer.ViewModel.Clip.GetData(ClipboardFormats.CUSTOM_IMAGE_FORMAT) as Image; if (image != null) { this._bufer.ViewModel.Representation = image; this._bufer.MouseOverTooltip.IsBalloon = false; this._bufer.MouseOverTooltip.OwnerDraw = true; this._bufer.MouseOverTooltip.Popup += (object sender, PopupEventArgs e) => { e.ToolTipSize = new Size((int)(image.Width * IMAGE_SCALE), (int)(image.Height * IMAGE_SCALE)); }; this._bufer.MouseOverTooltip.Draw += (object sender, DrawToolTipEventArgs e) => { using (var b = new TextureBrush(new Bitmap(image))) { b.ScaleTransform(IMAGE_SCALE, IMAGE_SCALE); var g = e.Graphics; g.FillRectangle(b, e.Bounds); } }; } } this._bufer.AddOnFocusHandler(this._Bufer_GotFocus); this._bufer.AddOnUnfocusHandler(this._Bufer_LostFocus); var buferSelectionHandler = this._buferSelectionHandlerFactory.CreateHandler(this._bufer, bufermanHost); if (this._settingsGetter.IsBuferClickingExplained) { this._bufer.AddOnClickHandler(buferSelectionHandler.DoOnClipSelection); } else { this._bufer.AddOnClickHandler((object sender, EventArgs e) => { if (this._settingsGetter.IsBuferClickingExplained) { buferSelectionHandler.DoOnClipSelection(sender, e); } else { this._bufermanHost.UserInteraction.ShowPopup(Resource.BuferClickingExplanationText, Application.ProductName); this._settingsSetter.MarkThatBuferClickingWasExplained(); } }); } var buferContextMenuState = new BuferContextMenuState( clipboardBuferService, buferSelectionHandler, bufermanHost, () => Resource.MenuPin, // TODO (m) remove these actions () => Resource.MenuUnpin, () => Resource.MenuAddedToFile, bufer); bufer.ContextMenu = buferContextMenuGenerator.GenerateContextMenuItems(buferContextMenuState, bufermanHost, buferTypeMenuGenerator); foreach (var plugin in plugins) if (plugin.Available && plugin.Enabled) { try { plugin.UpdateBuferItem(buferContextMenuState); } catch (Exception exc) { bufermanHost .UserInteraction .ShowPopup(exc.Message, plugin.Name); } } }
public Account(IFileStorage storage) { __AudioStorage = new CacheStorage.CacheStorage(storage); }
public DocumentsService(IDocumentsRepository repository, IFileStorage fileStorage) { _repository = repository; _fileStorage = fileStorage; }
public FilesController(IFileStorage storage) { _storage = storage; }
internal static void ShouldHaveAddedBookImage(int bookId, IDbConnection dbConnection, IFileStorage fileStorage) { var imageUrl = dbConnection.GetBookImageUrl(bookId); imageUrl.Should().NotBeNull(); var image = fileStorage.GetFile(imageUrl, CancellationToken.None).Result; image.Should().NotBeNullOrEmpty(); }
internal static void ShouldHaveUpdatedBookImage(int bookId, byte[] newImage, IDbConnection dbConnection, IFileStorage fileStorage) { var imageUrl = dbConnection.GetBookImageUrl(bookId); imageUrl.Should().NotBeNull(); var image = fileStorage.GetFile(imageUrl, CancellationToken.None).Result; image.Should().NotBeNull().And.Equal(newImage); }
public override void Run() { try { IOConnectionInfo ioc = _app.CurrentDb.Ioc; IFileStorage fileStorage = _app.GetFileStorage(ioc); if (!(fileStorage is CachingFileStorage)) { throw new Exception("Cannot sync a non-cached database!"); } StatusLogger.UpdateMessage(UiStringKey.SynchronizingCachedDatabase); CachingFileStorage cachingFileStorage = (CachingFileStorage)fileStorage; //download file from remote location and calculate hash: StatusLogger.UpdateSubMessage(_app.GetResourceString(UiStringKey.DownloadingRemoteFile)); string hash; MemoryStream remoteData; try { remoteData = cachingFileStorage.GetRemoteDataAndHash(ioc, out hash); Kp2aLog.Log("Checking for file change. Current hash = " + hash); } catch (FileNotFoundException) { StatusLogger.UpdateSubMessage(_app.GetResourceString(UiStringKey.RestoringRemoteFile)); cachingFileStorage.UpdateRemoteFile(ioc, _app.GetBooleanPreference(PreferenceKey.UseFileTransactions)); Finish(true, _app.GetResourceString(UiStringKey.SynchronizedDatabaseSuccessfully)); Kp2aLog.Log("Checking for file change: file not found"); return; } //check if remote file was modified: var baseVersionHash = cachingFileStorage.GetBaseVersionHash(ioc); Kp2aLog.Log("Checking for file change. baseVersionHash = " + baseVersionHash); if (baseVersionHash != hash) { //remote file is modified if (cachingFileStorage.HasLocalChanges(ioc)) { //conflict! need to merge _saveDb = new SaveDb(_context, _app, new ActionOnFinish(ActiveActivity, (success, result, activity) => { if (!success) { Finish(false, result); } else { Finish(true, _app.GetResourceString(UiStringKey.SynchronizedDatabaseSuccessfully)); } _saveDb = null; }), _app.CurrentDb, false, remoteData); _saveDb.Run(); _app.CurrentDb.UpdateGlobals(); _app.MarkAllGroupsAsDirty(); } else { //only the remote file was modified -> reload database. //note: it's best to lock the database and do a complete reload here (also better for UI consistency in case something goes wrong etc.) _app.TriggerReload(_context); Finish(true); } } else { //remote file is unmodified if (cachingFileStorage.HasLocalChanges(ioc)) { //but we have local changes -> upload: StatusLogger.UpdateSubMessage(_app.GetResourceString(UiStringKey.UploadingFile)); cachingFileStorage.UpdateRemoteFile(ioc, _app.GetBooleanPreference(PreferenceKey.UseFileTransactions)); StatusLogger.UpdateSubMessage(""); Finish(true, _app.GetResourceString(UiStringKey.SynchronizedDatabaseSuccessfully)); } else { //files are in sync: just set the result Finish(true, _app.GetResourceString(UiStringKey.FilesInSync)); } } } catch (Exception e) { Kp2aLog.LogUnexpectedError(e); Finish(false, e.Message); } }
public TemplateManager(ITemplateService templateService, IFileStorage fileStorage) { _fileStorage = fileStorage; _templateService = templateService; }
public EventPostsJob(IQueue <EventPost> queue, EventParserPluginManager eventParserPluginManager, EventPipeline eventPipeline, IMetricsClient metricsClient, UsageService usageService, IProjectRepository projectRepository, IFileStorage storage, JsonSerializerSettings jsonSerializerSettings, ILoggerFactory loggerFactory = null) : base(queue, loggerFactory) { _eventParserPluginManager = eventParserPluginManager; _eventPipeline = eventPipeline; _metricsClient = metricsClient; _usageService = usageService; _projectRepository = projectRepository; _storage = storage; _jsonSerializerSettings = jsonSerializerSettings; AutoComplete = false; }
public DocumentsController(NiisWebContext context, IDocumentGeneratorFactory templateGeneratorFactory, ITemplateUserInputChecker templateUserInputChecker, IFileStorage fileStorage, IAttachmentHelper attachmentHelper, IMediator mediator) { _context = context; _fileStorage = fileStorage; _mediator = mediator; }
public static Task <bool> SaveFileAsync(this IFileStorage storage, string path, string contents) { return(storage.SaveFileAsync(path, new MemoryStream(Encoding.UTF8.GetBytes(contents ?? String.Empty)))); }
public SystemHealthChecker(ICacheClient cacheClient, IElasticClient elasticClient, IFileStorage storage, ILogger <SystemHealthChecker> logger) { _cacheClient = new ScopedCacheClient(cacheClient, "health"); _elasticClient = elasticClient; _storage = storage; _logger = logger; }
public static ICollection <FileInfo> GetQueueFiles(this IFileStorage storage, string queueName, int?limit = null) { var files = storage.GetFileList(queueName + "\\q\\*.json", limit.HasValue ? limit * 2 : null).OrderByDescending(f => f.Created); return(limit.HasValue ? files.Take(limit.Value).ToList() : files.ToList()); }
public ContentManagementService(IContentManagementRepository repository, IFileStorage fileStorage) { _repository = repository; _fileStorage = fileStorage; }
public static void SaveObject <T>(this IFileStorage storage, string path, T data, IJsonSerializer serializer) { storage.SaveFile(path, serializer.Serialize(data)); }
public HomeController(IFileStorage storage) { Storage = storage ?? throw new ArgumentNullException(nameof(storage)); Storage.RemoveOldFiles(); }
public AddIssueContentRequestHandler(IIssueRepository issueRepository, IFileRepository fileRepository, IFileStorage fileStorage) { _issueRepository = issueRepository; _fileRepository = fileRepository; _fileStorage = fileStorage; }
public ItemGroupDeletedEvent(IFileStorage fileStorage, IMessageBroker messageBroker) { _fileStorage = fileStorage; _messageBroker = messageBroker; }
public static async Task <string> EnqueueAsync(this IQueue <EventPost> queue, EventPostInfo data, IFileStorage storage, bool shouldArchive = true, CancellationToken cancellationToken = default(CancellationToken)) { string path = $"q\\{Guid.NewGuid().ToString("N")}.json"; if (!await storage.SaveObjectAsync(path, data, cancellationToken).AnyContext()) { return(null); } return(await queue.EnqueueAsync(new EventPost { FilePath = path, ShouldArchive = shouldArchive }).AnyContext()); }
public static string Enqueue(this IQueue <EventPost> queue, EventPostInfo data, IFileStorage storage, bool shouldArchive = true) { string path = String.Format("q\\{0}.json", Guid.NewGuid().ToString("N")); try { if (!storage.SaveObject(path, data)) { return(null); } } catch (Exception ex) { Log.Error().Exception(ex).Message("Error saving event post data to storage.").Write(); } return(queue.Enqueue(new EventPost { FilePath = path, ShouldArchive = shouldArchive })); }