/// <summary> /// Производит атаку на ячейку /// </summary> private void AtackCell() { Cell selectedCell = GetSelectedCell(); Cell clickedCell = GetFocusedCell(); if (selectedCell != null && clickedCell != null) { if (clickedCell?.Owner == GetActivePlayer()) { _currentGameState = GameStates.Select; selectedCell.DisactiveCell(); clickedCell.ActiveCell(); } else { _moveRunner.Move(selectedCell, clickedCell, GetActivePlayer()); if (IsFinishedGame()) { _currentGameState = GameStates.Finished; FinishedEvent?.Invoke(this, EventArgs.Empty); } } } PaintEvent?.Invoke(); _button.CallPaintEvent(); }
private IEnumerator CallWrapper() { yield return(null); while (IsRunning) { if (IsPaused) { yield return(null); } else { if (Enumerator != null && Enumerator.MoveNext()) { yield return(Enumerator.Current); } else { IsRunning = false; } } } FinishedEvent?.Invoke(this, stoppedManually); }
/// <summary> /// 下载文件 /// </summary> /// <param name="fileId"></param> /// <param name="savePath">文件保存路径</param> public void DownLoadFile(DriveService driveService, string fileId, long fileSize, string savePath) { if (driveService == null) { return; } var request = driveService.Files.Get(fileId); var stream = new FileStream(savePath, FileMode.Create); // Add a handler which will be notified on progress changes. // It will notify on each chunk download and when the // download is completed or failed. try { request.MediaDownloader.ChunkSize = 8192;//配置chunk大小 request.MediaDownloader.ProgressChanged += (IDownloadProgress progress) => { switch (progress.Status) { case DownloadStatus.Downloading: { Console.WriteLine(progress.BytesDownloaded); ProgressEvent?.Invoke(progress.BytesDownloaded, fileSize); break; } case DownloadStatus.Completed: { Console.WriteLine("Download complete."); FinishedEvent?.Invoke(); break; } case DownloadStatus.Failed: { Console.WriteLine("Download failed."); FailedEvent?.Invoke(); break; } } }; request.Download(stream); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } finally { if (stream != null) { stream.Close(); stream = null; GC.Collect(); } } }
protected void OnAssigned(AssignableObject asg) { ++_assigned; if (Questions.Length != 0 && _assigned < 4) { int _a_tmp = _assigned - 1; Questions[_a_tmp].SetActive(false); Questions[_assigned].SetActive(true); _assignables = GetComponentsInChildren <AssignableObject>(); } //if (_assigned == _assignableCount) if (_assigned == 4) { FinishedEvent.Invoke(this); } }
/// <summary> /// 检查是否全部完成 /// </summary> /// <param name="pan"></param> private void VertifyFinished() { foreach (PanKey p in pans) { if (!p.CheckLocation(Columns)) { return; } } timer.Stop(); //恢复空白格子模板 Binding binding = new Binding("Template"); binding.Source = pans[1]; panNull.SetBinding(PanKey.TemplateProperty, binding); FinishedEvent.Invoke(Time.ToString()); }
/// <summary> /// /// </summary> /// <param name="client"></param> /// <param name="dropboxSourcePath">folder + "/" + file,这个/一定不能省略</param> /// <param name="savePath"></param> /// <param name="fileSize"></param> /// <returns></returns> public async Task <bool> DownLoadFile(DropboxClient client, string folder, string fileName, string savePath, long fileSize) { string dropboxSourcePath = ""; if (string.IsNullOrEmpty(folder)) { dropboxSourcePath = "/" + fileName; } else { dropboxSourcePath = folder + "/" + fileName; } using (var response = await client.Files.DownloadAsync(dropboxSourcePath)) { ulong aFileSize = response.Response.Size; const int aBufferSize = 4 * 1024 * 1024; var aBuffer = new byte[aBufferSize]; using (var aDropboxContentStream = await response.GetContentAsStreamAsync()) { int aLengthOfBytesRead = 0; using (FileStream fs = new FileStream(savePath, FileMode.Create)) { long currentSize = 0; while ((aLengthOfBytesRead = aDropboxContentStream.Read(aBuffer, 0, aBufferSize)) > 0) { fs.Write(aBuffer, 0, aLengthOfBytesRead); currentSize += aLengthOfBytesRead; ProgressEvent?.Invoke(currentSize, fileSize); } } } FinishedEvent?.Invoke(); } return(true); }
/// <summary> /// /// </summary> /// <param name="graphClient"></param> /// <param name="fileId"></param> /// <param name="savePath">文件保存路径</param> /// <param name="fileSize"></param> /// <returns></returns> // Downloads the content of an existing file. public async Task <bool> DownLoadFile(GraphServiceClient graphClient, string fileId, string savePath, long fileSize) { const long DefaultChunkSize = 50 * 1024; // 50 KB, TODO: change chunk size to make it realistic for a large file. long ChunkSize = DefaultChunkSize; long offset = 0; // cursor location for updating the Range header. byte[] bytesInStream; // bytes in range returned by chunk download. // We'll use the file metadata to determine size and the name of the downloaded file // and to get the download URL. var driveItemInfo = await graphClient.Me.Drive.Items[fileId].Request().GetAsync(); // Get the download URL. This URL is preauthenticated and has a short TTL. object downloadUrl; driveItemInfo.AdditionalData.TryGetValue("@microsoft.graph.downloadUrl", out downloadUrl); // Get the number of bytes to download. calculate the number of chunks and determine // the last chunk size. long size = (long)driveItemInfo.Size; int numberOfChunks = Convert.ToInt32(size / DefaultChunkSize); // We are incrementing the offset cursor after writing the response stream to a file after each chunk. // Subtracting one since the size is 1 based, and the range is 0 base. There should be a better way to do // this but I haven't spent the time on that. int lastChunkSize = Convert.ToInt32(size % DefaultChunkSize) - numberOfChunks - 1; if (lastChunkSize > 0) { numberOfChunks++; } long currentSize = 0; // Create a file stream to contain the downloaded file. using (FileStream fileStream = new FileStream(savePath, FileMode.Create)) { for (int i = 0; i < numberOfChunks; i++) { // Setup the last chunk to request. This will be called at the end of this loop. if (i == numberOfChunks - 1) { ChunkSize = lastChunkSize; } // Create the request message with the download URL and Range header. HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, (string)downloadUrl); req.Headers.Range = new System.Net.Http.Headers.RangeHeaderValue(offset, ChunkSize + offset); // We can use the the client library to send this although it does add an authentication cost. // HttpResponseMessage response = await graphClient.HttpProvider.SendAsync(req); // Since the download URL is preauthenticated, and we aren't deserializing objects, // we'd be better to make the request with HttpClient. var client = new HttpClient(); HttpResponseMessage response = await client.SendAsync(req); using (Stream responseStream = await response.Content.ReadAsStreamAsync()) { bytesInStream = new byte[ChunkSize]; int read; do { read = responseStream.Read(bytesInStream, 0, (int)bytesInStream.Length); if (read > 0) { fileStream.Write(bytesInStream, 0, read); currentSize += read; ProgressEvent?.Invoke(currentSize, fileSize); } }while (read > 0); } offset += ChunkSize + 1; // Move the offset cursor to the next chunk. } } FinishedEvent?.Invoke(); return(true); }
/// <summary> /// 分块下载文件 /// </summary> /// <param name="url">下载的url</param> /// <param name="savePath">保存路径</param> /// <param name="fileSize">文件的大小</param> public async void Download(string url, string savePath, long fileSize = 0) { //获取文件大小 if (fileSize == 0) { fileSize = Size(url); } const long DefaultChunkSize = 50 * 1024; // 50 KB, TODO: change chunk size to make it realistic for a large file. long ChunkSize = DefaultChunkSize; long offset = 0; // cursor location for updating the Range header. byte[] bytesInStream; // bytes in range returned by chunk download. int numberOfChunks = Convert.ToInt32(fileSize / DefaultChunkSize); // We are incrementing the offset cursor after writing the response stream to a file after each chunk. // Subtracting one since the size is 1 based, and the range is 0 base. There should be a better way to do // this but I haven't spent the time on that. int lastChunkSize = Convert.ToInt32(fileSize % DefaultChunkSize) - numberOfChunks - 1; if (lastChunkSize > 0) { numberOfChunks++; } long currentSize = 0; // Create a file stream to contain the downloaded file. using (FileStream fileStream = new FileStream(savePath, FileMode.Create)) { for (int i = 0; i < numberOfChunks; i++) { // Setup the last chunk to request. This will be called at the end of this loop. if (i == numberOfChunks - 1) { ChunkSize = lastChunkSize; } // Create the request message with the download URL and Range header. HttpRequestMessage req = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, url); req.Headers.Range = new System.Net.Http.Headers.RangeHeaderValue(offset, ChunkSize + offset); var client = new HttpClient(); HttpResponseMessage response = await client.SendAsync(req); using (Stream responseStream = await response.Content.ReadAsStreamAsync()) { bytesInStream = new byte[ChunkSize]; int read; do { read = responseStream.Read(bytesInStream, 0, (int)bytesInStream.Length); if (read > 0) { fileStream.Write(bytesInStream, 0, read); currentSize += read; ProgressEvent?.Invoke(currentSize, fileSize); Debug.WriteLine(i + " : " + currentSize + " : " + fileSize); } }while (read > 0); } offset += ChunkSize + 1; // Move the offset cursor to the next chunk. } } FinishedEvent?.Invoke(); }
public async Task <bool> UpLoadFile(GraphServiceClient graphClient, string sourcePath, string fileID = null) { try { if (!System.IO.File.Exists(sourcePath)) { return(false); } System.IO.FileInfo info = new System.IO.FileInfo(sourcePath); long fileSize = info.Length; string fileName = System.IO.Path.GetFileName(sourcePath); long currentSize = 0; using (FileStream fileStream = new FileStream(sourcePath, FileMode.Open)) { // Create the upload session. The access token is no longer required as you have session established for the upload. // POST /v1.0/drive/root:/UploadLargeFile.bmp:/microsoft.graph.createUploadSession UploadSession uploadSession; if (string.IsNullOrEmpty(fileID)) { uploadSession = await graphClient.Me.Drive.Root.ItemWithPath(fileName).CreateUploadSession().Request().PostAsync(); } else { uploadSession = await graphClient.Me.Drive.Items[fileID].ItemWithPath(fileName).CreateUploadSession().Request().PostAsync(); } var maxChunkSize = 320 * 1024; // 320 KB - Change this to your chunk size. 5MB is the default. var provider = new ChunkedUploadProvider(uploadSession, graphClient, fileStream, maxChunkSize); // Setup the chunk request necessities var chunkRequests = provider.GetUploadChunkRequests(); var readBuffer = new byte[maxChunkSize]; var trackedExceptions = new List <Exception>(); DriveItem itemResult = null; //upload the chunks foreach (var request in chunkRequests) { // Do your updates here: update progress bar, etc. // ... // Send chunk request var result = await provider.GetChunkRequestResponseAsync(request, readBuffer, trackedExceptions); //这里时最终的一个结果 if (result.UploadSucceeded) { itemResult = result.ItemResponse; currentSize = (long)result.ItemResponse.Size; } else { currentSize += maxChunkSize; } ProgressEvent?.Invoke(currentSize, fileSize); } // Check that upload succeeded if (itemResult == null) { // Retry the upload // ... FailedEvent?.Invoke(); } else { FinishedEvent?.Invoke(); } return(true); } } catch (ServiceException e) { System.Diagnostics.Debug.WriteLine("We could not upload the file: " + e.Error.Message); FailedEvent?.Invoke(); return(false); } }
private void DownloadComplete(object sender, DownloadDataCompletedEventArgs args) { FinishedEvent?.Invoke(args.Result); }
/// <summary> ///上传文件到Cloud,如果传递同名的文件有什么影响 /// </summary> /// <param name="sourcePath"></param> public void UpLoadFile(DriveService driveService, string sourcePath, string parentId = null) { if (driveService == null) { return; } if (!System.IO.File.Exists(sourcePath)) { return; } System.IO.FileInfo info = new System.IO.FileInfo(sourcePath); long fileSize = info.Length; string fileName = System.IO.Path.GetFileName(sourcePath); var contentType = MimeMapping.GetMimeMapping(fileName); var fileMetadata = new File() { Name = fileName }; if (!string.IsNullOrEmpty(parentId)) { fileMetadata.Parents = new List <string>() { parentId }; } FilesResource.CreateMediaUpload request; using (var stream = new System.IO.FileStream(sourcePath, System.IO.FileMode.Open)) { request = driveService.Files.Create( fileMetadata, stream, contentType); request.Fields = "id"; request.ChunkSize = 262144;//配置chunk大小,must be a multiple of Google.Apis.Upload.ResumableUpload.MinimumChunkSize request.ProgressChanged += (IUploadProgress progress) => { switch (progress.Status) { case UploadStatus.Uploading: { // Console.WriteLine(progress.BytesSent); ProgressEvent?.Invoke(progress.BytesSent, fileSize); break; } case UploadStatus.Completed: { Console.WriteLine("Upload complete."); FinishedEvent?.Invoke(); break; } case UploadStatus.Failed: { Console.WriteLine("Upload failed."); FailedEvent?.Invoke(); break; } } }; request.Upload(); } var file = request.ResponseBody; Console.WriteLine("File ID: " + file.Id); }
/// <summary> /// /// </summary> /// <param name="client"></param> /// <param name="folder"></param> /// <param name="sourcePath"></param> public async void UpLoadFile(DropboxClient client, string folder, string sourcePath) { // Chunk size is 128KB. const int chunkSize = 128 * 1024; if (!System.IO.File.Exists(sourcePath)) { return; } System.IO.FileInfo info = new System.IO.FileInfo(sourcePath); long fileSize = info.Length; string fileName = System.IO.Path.GetFileName(sourcePath); string path; if (string.IsNullOrEmpty(folder)) { path = "/" + fileName; } else { path = folder + "/" + fileName; } //using (var stream = new MemoryStream(fileContent)) using (var stream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { int numChunks = (int)Math.Ceiling((double)stream.Length / chunkSize); byte[] buffer = new byte[chunkSize]; string sessionId = null; long currentSize = 0; for (var idx = 0; idx < numChunks; idx++) { var byteRead = stream.Read(buffer, 0, chunkSize); ProgressEvent?.Invoke(currentSize, fileSize); using (MemoryStream memStream = new MemoryStream(buffer, 0, byteRead)) { if (idx == 0) { if (numChunks == 1) { //小文件 await client.Files.UploadAsync(path, body : memStream); } else { var result = await client.Files.UploadSessionStartAsync(false, memStream); sessionId = result.SessionId; } } else { UploadSessionCursor cursor = new UploadSessionCursor(sessionId, (ulong)(chunkSize * idx)); if (idx == numChunks - 1) { await client.Files.UploadSessionFinishAsync(cursor, new CommitInfo(path), memStream); } else { await client.Files.UploadSessionAppendV2Async(cursor, false, memStream); } } } } FinishedEvent?.Invoke(); } }