private void HandleAsyncReceiveHeader(IAsyncResult asyncResult) { AsyncData asyncData = (AsyncData)asyncResult.AsyncState; Socket clientSock = asyncData.clientSock; try { asyncData.msgLength = clientSock.EndReceive(asyncResult); } catch { Debug.Log("TCPClient::HandleAsyncReceive() : EndReceive - 예외 " + m_clientSock.RemoteEndPoint.ToString()); Disconnect(); return; } if (asyncData.msgLength < 2) // 다시 해더 받기 { Debug.Log("TcpClient::헤더 오류 - 다시 헤더 받기"); if (!BeginReceiveHeader(asyncData, asyncData)) { return; } } short packetContentSize = BitConverter.ToInt16(asyncData.msg, 0); BeginReceiveContent(asyncData, packetContentSize, asyncData); }
private void HandleAsyncAccept(IAsyncResult asyncResult) { Socket listenSock = (Socket)asyncResult.AsyncState; Socket clientSock = listenSock.EndAccept(asyncResult); clientSockes.Add(clientSock); Debug.Log("TcpServer::Accept " + clientSock.RemoteEndPoint.ToString()); if (OnAccepted != null) { OnAccepted(clientSock); } AsyncCallback asyncReceiveCallback = new AsyncCallback(HandleAsyncReceive); AsyncData asyncData = new AsyncData(); asyncData.clientSock = clientSock; object ob = asyncData; try { clientSock.BeginReceive(asyncData.msg, 0, AsyncData.msgMaxLength, SocketFlags.None, asyncReceiveCallback, ob); } catch { DisconnectClient(clientSock); } AsyncCallback asyncAcceptCallback = new AsyncCallback(HandleAsyncAccept); ob = listenSock; listenSock.BeginAccept(asyncAcceptCallback, ob); }
public void HandleAsyncReceiveLength(IAsyncResult asyncResult) { AsyncData asyncData = (AsyncData)asyncResult.AsyncState; Socket clientSock = asyncData.clientSock; try { asyncData.msgSize = (short)clientSock.EndReceive(asyncResult); } catch { Console.WriteLine("클라이언트가 접속을 종료했습니다."); LoginUser.Remove(clientSock); clientSock.Close(); return; } if (asyncData.msgSize > 0) { int msgSize = BitConverter.ToInt16(asyncData.msg, 0); asyncData = new AsyncData(clientSock); clientSock.BeginReceive(asyncData.msg, 0, msgSize + UnityServer.packetType, SocketFlags.None, asyncReceiveDataCallBack, (Object)asyncData); } else { asyncData = new AsyncData(clientSock); clientSock.BeginReceive(asyncData.msg, 0, UnityServer.packetLength, SocketFlags.None, asyncReceiveLengthCallBack, (Object)asyncData); } }
// public method // start tcp server // set socket // set async call back public void ServerStart() { if (listenSocket.Connected) { return; } serverIP = GetLocalIPAddress(); // listen socket bind listenSocket.Bind(new IPEndPoint(IPAddress.Parse(serverIP), port)); // listen socket listen listenSocket.Listen(10); // add socket accept callback method AsyncCallback acceptCallback = new AsyncCallback(AcceptAsyncCallback); AsyncData asyncData = new AsyncData(); object asyncLinker = asyncData; asyncLinker = listenSocket; listenSocket.BeginAccept(acceptCallback, asyncLinker); Console.WriteLine("start server"); }
public Task ExecuteAsync(AsyncData data, WorkSession session, ICommandResultSender sender, CancellationToken cancellationToken) { var cursorPosition = FastConvert.Utf8ByteArrayToInt32(data.GetFirst()); session.CursorPosition = cursorPosition; return(_signatureHelp.ApplyCursorPositionChangeAsync(session, sender, cancellationToken)); }
public void Loading_ShouldHave_DataAsNull_And_StateAsLoading() { var data = AsyncData <string> .Loading(); data.Data.Should().BeNull(); data.State.Should().Be(AsyncDataState.Loading); }
public void Loaded_ShouldHave_DataAsDone_And_StateAsLoaded() { var data = AsyncData <string> .Loaded("done"); data.Data.Should().Be("done"); data.State.Should().Be(AsyncDataState.Loaded); }
//Accept 콜백 메소드 //Begin ReceiveLength 메소드 public void HandleAsyncAccept(IAsyncResult asyncResult) { Socket listenSock = (Socket)asyncResult.AsyncState; Socket clientSock; try { clientSock = listenSock.EndAccept(asyncResult); } catch { clientSock = null; Console.WriteLine("DataReceiver::HandleAsyncAccept.EndAccept 에러"); } if (clientSock != null) { Console.WriteLine(clientSock.RemoteEndPoint.ToString() + " 접속"); ConnectionChecker.AddClient(clientSock); AsyncData asyncData = new AsyncData(clientSock); clientSock.BeginReceive(asyncData.msg, 0, UnityServer.packetLength, SocketFlags.None, asyncReceiveLengthCallBack, (Object)asyncData); } listenSock.BeginAccept(asyncAcceptCallback, (Object)listenSock); }
private void NoAnswerCallback(AsyncData async) { _asyncTaskModule.StopTask(AsyncTasksNames.RestoreRemote); if (async.IsLast()) { AddServerToFailed(_remoteServer); StartNextServer(); return; } var ret = WriterNet.SendToWriter(_remoteServer, new RestoreCommandWithData(_local[0].ServerId, _local.ToList(), _isModelUpdated, _tableName)); if (ret is FailNetResult) { AddServerToFailed(_remoteServer); StartNextServer(); } else { _asyncTaskModule.StartTask(AsyncTasksNames.RestoreRemote); } }
public void CalibrationHandler(AsyncData asyncData) { Console.WriteLine("Calibration handler"); _calibrationAsyncData = asyncData; //this async data doesn't seem to tell anything _isCalibrating = true; }
// This is the method that the underlying, free-threaded // asynchronous behavior will invoke. This will happen on // an arbitrary thread. private void OnAsyncCompletionMethod(object operationState) { AsyncData data = operationState as AsyncData; AsyncOperation asyncOp = data.Operation; AsyncOperationCompletedEventArgs args = new AsyncOperationCompletedEventArgs(data); // In this case, don't allow cancellation, as the method // is about to raise the completed event. lock (this.userStateToLifetime.SyncRoot) { if (userStateToLifetime.Contains(data.UserData) == false) { asyncOp = null; } else { this.userStateToLifetime.Remove(asyncOp.UserSuppliedState); } } // The asyncOp object is responsible for marshaling // the call. if (asyncOp != null) { asyncOp.PostOperationCompleted(this.onCompletedDelegate, args); } // Note that after the call to OperationCompleted, // asyncOp is no longer usable, and any attempt to use it // will cause an exception to be thrown. }
/// <summary> /// Fill dataset asyncronously /// </summary> public void Fill(ref DataTable datatable, AsyncCallback callback) { AsyncData data = new AsyncData(datatable, callback); sqlconnection.Open(); IAsyncResult ar = sqlcommand.BeginExecuteReader(new AsyncCallback(callbackFill), data); }
public async Task ExecuteAsync(AsyncData data, WorkSession session, ICommandResultSender sender, CancellationToken cancellationToken) { var roslynSession = session.Roslyn; var actionId = FastConvert.Utf8ByteArrayToInt32(data.GetFirst()); var action = roslynSession.CurrentCodeActions[actionId]; var operations = await action.GetOperationsAsync(cancellationToken).ConfigureAwait(false); foreach (var operation in operations) { operation.Apply(roslynSession.Workspace, cancellationToken); } // I rollback the changes since I want to send them to client and get them back as ReplaceText // This makes sure any other typing on client merges with these changes properly var changes = await roslynSession.RollbackWorkspaceChangesAsync().ConfigureAwait(false); var writer = sender.StartJsonMessage("changes"); writer.WriteProperty("reason", "fix"); writer.WritePropertyStartArray("changes"); foreach (var change in changes) { writer.WriteChange(change); } writer.WriteEndArray(); await sender.SendJsonMessageAsync(cancellationToken).ConfigureAwait(false); }
public void HandleAsyncReceiveData(IAsyncResult asyncResult) { AsyncData asyncData = (AsyncData)asyncResult.AsyncState; Socket clientSock = asyncData.clientSock; try { asyncData.msgSize = (short)clientSock.EndReceive(asyncResult); } catch { return; } if (asyncData.msgSize >= UnityServer.packetId) { Array.Resize(ref asyncData.msg, asyncData.msgSize); TcpPacket paket = new TcpPacket(asyncData.msg, clientSock); lock (receiveLock) { try { msgs.Enqueue(paket); } catch { Console.WriteLine("DataReceiver::Enqueue 에러"); } } } asyncData = new AsyncData(clientSock); clientSock.BeginReceive(asyncData.msg, 0, UnityServer.packetLength, SocketFlags.None, asyncReceiveLengthCallBack, (Object)asyncData); }
private static void OnSnapshotCommitted(AsyncData asyncData) { try { ResultCode resultCode; if (!asyncData.TryGetResultCode(out resultCode)) { return; } if (resultCode == ResultCode.InvalidSnapshot) { print("Snapshot validation failed: " + GetErrorMessage(asyncData)); } else if (resultCode != ResultCode.Ok && resultCode != ResultCode.Cancelled) { print("Could not commit snapshot: " + GetErrorMessage(asyncData)); } } catch (InteractionApiException ex) { print("EyeTracking operation failed: " + ex.Message); } asyncData.Dispose(); }
private void OnStateChanged(AsyncData data) { using (data) { ResultCode resultCode; if (!data.TryGetResultCode(out resultCode) || resultCode != ResultCode.Ok) { return; } using (var stateBag = data.GetDataAs <StateBag>()) { if (stateBag != null) { if (_isInitialized) { T value; if (GetData(stateBag, out value)) { _currentValue = new EyeXEngineStateValue <T>(value); } } } } } }
private WebResponse Insert(Authenticator authentication, Uri resumableUploadUri, Stream payload, string contentType, string slug, AsyncData data) { Uri resumeUri = InitiateUpload(resumableUploadUri, authentication, contentType, slug, GetStreamLength(payload)); return(UploadStream(HttpMethods.Post, resumeUri, authentication, payload, contentType, data)); }
//Udp 데이터 수신 public void UdpReceiveDataCallback(IAsyncResult asyncResult) { AsyncData asyncData = (AsyncData)asyncResult.AsyncState; try { asyncData.msgSize = (short)udpSock.EndReceiveFrom(asyncResult, ref asyncData.EP); } catch (Exception e) { Debug.Log("연결 끊김 :" + e.Message); } if (asyncData.msgSize > 0) { Array.Resize(ref asyncData.msg, asyncData.msgSize); while (asyncData.msg.Length > 0) { byte[] msgSize = ResizeByteArray(0, NetworkManager.packetLength, ref asyncData.msg); asyncData.msgSize = (short)(BitConverter.ToInt16(msgSize, 0) + NetworkManager.packetSource + NetworkManager.packetId + NetworkManager.udpId); byte[] msg = ResizeByteArray(0, asyncData.msgSize, ref asyncData.msg); DataPacket packet = new DataPacket(msg, asyncData.EP); //lock (receiveLock) //{ msgs.Enqueue(packet); //} } } asyncData = new AsyncData(asyncData.EP); udpSock.BeginReceiveFrom(asyncData.msg, 0, AsyncData.msgMaxSize, SocketFlags.None, ref asyncData.EP, new AsyncCallback(UdpReceiveDataCallback), asyncData); }
//Tcp (서버) 수신 시작 public void StartTcpReceive() { AsyncData asyncData = new AsyncData(tcpSock); //패킷 헤더 중 패킷의 길이 (2) 만큼 데이터를 받는다 tcpSock.BeginReceive(asyncData.msg, 0, NetworkManager.packetLength, SocketFlags.None, new AsyncCallback(TcpReceiveLengthCallback), asyncData); }
public void Initial_ShouldHave_DataAsNull_And_StateAsInitial() { var data = AsyncData <string> .Initial(); data.Data.Should().BeNull(); data.State.Should().Be(AsyncDataState.Initial); }
//异步获取解密后的字节数据 public static void GetABBytes(IAsyncResult result) { AsyncData asyncData = (AsyncData)result.AsyncState; byte[] data = asyncData.decryptAsyn.EndInvoke(result); asyncData.cb?.Invoke(data); }
/// <summary>Handler for async reads from a stream</summary> protected virtual void DataRecv(IAsyncResult ar) { AsyncData data = (AsyncData)ar.AsyncState; lock (m_lock) { try { if (m_outp == null) { return; } data.Read = data.Source.EndRead(ar); if (data.Read != 0 || IsConnected) { m_outp.Write(data.Buffer, 0, data.Read); m_outp.Flush(); data.Source.BeginRead(data.Buffer, 0, data.Buffer.Length, DataRecv, data); return; } } catch (Exception ex) { var type = GetType().DeclaringType; Log.Write(ELogLevel.Error, ex, $"[{(type != null ? type.Name : "")}] Data receive exception"); } RaiseConnectionDropped(); } }
/// <summary> /// 通知异步的操作完成 /// </summary> protected virtual void CallCompleteCallback() { if (AsyncData != null) { AsyncData.NotifyAsyncComplete(); } }
protected virtual void WriteBodyAsync() { var op = Context.Operation; //一个文件失败,则把整个过程看作失败 try { _fs = FileInfo.OpenRead(); _buffer = new byte[AsyncData.HttpContext.Client.Setting.WriteBufferSize]; var ee = new DataProgressEventArgs(_fs.Length, 0L); if (op == null) { OnProgressChanged(ee); } else { op.Post(__ => OnProgressChanged(ee), null); } ReadFileAsync(); } catch (Exception ex) { AsyncData.Exception = ex; AsyncData.NotifyAsyncComplete(); } }
void ReadFileAsync() { _fs.BeginRead(_buffer, 0, _buffer.Length, _ => { try { var count = _fs.EndRead(_); var ee = new DataProgressEventArgs(_fs.Length, _fs.Position); var op = Context.Operation; if (op == null) { OnProgressChanged(ee); } else { op.Post(__ => OnProgressChanged(ee), null); } if (count == 0) { _fs.Close(); WriteFooterAsync(); } else { AsyncData.AsyncStreamWrite(_buffer, 0, count, true, __ => ReadFileAsync()); } } catch (Exception ex) { AsyncData.Exception = ex; AsyncData.NotifyAsyncComplete(); } }, null); }
public Task ExecuteAsync(AsyncData data, WorkSession session, ICommandResultSender sender, CancellationToken cancellationToken) { var first = data.GetFirst(); var firstByte = first.Array[first.Offset]; if (firstByte == (byte)'I') { var infoItemIndex = FastConvert.Utf8ByteArrayToInt32(first.Skip(1)); return(_completion.SendItemInfoAsync(infoItemIndex, session, sender, cancellationToken)); } if (firstByte == (byte)'X') { return(_completion.CancelCompletionAsync(session, sender, cancellationToken)); } if (firstByte == (byte)'F') { return(_completion.ForceCompletionAsync(session, sender, cancellationToken)); } var itemIndex = FastConvert.Utf8ByteArrayToInt32(first); return(_completion.SelectCompletionAsync(itemIndex, session, sender, cancellationToken)); }
public void ErrorMessage_ShouldHave_DataAsNull_And_StateAsError() { var data = AsyncData <string> .ErrorMessage("error"); data.Data.Should().BeNull(); data.Error.Should().Be("error"); data.State.Should().Be(AsyncDataState.Error); }
//Udp (클라이언트) 수신 시작 public void StartUdpReceive() { //매개변수로 받은 리스트의 EndPoint에서 비동기 수신을 대기한다 AsyncData asyncData = new AsyncData(new IPEndPoint(IPAddress.Any, 0)); udpSock.BeginReceiveFrom(asyncData.msg, 0, AsyncData.msgMaxSize, SocketFlags.None, ref asyncData.EP, new AsyncCallback(UdpReceiveDataCallback), asyncData); Debug.Log("UDP 수신시작"); }
private void PingProcess(AsyncData data) { var servers = _collectorNet.GetServersByType(typeof(SingleConnectionToDistributor)); _collectorNet.PingDistributors(servers); servers = _model.GetAllServers2(); _collectorNet.PingWriter(servers, _model.ServerAvailable); }
/// <summary> /// Callback method useful during application development to find malformed or /// incorrectly set up snapshots and interactors. /// </summary> /// <param name="asyncData">Data packet that contains value code and error messages.</param> private static void OnSnapshotCommitted(AsyncData asyncData) { using (asyncData) { ResultCode resultCode; Debug.Assert(asyncData.TryGetResultCode(out resultCode), "Failed to read value code after committing snapshot."); Debug.Assert(resultCode != ResultCode.InvalidSnapshot, "Snapshot validation failed: " + GetErrorMessage(asyncData)); } }
/// <summary> /// constructor. takes the async data blob /// </summary> /// <param name="data">async data to constructor</param> internal AsyncOperationCompletedEventArgs(AsyncData data) : base(data.Exception, false, data.UserData) { feedObject = data.Feed; stream = data.DataStream; IAsyncEntryData entryData = data as IAsyncEntryData; if (entryData != null) { entryObject = entryData.Entry; } }
internal bool SendProgressData(AsyncData data, AsyncOperationProgressEventArgs args) { // In this case, don't allow cancellation, as the method // is about to raise the completed event. bool ret = !CheckIfOperationIsCancelled(data.UserData); if (ret == true) { data.Operation.Post(data.Delegate, args); } return ret; }
private static string GetErrorMessage(AsyncData asyncData) { string errorMessage; if (asyncData.TryGetPropertyValue<string>(Literals.ErrorMessage, out errorMessage)) { return errorMessage; } else { return "Unspecified error."; } }
private WebResponse Update(Authenticator authentication, AbstractEntry payload, AsyncData data) { WebResponse r = null; Uri initialUri = ResumableUploader.GetResumableEditUri(payload.Links); if (initialUri == null) throw new ArgumentException("payload did not contain a resumabled edit media Uri"); Uri resumeUri = InitiateUpload(initialUri, authentication, payload, HttpMethods.Put); // get the stream using (Stream s = payload.MediaSource.GetDataStream()) { r = UploadStream(HttpMethods.Put, resumeUri, authentication, s, payload.MediaSource.ContentType, data); } return r; }
private HttpWebResponse UploadStreamPart(int partIndex, string httpMethod, Uri sessionUri, Authenticator authentication, Stream payload, string mediaType, AsyncData data) { HttpWebRequest request = authentication.CreateHttpWebRequest(httpMethod, sessionUri); request.AllowWriteStreamBuffering = false; request.Timeout = 600000; // write the data request.ContentType = mediaType; CopyData(payload, request, partIndex, data, sessionUri); HttpWebResponse response = request.GetResponse() as HttpWebResponse; return response; }
private WebResponse Resume(Authenticator authentication, Uri resumeUri, String httpmethod, Stream payload, string contentType, AsyncData data) { return UploadStream(httpmethod, resumeUri, authentication, payload, contentType, data); }
/// <summary> /// handles the response stream /// copies it into the memory stream, or parses it into a feed. /// </summary> /// <param name="data"></param> /// <param name="responseStream"></param> /// <param name="contentLength"></param> /// <returns></returns> protected virtual void HandleResponseStream(AsyncData data, Stream responseStream, long contentLength) { data.DataStream = CopyResponseToMemory(data, responseStream, contentLength); }
private MemoryStream CopyResponseToMemory(AsyncData data, Stream responseStream, long contentLength) { MemoryStream memStream = null; if (responseStream != null) { // read the stream into memory. That's the only way to satisfy the "main work // on the other thread requirement memStream = new MemoryStream(); const int size = 4096; var bytes = new byte[size]; int numBytes; double current = 0; long bytesWritten = 0; while ((numBytes = responseStream.Read(bytes, 0, size)) > 0) { memStream.Write(bytes, 0, numBytes); if (data == null || data.Delegate == null) { continue; } bytesWritten += numBytes; if (contentLength > size) { current = bytesWritten * 100d / contentLength; } // see if we are still in the list... // Multiple threads will access the task dictionary, // so it must be locked to serialize access. if (CheckIfOperationIsCancelled(data.UserData) == true) { throw new ArgumentException("Operation was cancelled"); } var args = new AsyncOperationProgressEventArgs(contentLength, bytesWritten, (int)current, data.UriToUse, data.HttpVerb, data.UserData); data.Operation.Post(data.Delegate, args); } memStream.Seek(0, SeekOrigin.Begin); } return memStream; }
private void OnSnapshotCommitted(AsyncData asyncData) { ResultCode resultCode; if (!asyncData.TryGetResultCode(out resultCode)) return; if (resultCode == ResultCode.InvalidSnapshot) { Debug.LogWarning("Snapshot validation failed: " + GetErrorMessage(asyncData)); } else if (resultCode != ResultCode.Ok) { Debug.LogWarning("Could not commit snapshot: " + GetErrorMessage(asyncData)); } }
internal AsyncOperationCompletedEventArgs(AsyncData data, bool cancelled) : base(data.Exception, cancelled, data.UserData) { }
private WebResponse Update(Authenticator authentication, Uri resumableUploadUri, Stream payload, string contentType, AsyncData data) { Uri resumeUri = InitiateUpload(resumableUploadUri, authentication, contentType, null, GetStreamLength(payload), HttpMethods.Put); return UploadStream(HttpMethods.Put, resumeUri, authentication, payload, contentType, data); }
/// <summary> /// this method cancels the corresponding async operation. /// It sends still a completed event, but that event will then /// have the cancel property set to true /// </summary> /// <param name="userData">your identifier for the operation to be cancelled</param> public void CancelAsync(object userData) { lock (this.userStateToLifetime.SyncRoot) { object obj = this.userStateToLifetime[userData]; if (obj != null) { this.userStateToLifetime.Remove(userData); AsyncOperation asyncOp = obj as AsyncOperation; // The asyncOp object is responsible for // marshaling the call to the proper // thread or context. AsyncData data = new AsyncData(null, userData, this.onProgressReportDelegate); AsyncOperationCompletedEventArgs args = new AsyncOperationCompletedEventArgs(data, true); asyncOp.PostOperationCompleted(this.onCompletedDelegate, args); } } }
/// <summary> /// Note the URI passed in here, is the session URI obtained by InitiateUpload /// </summary> /// <param name="targetUri"></param> /// <param name="authentication"></param> /// <param name="payload"></param> /// <param name="mediaType"></param> public WebResponse UploadStream(string httpMethod, Uri sessionUri, Authenticator authentication, Stream payload, string mediaType, AsyncData data) { HttpWebResponse returnResponse = null; // upload one part at a time int index = 0; lastChunks.Add(sessionUri, 0); bool isDone = false; // if the stream passed as parameter is NOT at the beginning, we assume // that we are resuming try { // calculate a new index, we will resume in chunk sizes if (payload.Position != 0) { index = (int)((double)payload.Position / (this.chunkSize * ResumableUploader.MB)); } } catch (System.NotSupportedException) { index = 0; } do { HttpWebResponse response; try { response = UploadStreamPart(index, httpMethod, sessionUri, authentication, payload, mediaType, data); if (data != null && CheckIfOperationIsCancelled(data.UserData)) { break; } index++; { int status = (int)response.StatusCode; switch (status) { case 308: isDone = false; break; case 200: case 201: isDone = true; returnResponse = response; break; default: throw new ApplicationException("Unexpected return code during resumable upload"); } } } finally { response = null; } } while (!isDone); lastChunks.Remove(sessionUri); return returnResponse; }
private WebResponse Insert(Authenticator authentication, AbstractEntry payload, AsyncData data) { Uri initialUri = ResumableUploader.GetResumableCreateUri(payload.Links); if (initialUri == null) throw new ArgumentException("payload did not contain a resumabled create media Uri"); Uri resumeUri = InitiateUpload(initialUri, authentication, payload); return UploadStream(HttpMethods.Post, resumeUri, authentication, payload.MediaSource.Data, payload.MediaSource.ContentType, data); }
////////////////////////////////////////////////////////////////////// /// <summary>takes our copy of the stream, and puts it into the request stream /// returns FALSE when we are done by reaching the end of the input stream</summary> ////////////////////////////////////////////////////////////////////// protected bool CopyData(Stream input, HttpWebRequest request, int partIndex, AsyncData data, Uri requestId) { long chunkCounter = 0; long chunkStart = lastChunks[requestId]; long chunkSizeMb = this.chunkSize * ResumableUploader.MB; long dataLength; dataLength = GetStreamLength(input); // calculate the range // move the source stream to the correct position input.Seek(chunkStart, SeekOrigin.Begin); // to reduce memory consumption, we read in 256K chunks const int size = 262144; byte[] bytes = new byte[size]; int numBytes; // first calculate the contentlength. We can not modify // headers AFTER we started writing to the stream // Note: we want to read in chunksize*MB, but it might be less // if we have smaller files or are at the last chunk while ((numBytes = input.Read(bytes, 0, size)) > 0) { chunkCounter += numBytes; if (chunkCounter >= chunkSizeMb) { break; } } request.ContentLength = chunkCounter; long chunkEnd = chunkStart + chunkCounter; // modify the content-range header string contentRange = String.Format("bytes {0}-{1}/{2}", chunkStart, chunkEnd - 1, dataLength > 0 ? dataLength.ToString() : "*"); request.Headers.Add(HttpRequestHeader.ContentRange, contentRange); lastChunks[requestId] = chunkEnd; // save the last start index, need to add 503 error handling to this // stream it into the real request stream using (Stream req = request.GetRequestStream()) { // move the source stream to the correct position input.Seek(chunkStart, SeekOrigin.Begin); chunkCounter = 0; // to reduce memory consumption, we read in 256K chunks while ((numBytes = input.Read(bytes, 0, size)) > 0) { req.Write(bytes, 0, numBytes); chunkCounter += numBytes; // while we are writing along, send notifications out if (data != null) { if (CheckIfOperationIsCancelled(data.UserData)) { break; } else if (data.Delegate != null && data.DataHandler != null) { AsyncOperationProgressEventArgs args; long position = chunkStart + chunkCounter - 1; int percentage = (int)((double)position / dataLength * 100); args = new AsyncOperationProgressEventArgs(dataLength, position, percentage, request.RequestUri, request.Method, data.UserData); data.DataHandler.SendProgressData(data, args); } } if (chunkCounter >= request.ContentLength) { break; } } } return chunkCounter < chunkSizeMb; }
private WebResponse Insert(Authenticator authentication, Uri resumableUploadUri, Stream payload, string contentType, string slug, AsyncData data) { Uri resumeUri = InitiateUpload(resumableUploadUri, authentication, contentType, slug, GetStreamLength(payload)); return UploadStream(HttpMethods.Post, resumeUri, authentication, payload, contentType, data); }