private async Task TakeOffline(IRemoteClient client, Deployment deployment) { if (string.IsNullOrEmpty(deployment.OfflineFile)) { return; } IRemoteFolder folder = await GetFolder(client, deployment.RemotePath); IRemoteFile offlineFile = folder?.Files.FirstOrDefault(x => x.Name.StartsWith(deployment.OfflineFile, StringComparison.OrdinalIgnoreCase)); if (offlineFile == null) { return; } if (offlineFile.Name.Equals(deployment.OfflineFile, StringComparison.OrdinalIgnoreCase)) { return; } await client.MoveFile(offlineFile.Path, $"{folder.Path}{client.PathSeparator}{deployment.OfflineFile}"); _remoteFolderCache.Remove(folder.Path); }
public IFileVersionMetadata WriteRemoteFile(IFolderMetadata folderMetadata, IRemoteFile remoteFile) { if (folderMetadata == null) { throw new ArgumentNullException("folderMetadata"); } if (remoteFile == null) { throw new ArgumentNullException("remoteFile"); } if (string.IsNullOrEmpty(remoteFile.Name)) { throw new ArgumentNullException("remoteFile.Name"); } if (remoteFile.Stream == null) { throw new ArgumentNullException("remoteFile.Stream"); } IBlobFileMetadata blobFileMetadata = this.BlobMetadataAdapter.CreateFile(folderMetadata, remoteFile.Name); blobFileMetadata.Name = remoteFile.Name; //резервация параметров сохранения файла с blobFileMetadata.EnsureRemoteSaveProperties(remoteFile); //запись файла IFileVersionMetadata savedVersion = this.WriteInternal(blobFileMetadata, remoteFile.Stream, remoteFile.TimeCreated); return(savedVersion); }
public PersistentService(ISerializer serializer, ILinqService linqService, IRemoteFile remoteFile) { _serializer = serializer; _linqService = linqService; _remoteFile = remoteFile; }
public bool StartVideoDownload(RemoteVideoFile remoteFile) { if (!this.IsDownloading) { string destinationFilePath = this.GetPathSafety(remoteFile); if (!this.CheckLocalVideoExist(destinationFilePath, remoteFile.Size)) { this.downloadId = this.hikApi.VideoService.StartDownloadFile(this.session.UserId, remoteFile.Name, destinationFilePath); this.logger.Info($"{remoteFile.ToUserFriendlyString()}- downloading"); this.currentDownloadFile = remoteFile; this.progress = this.config.ShowProgress ? this.progressFactory.Create() : default(IProgressBar); return(true); } this.logger.Info($"{remoteFile.ToUserFriendlyString()}- exist"); return(false); } else { this.logger.Warn("HikClient.StartDownload : Downloading, please stop firstly!"); return(false); } }
private void downloadButton_Click(object sender, EventArgs e) { if (storage == null) { MessageBox.Show(this, "Not connected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } if (remoteListView.SelectedIndices.Count != 1) { MessageBox.Show(this, "Please select only one file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } IRemoteFile file = remoteListView.SelectedItems[0].Tag as IRemoteFile; saveFileDialog1.FileName = Path.GetFileName(file.Name); if (saveFileDialog1.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) { try { File.WriteAllBytes(saveFileDialog1.FileName, file.ReadAllBytes()); MessageBox.Show(this, "File downloaded.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show(this, "File download failed." + Environment.NewLine + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } }
public AnalyzeReportCommand(IRemoteFile remoteFile) { Debug.Assert(remoteFile != null); this._remoteFile = remoteFile; Name = "analyze"; Description = "will analyze the template-report.json file and return some info"; }
public NuGetPackageDownloaderTests() { httpClient = new HttpClient(); remoteFile = new RemoteFile(); nugetHelper = new NuGetHelper(remoteFile); nugetDownloader = new NuGetPackageDownloader(nugetHelper, remoteFile); sampleFileHelper = new SampleFileHelper(); }
public RemoteDeploy(IRemoteCommand remoteCommand, IRemoteFile remoteFile, ManagedProcess.Factory managedProcessFactory, IFileSystem fileSystem) { _remoteCommand = remoteCommand; _remoteFile = remoteFile; _managedProcessFactory = managedProcessFactory; _fileSystem = fileSystem; }
public AnalyzeTemplateCommand(IReporter reporter, ITemplateAnalyzer analyzer, IRemoteFile remoteFile) : base() { Debug.Assert(reporter != null); Debug.Assert(analyzer != null); _reporter = reporter; _templateAnalyzer = analyzer; _remoteFile = remoteFile; }
private string GetPathSafety(IRemoteFile remoteFile) { string workingDirectory = this.GetWorkingDirectory(remoteFile); this.filesHelper.FolderCreateIfNotExist(workingDirectory); string destinationFilePath = this.GetFullPath(remoteFile, workingDirectory); return(destinationFilePath); }
private static async Task <DeploymentDirectoryConfig> FetchDeploymentConfig(IRemoteDirectory deploymentRootDir) { IRemoteFile configFile = await deploymentRootDir.GetFile(Constants.DeploymentConfigFileName); if (!await configFile.Exists()) { Trace.TraceInformation("The deployments config file {0} was not found in the {1} directory; i.e. NO applications to deploy.", Constants.DeploymentConfigFileName, deploymentRootDir.Name); return(new DeploymentDirectoryConfig(new List <DeploymentConfig>())); } return(await new DeploymentConfigParser().ParseData(configFile.DownloadText().Result)); }
public TemplateReport(INuGetHelper nugetHelper, HttpClient httpClient, INuGetPackageDownloader nugetDownloader, IRemoteFile remoteFile) { Debug.Assert(nugetHelper != null); Debug.Assert(httpClient != null); Debug.Assert(nugetDownloader != null); Debug.Assert(remoteFile != null); _nugetHelper = nugetHelper; _httpClient = httpClient; _nugetDownloader = nugetDownloader; _remoteFile = remoteFile; }
public void EnsureRemoteSaveProperties(IRemoteFile remoteFile) { if (remoteFile == null) { throw new ArgumentNullException("remoteFile"); } if (remoteFile.CreatedStorageNode == null) { throw new ArgumentNullException("remoteFile.CreatedStorageNode"); } if (remoteFile.UniqueID == null) { throw new ArgumentNullException("remoteFile.UniqueID"); } if (remoteFile.VersionID == null) { throw new ArgumentNullException("fileVersionUniqueID"); } this.UniqueID = remoteFile.UniqueID; this.VersionUniqueID = remoteFile.VersionID; if (this.ID > 0) { //файл уже существует, все версии, которые в него загружаются //должны иметь тот же идентификатор файла //новая версия файла с удаленного узла не соответствует этому условию if (this.UniqueID != remoteFile.UniqueID) { throw new Exception(string.Format("Идентификатор локального файла не совпадает с идентификатором файла с удаленного узла.")); } //сравниваем даты изменения файлов, если с удаленного сервера //пришла более новая версия, то записываем ее и в файл //в случае если пришла более ранняя версия ничего не делаем. //у файла должен остаться идентификатор последней версии //файл вообще не должен пересохраниться if (this.TimeModified > remoteFile.TimeCreated) { this.PreventSavePreviousVersion = true; } else { this.TimeModified = remoteFile.TimeCreated; } } this.RemoteFile = remoteFile; }
private void deleteButton_Click(object sender, EventArgs e) { if (storage == null) { MessageBox.Show(this, "Not connected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } if (remoteListView.SelectedIndices.Count == 0) { MessageBox.Show(this, "Please select files to delete.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } if (MessageBox.Show(this, "Are you sure you want to delete the selected files?", "Confirm deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == System.Windows.Forms.DialogResult.No) { return; } bool allSuccess = true; remoteListView.BeginUpdate(); foreach (ListViewItem item in remoteListView.SelectedItems) { IRemoteFile file = item.Tag as IRemoteFile; try { bool success = file.Delete(); if (!success) { allSuccess = false; MessageBox.Show(this, file.Name + " failed to delete.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { item.Remove(); } } catch (Exception ex) { MessageBox.Show(this, file.Name + " failed to delete." + Environment.NewLine + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } remoteListView.EndUpdate(); updateQuota(); if (allSuccess) { MessageBox.Show(this, "Files deleted.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
private void DeleteCurrentFile() { if (this.currentDownloadFile != null) { string path = this.GetFullPath(this.currentDownloadFile); this.logger.Warn($"Removing file {path}"); this.filesHelper.DeleteFile(path); this.currentDownloadFile = null; } else { this.logger.Warn("HikClient.DeleteCurrentFile : Nothing to delete"); } }
public ReportCommand(HttpClient httpClient, INuGetHelper nugetHelper, IRemoteFile remoteFile, INuGetPackageDownloader nugetPkgDownloader, TemplatesShared.IReporter reporter) : base() { Debug.Assert(httpClient != null); Debug.Assert(nugetHelper != null); Debug.Assert(remoteFile != null); Debug.Assert(nugetPkgDownloader != null); _httpClient = httpClient; _nugetHelper = nugetHelper; _remoteFile = remoteFile; _nugetPkgDownloader = nugetPkgDownloader; _reporter = reporter; Name = "report"; Description = "will create the template report into a json file"; }
public void InIt() { _id = Guid.NewGuid(); _stubModel = MockRepository.GenerateStub <IModel>(); _stubTeamPlayers = MockRepository.GenerateStub <TeamPlayers>(); _stubDtoPlayer = MockRepository.GenerateStub <PlayerDTO>(); _stubPlayer = MockRepository.GenerateStub <Player>(); _stubSerializer = MockRepository.GenerateStub <ISerializer>(); _stubLinqService = MockRepository.GenerateStub <ILinqService>(); _stubRemoteFile = MockRepository.GenerateStub <IRemoteFile>(); _stubPersistentService = MockRepository.GenerateStub <IPersistentService>(); _target = new PersistentService(_stubSerializer, _stubLinqService, _stubRemoteFile); }
public CoreAttachWindow(IServiceProvider serviceProvider) { var serviceManager = new ServiceManager(); _taskContext = serviceManager.GetJoinableTaskContext(); _dialogUtil = new DialogUtil(); IExtensionOptions options = ((YetiVSIService)serviceManager.RequireGlobalService(typeof(YetiVSIService))) .Options; var managedProcessFactory = new ManagedProcess.Factory(); var progressDialogFactory = new ProgressDialog.Factory(); _cancelableTaskFactory = new CancelableTask.Factory(_taskContext, progressDialogFactory); _coreListRequest = new CoreListRequest.Factory().Create(); var jsonUtil = new JsonUtil(); var credentialConfigFactory = new CredentialConfig.Factory(jsonUtil); var accountOptionLoader = new VsiAccountOptionLoader(options); var credentialManager = new CredentialManager(credentialConfigFactory, accountOptionLoader); _developerAccount = credentialManager.LoadAccount(); IRemoteCommand remoteCommand = new RemoteCommand(managedProcessFactory); _remoteFile = new RemoteFile(managedProcessFactory); var cloudConnection = new CloudConnection(); var sdkConfigFactory = new SdkConfig.Factory(jsonUtil); // NOTE: the lifetime of this CloudRunner is limited to the current CoreAttachWindow. _cloudRunner = new CloudRunner(sdkConfigFactory, credentialManager, cloudConnection, new GgpSDKUtil()); _gameletClientFactory = new GameletClient.Factory(); var sshKeyLoader = new SshKeyLoader(managedProcessFactory); var sshKnownHostsWriter = new SshKnownHostsWriter(); _sshManager = new SshManager(_gameletClientFactory, _cloudRunner, sshKeyLoader, sshKnownHostsWriter, remoteCommand); _debugSessionMetrics = new DebugSessionMetrics( serviceProvider.GetService(typeof(SMetrics)) as IMetrics); _debugSessionMetrics.UseNewDebugSessionId(); _actionRecorder = new ActionRecorder(_debugSessionMetrics); InitializeComponent(); _instanceSelectionWindowFactory = new ProjectInstanceSelection.Factory(); _paramsFactory = new DebugEngine.DebugEngine.Params.Factory(jsonUtil); SelectInstanceOnInit(); }
public void DownloadFile(int userId, IRemoteFile remoteFile, string destinationPath) { if (remoteFile.Size > 0) { NET_DVR_PIC_PARAM temp = new NET_DVR_PIC_PARAM { pDVRFileName = remoteFile.Name, pSavedFileBuf = Marshal.AllocHGlobal((int)remoteFile.Size), dwBufLen = (uint)remoteFile.Size }; if (SdkHelper.InvokeSDK(() => NET_DVR_GetPicture_V50(userId, ref temp))) { SdkHelper.InvokeSDK(() => NET_DVR_GetPicture(userId, temp.pDVRFileName, destinationPath)); } Marshal.FreeHGlobal(temp.pSavedFileBuf); } }
private void UpdateProgressInternal(int progressValue) { if (progressValue >= ProgressBarMinimum && progressValue < ProgressBarMaximum) { this.progress?.Report((double)progressValue / ProgressBarMaximum); } else if (progressValue == ProgressBarMaximum) { this.StopVideoDownload(); this.currentDownloadFile = null; this.logger.Info("- downloaded"); } else { this.StopVideoDownload(); throw new InvalidOperationException($"HikClient.UpdateDownloadProgress failed, progress value = {progressValue}"); } }
private async Task PutOnline(IRemoteClient client, Deployment deployment) { if (string.IsNullOrEmpty(deployment.OfflineFile)) { return; } IRemoteFolder folder = await GetFolder(client, deployment.RemotePath); IRemoteFile offlineFile = folder?.Files.FirstOrDefault(x => x.Name.Equals(deployment.OfflineFile)); if (offlineFile == null) { return; } await client.MoveFile(offlineFile.Path, $"{offlineFile.Path}.x"); _remoteFolderCache.Remove(folder.Path); }
protected virtual void Dispose(bool disposing) { if (!this.disposedValue) { if (disposing) { this.progress?.Dispose(); } this.logger.Info($"Logout the device"); if (this.session != null) { this.hikApi.Logout(this.session.UserId); } this.session = null; this.progress = null; this.currentDownloadFile = null; this.hikApi.Cleanup(); this.disposedValue = true; } }
public NuGetHelper(IRemoteFile remoteFile) { RemoteFile = remoteFile; }
public NuGetPackageDownloader(INuGetHelper nugetHelper, IRemoteFile remoteFile) { _nugetHelper = nugetHelper; _remoteFile = remoteFile; }
protected async Task <IEnumerable <NuGetPackage> > ConsumeAsync(BufferBlock <NuGetPackage> packkageQueue, IRemoteFile remoteFile) { var resultList = new List <NuGetPackage>(); while (await packkageQueue.OutputAvailableAsync()) { var pkg = await packkageQueue.ReceiveAsync <NuGetPackage>(); var downloadUrl = _nugetHelper.GetDownloadUrlFor(pkg); var localFilepath = await remoteFile.GetRemoteFileAsync(downloadUrl, pkg.GetPackageFilename()); pkg.LocalFilepath = localFilepath; resultList.Add(pkg); } return(resultList); }
private string GetFullPath(IRemoteFile file, string directory = null) { string folder = directory ?? this.GetWorkingDirectory(file); return(this.filesHelper.CombinePath(folder, file.ToFileNameString())); }
public IFileVersionMetadata WriteRemoteFileVersion(IFileMetadata fileMetadata, IRemoteFile remoteFile) { if (fileMetadata == null) { throw new ArgumentNullException("fileMetadata"); } if (fileMetadata.FolderMetadata == null) { throw new ArgumentNullException("fileMetadata.FolderMetadata"); } if (remoteFile == null) { throw new ArgumentNullException("remoteFile"); } if (remoteFile.Stream == null) { throw new ArgumentNullException("remoteFile.Stream"); } this.Logger.WriteFormatMessage("WriteFileVersion:Начало записи новой версии файла, fileMetadata.Name: {0}, fileMetadata.UniqueID: {1}", fileMetadata.Name, fileMetadata.UniqueID); IBlobFileMetadata blobFileMetadata = (IBlobFileMetadata)fileMetadata; if (!string.IsNullOrEmpty(remoteFile.Name)) { blobFileMetadata.Name = remoteFile.Name; } //резервация параметров сохранения blobFileMetadata.EnsureRemoteSaveProperties(remoteFile); //запись версии файла IFileVersionMetadata savedVersion = this.WriteInternal(blobFileMetadata, remoteFile.Stream, remoteFile.TimeCreated); return(savedVersion); }
private string GetWorkingDirectory(IRemoteFile file) { return(this.filesHelper.CombinePath(this.config.DestinationFolder, file.ToDirectoryNameString())); }
public void InIt() { _id = Guid.NewGuid(); _stubModel = MockRepository.GenerateStub<IModel>(); _stubTeamPlayers = MockRepository.GenerateStub<TeamPlayers>(); _stubDtoPlayer = MockRepository.GenerateStub<PlayerDTO>(); _stubPlayer = MockRepository.GenerateStub<Player>(); _stubSerializer = MockRepository.GenerateStub<ISerializer>(); _stubLinqService = MockRepository.GenerateStub<ILinqService>(); _stubRemoteFile = MockRepository.GenerateStub<IRemoteFile>(); _stubPersistentService = MockRepository.GenerateStub<IPersistentService>(); _target = new PersistentService(_stubSerializer, _stubLinqService,_stubRemoteFile); }
private void ProcessRemoteFilesInternal(ReplicationFolder replicationFolder, Tuple <Guid, Guid>[] remoteFiles) { if (replicationFolder == null) { throw new ArgumentNullException("replicationFolder"); } if (remoteFiles == null || remoteFiles.Length == 0) { throw new ArgumentNullException("remoteFiles"); } //словарь существующих файлов. Dictionary <Guid, File> existsFiles = new Dictionary <Guid, File>(); Dictionary <string, byte> uniqueFileVersions = new Dictionary <string, byte>(); //формируем словарь существующих файлов и списков файлов, //которых не существует и которые необходимо реплицировать. List <RemoteFileInfo> filesToDownload = new List <RemoteFileInfo>(); foreach (Tuple <Guid, Guid> fileVersionInfo in remoteFiles) { Guid fileID = fileVersionInfo.Item1; Guid fileVersionID = fileVersionInfo.Item2; bool fileVersionExists = false; string key = string.Format("{0}_{1}", fileID, fileVersionID); if (uniqueFileVersions.ContainsKey(key)) { continue; } uniqueFileVersions.Add(key, 0); File file = null; try { file = this.Engine.GetFileInternal(replicationFolder.Folder.Url, fileID, null, false); } catch (Exception fileEx) { //таблицы с файлов может не быть. this.Logger.WriteMessage(fileEx.ToString(), LogLevel.Error); } if (file != null) { fileVersionExists = file.VersionUniqueID == fileVersionID || file.GetVersion(fileVersionID, false) != null; if (!existsFiles.ContainsKey(file.UniqueID)) { existsFiles.Add(file.UniqueID, file); } } if (!fileVersionExists) { filesToDownload.Add(new RemoteFileInfo(fileVersionInfo, replicationFolder.Folder)); } } if (filesToDownload.Count == 0) { return; } DateTime?lastSync = null; try { foreach (RemoteFileInfo remoteFileInfo in filesToDownload) { IRemoteFile remoteFile = null; try { remoteFile = this.Transport.GetReplicationFile( replicationFolder.SourceStorage, remoteFileInfo.Folder.Url, remoteFileInfo.UniqueID, remoteFileInfo.VersionID); if (remoteFile == null) { throw new Exception(string.Format("Не удалось получить файла с идентификатором {0} с узла {1}", remoteFileInfo.UniqueID, replicationFolder.SourceStorage.Host)); } StorageNode typedNode = (StorageNode)replicationFolder.SourceStorage; remoteFile.CreatedStorageNode = typedNode.Metadata; var stream = remoteFile.Stream; if (stream == null) { throw new Exception(string.Format("Не удалось получить поток файла с идентификатором {0} с узла {1}", remoteFileInfo.UniqueID, replicationFolder.SourceStorage.Host)); } File localFile = null; if (existsFiles.ContainsKey(remoteFile.UniqueID)) { localFile = existsFiles[remoteFile.UniqueID]; } if (localFile == null) { //загружаем новый файл IFileVersionMetadata fileVersion = this.Engine.DataAdapter.WriteRemoteFile(replicationFolder.TypedFolder.Metadata, remoteFile); localFile = new File(this.Engine, replicationFolder.Folder, fileVersion.FileMetadata); //добавляем в коллекцию существующих на текущем узле existsFiles.Add(localFile.UniqueID, localFile); } else { //файл уже существует, добавляем только новую версию файла this.Engine.DataAdapter.WriteRemoteFileVersion(localFile.Metadata, remoteFile); } //обновляем дату синхронизации по дате создания версии lastSync = remoteFile.TimeCreated; } catch (Exception remoteFileEx) { throw new Exception(string.Format("Ошибка при репликации файла {0} с узла {1}", remoteFileInfo.UniqueID, replicationFolder.SourceStorage.Host), remoteFileEx); } finally { try { if (remoteFile != null && remoteFile.Stream != null) { remoteFile.Stream.Dispose(); } } catch (Exception innerEx) { this.Logger.WriteMessage(innerEx.ToString(), LogLevel.Error); } } } } catch (Exception ex) { this.Logger.WriteMessage(ex.ToString(), LogLevel.Error); } if (lastSync.HasValue) { replicationFolder.Metadata.LastSyncTime = lastSync.Value; replicationFolder.Update(); } }