private static IEnumerator<Int32> PipeServerAsyncEnumerator(AsyncEnumerator ae) { // Each server object performs asynchronous operation on this pipe using (var pipe = new NamedPipeServerStream( "Echo", PipeDirection.InOut, -1, PipeTransmissionMode.Message, PipeOptions.Asynchronous | PipeOptions.WriteThrough)) { // Asynchronously accept a client connection pipe.BeginWaitForConnection(ae.End(), null); yield return 1; // A client connected, let's accept another client var aeNewClient = new AsyncEnumerator(); aeNewClient.BeginExecute(PipeServerAsyncEnumerator(aeNewClient), aeNewClient.EndExecute); // Accept the client connection pipe.EndWaitForConnection(ae.DequeueAsyncResult()); // Asynchronously read a request from the client Byte[] data = new Byte[1000]; pipe.BeginRead(data, 0, data.Length, ae.End(), null); yield return 1; // The client sent us a request, process it Int32 bytesRead = pipe.EndRead(ae.DequeueAsyncResult()); // Just change to upper case data = Encoding.UTF8.GetBytes( Encoding.UTF8.GetString(data, 0, bytesRead).ToUpper().ToCharArray()); // Asynchronously send the response back to the client pipe.BeginWrite(data, 0, data.Length, ae.End(), null); yield return 1; // The response was sent to the client, close our side of the connection pipe.EndWrite(ae.DequeueAsyncResult()); } // Close happens in a finally block now! }
private static IEnumerator <int> GenerateTransferTask( AsyncEnumerator ae, HttpContext context, string url) { WebRequest request = WebRequest.Create(url); request.BeginGetResponse(ae.End(), null); yield return(1); using (WebResponse response = request.EndGetResponse(ae.DequeueAsyncResult())) { Stream streamIn = response.GetResponseStream(); Stream streamOut = context.Response.OutputStream; byte[] buffer = new byte[1024]; while (true) { streamIn.BeginRead(buffer, 0, buffer.Length, ae.End(), null); yield return(1); int lengthRead = streamIn.EndRead(ae.DequeueAsyncResult()); if (lengthRead <= 0) { break; } streamOut.BeginWrite(buffer, 0, lengthRead, ae.End(), null); yield return(1); streamOut.EndWrite(ae.DequeueAsyncResult()); } } }
private static IEnumerator <Int32> CopyStream(AsyncEnumerator <Int64> ae, Stream source, Stream destination, Int32 bufferSize, Action <Int64> reportProgress) { Byte[] buffer = new Byte[bufferSize]; Int64 totalBytesRead = 0; while (true) { ae.SetOperationTag("Reading from source stream"); // Read whichever is smaller (number of bytes left to read OR the buffer size) source.BeginRead(buffer, 0, buffer.Length, ae.End(), null); yield return(1); Int32 bytesReadThisTime = source.EndRead(ae.DequeueAsyncResult()); totalBytesRead += bytesReadThisTime; ae.SetOperationTag("Writing to destination stream"); destination.BeginWrite(buffer, 0, bytesReadThisTime, ae.End(), null); yield return(1); destination.EndWrite(ae.DequeueAsyncResult()); if (reportProgress != null) { reportProgress(totalBytesRead); } if (bytesReadThisTime < buffer.Length) { break; } } ae.Result = totalBytesRead; }
private static IEnumerator<Int32> ProcessAllAndEachOps(AsyncEnumerator ae, String[] urls) { Int32 numOps = urls.Length; // Issue all the asynchronous operation(s) so they run concurrently for (Int32 n = 0; n < numOps; n++) { WebRequest wr = WebRequest.Create(urls[n]); wr.BeginGetResponse(ae.End(), wr); } // Have AsyncEnumerator wait until ALL operations complete yield return numOps; Console.WriteLine("All the operations completed:"); for (Int32 n = 0; n < numOps; n++) { ProcessCompletedWebRequest(ae.DequeueAsyncResult()); } Console.WriteLine(); // *** Blank line between demos *** System.Diagnostics.Debugger.Break(); // Issue all the asynchronous operation(s) so they run concurrently for (Int32 n = 0; n < numOps; n++) { WebRequest wr = WebRequest.Create(urls[n]); wr.BeginGetResponse(ae.End(), wr); } for (Int32 n = 0; n < numOps; n++) { // Have AsyncEnumerator wait until EACH operation completes yield return 1; Console.WriteLine("An operation completed:"); ProcessCompletedWebRequest(ae.DequeueAsyncResult()); } }
private static IEnumerator <Int32> PipeClientAsyncEnumerator(AsyncEnumerator ae, String serverName, String message) { // Each client object performs asynchronous operations on this pipe using (var pipe = new NamedPipeClientStream(serverName, "Echo", PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.WriteThrough)) { pipe.Connect(); // Must Connect before setting ReadMode pipe.ReadMode = PipeTransmissionMode.Message; // Asynchronously send data to the server Byte[] output = Encoding.UTF8.GetBytes(message); pipe.BeginWrite(output, 0, output.Length, ae.End(), null); yield return(1); // The data was sent to the server pipe.EndWrite(ae.DequeueAsyncResult()); // Asynchronously read the server's response Byte[] data = new Byte[1000]; pipe.BeginRead(data, 0, data.Length, ae.End(), data); yield return(1); // The server responded, display the response and close out connection Int32 bytesRead = pipe.EndRead(ae.DequeueAsyncResult()); Console.WriteLine("Server response: " + Encoding.UTF8.GetString(data, 0, bytesRead)); } // Close(); }
public IEnumerator<int> Login(SerializedObject request, string loginID, string password, string version, int appType, AsyncEnumerator ae) { long session = request.Session; string connectionString = SettingManager.Default.ConnectionString; IsFailedCountExceed(loginID, password, connectionString); LoginParameter loginParameter = new LoginParameter(); loginParameter.CompanyName = string.Empty; if (loginID == String.Empty) { AuditHelper.AddIllegalLogin(AppType.TradingConsole, loginID, password, this.GetLocalIP()); Application.Default.TradingConsoleServer.SaveLoginFail(loginID, password, GetLocalIP()); SendErrorResult(request); yield break; } string message = string.Empty; Application.Default.ParticipantService.BeginLogin(loginID, password, ae.End(), null); yield return 1; loginParameter.UserID = Application.Default.ParticipantService.EndLogin(ae.DequeueAsyncResult()); if (loginParameter.UserID == Guid.Empty) { _Logger.ErrorFormat("{0} is not a valid user", loginID); } else { Guid programID = new Guid(SettingManager.Default.GetLoginSetting("TradingConsole")); Guid permissionID = new Guid(SettingManager.Default.GetLoginSetting("Run")); Application.Default.SecurityService.BeginCheckPermission(loginParameter.UserID, programID, permissionID, "", "", loginParameter.UserID, ae.End(), null); yield return 1; bool isAuthrized = Application.Default.SecurityService.EndCheckPermission(ae.DequeueAsyncResult(), out message); if (!isAuthrized) { _Logger.ErrorFormat("{0} doesn't have the right to login trader", loginID); loginParameter.UserID = Guid.Empty; } else { Token token = new Token(Guid.Empty, UserType.Customer, (AppType)appType); token.UserID = loginParameter.UserID; token.SessionID = session.ToString(); SessionManager.Default.AddToken(session, token); Application.Default.StateServer.BeginLogin(token, ae.End(), null); yield return 1; bool isStateServerLogined = Application.Default.StateServer.EndLogin(ae.DequeueAsyncResult()); SetLoginParameter(loginParameter, session, password, version, appType, isStateServerLogined, token); } } if (loginParameter.UserID == Guid.Empty) { AuditHelper.AddIllegalLogin(AppType.TradingConsole, loginID, password, this.GetLocalIP()); Application.Default.TradingConsoleServer.SaveLoginFail(loginID, password, GetLocalIP()); SendErrorResult(request); } else { SetResult(request, loginParameter, session, loginID, password, version, appType, connectionString); } }
private static IEnumerator <Int32> PipeServerAsyncEnumerator(AsyncEnumerator ae) { // Each server object performs asynchronous operations on this pipe using (var pipe = new NamedPipeServerStream( "Echo", PipeDirection.InOut, -1, PipeTransmissionMode.Message, PipeOptions.Asynchronous | PipeOptions.WriteThrough)) { // Asynchronously accept a client connection pipe.BeginWaitForConnection(ae.End(), null); yield return(1); // A client connected, let's accept another client var aeNewClient = new AsyncEnumerator(); aeNewClient.BeginExecute(PipeServerAsyncEnumerator(aeNewClient), aeNewClient.EndExecute); // Accept the client connection pipe.EndWaitForConnection(ae.DequeueAsyncResult()); // Asynchronously read a request from the client Byte[] data = new Byte[1000]; pipe.BeginRead(data, 0, data.Length, ae.End(), null); yield return(1); // The client sent us a request, process it. Int32 bytesRead = pipe.EndRead(ae.DequeueAsyncResult()); // Get the timestamp of this client's request DateTime now = DateTime.Now; // We want to save the timestamp of the most-recent client request. Since multiple // clients are running concurrently, this has to be done in a thread-safe way s_gate.BeginRegion(SyncGateMode.Exclusive, ae.End()); // Request exclusive access yield return(1); // The iterator resumes when exclusive access is granted if (s_lastClientRequestTimestamp < now) { s_lastClientRequestTimestamp = now; } s_gate.EndRegion(ae.DequeueAsyncResult()); // Relinquish exclusive access // My sample server just changes all the characters to uppercase // But, you can replace this code with any compute-bound operation data = Encoding.UTF8.GetBytes( Encoding.UTF8.GetString(data, 0, bytesRead).ToUpper().ToCharArray()); // Asynchronously send the response back to the client pipe.BeginWrite(data, 0, data.Length, ae.End(), null); yield return(1); // The response was sent to the client, close our side of the connection pipe.EndWrite(ae.DequeueAsyncResult()); } // Close the pipe }
private static IEnumerator <int> GetAsyncEnumerator( AsyncEnumerator ae, string urlIn, string urlOut, Action <double> onProgress, Action <int> onComplete) { onProgress(0); var requestIn = WebRequest.Create(urlIn); requestIn.BeginGetResponse(ae.End(), null); yield return(1); using (var responseIn = requestIn.EndGetResponse(ae.DequeueAsyncResult())) { var streamIn = responseIn.GetResponseStream(); var requestOut = WebRequest.Create(urlOut); requestOut.Method = "POST"; var totalLength = (int)responseIn.ContentLength; requestOut.BeginGetRequestStream(ae.End(), null); yield return(1); using (var streamOut = requestOut.EndGetRequestStream(ae.DequeueAsyncResult())) { var totalRead = 0; var buffer = new byte[10240]; while (totalRead < totalLength) { streamIn.BeginRead(buffer, 0, buffer.Length, ae.End(), null); yield return(1); var lengthRead = streamIn.EndRead(ae.DequeueAsyncResult()); streamOut.BeginWrite(buffer, 0, lengthRead, ae.End(), null); yield return(1); streamOut.EndWrite(ae.DequeueAsyncResult()); totalRead += lengthRead; onProgress(100.0 * totalRead / totalLength); } } onComplete(totalLength); } }
private IEnumerator<Int32> DownloadString(AsyncEnumerator ae, String uri) { var request = WebRequest.Create(uri); request.BeginGetResponse(ae.End(), null); yield return 1; var response = (WebResponse) request.EndGetResponse(ae.DequeueAsyncResult()); Byte[] buffer = new Byte[response.ContentLength]; using (var stream = response.GetResponseStream()) { stream.BeginRead(buffer, 0, buffer.Length, ae.End(), null); yield return 1; stream.EndRead(ae.DequeueAsyncResult()); } m_textBox.Text = Encoding.UTF8.GetString(buffer, 0, buffer.Length); }
private static IEnumerator<int> GetAsyncEnumerator( AsyncEnumerator ae, string urlIn, string urlOut, Action<double> onProgress, Action<int> onComplete) { onProgress(0); var requestIn = WebRequest.Create(urlIn); requestIn.BeginGetResponse(ae.End(), null); yield return 1; using (var responseIn = requestIn.EndGetResponse(ae.DequeueAsyncResult())) { var streamIn = responseIn.GetResponseStream(); var requestOut = WebRequest.Create(urlOut); requestOut.Method = "POST"; var totalLength = (int)responseIn.ContentLength; requestOut.BeginGetRequestStream(ae.End(), null); yield return 1; using (var streamOut = requestOut.EndGetRequestStream(ae.DequeueAsyncResult())) { var totalRead = 0; var buffer = new byte[10240]; while (totalRead < totalLength) { streamIn.BeginRead(buffer, 0, buffer.Length, ae.End(), null); yield return 1; var lengthRead = streamIn.EndRead(ae.DequeueAsyncResult()); streamOut.BeginWrite(buffer, 0, lengthRead, ae.End(), null); yield return 1; streamOut.EndWrite(ae.DequeueAsyncResult()); totalRead += lengthRead; onProgress(100.0 * totalRead / totalLength); } } onComplete(totalLength); } }
public static IEnumerator<int> GetInitData(SerializedObject request, DataSet initData, AsyncEnumerator ae) { XElement result = null; long session = request.Session; Token token = SessionManager.Default.GetToken(session); if (initData == null) { Application.Default.StateServer.BeginGetInitData(token, null, ae.End(), null); yield return 1; int sequence; initData = Application.Default.StateServer.EndGetInitData(ae.DequeueAsyncResult(), out sequence); } try { var data = Init(session, initData); int commandSequence = data.Item2; DataSet ds = data.Item1; var dict = new Dictionary<string, string>() { {"commandSequence",commandSequence.ToString()}, {"data",ds.ToXml()} }; result = XmlResultHelper.NewResult(dict); request.Content = result; SendCenter.Default.Send(request); } catch (Exception ex) { request.Content = XmlResultHelper.NewErrorResult(ex.ToString()); SendCenter.Default.Send(request); } }
private static IEnumerator <int> CopyStream(AsyncEnumerator ae, Stream readStream, Stream writeStream) { byte[][] buffer = new byte[][] { new byte[8192], new byte[8192] }; int bytesRead = 0; int currentBuffer = 0; ae.AddAsync <IAsyncResult>(readStream.BeginRead(buffer[currentBuffer], 0, buffer[0].Length, ae.GetAsyncCallback(), null)); yield return(1); for (bytesRead = readStream.EndRead(ae.CompletedAsyncResults[0]); bytesRead > 0; bytesRead = readStream.EndRead(ae.CompletedAsyncResults[1])) { ae.AddAsync <IAsyncResult>(writeStream.BeginWrite(buffer[currentBuffer % 2], 0, bytesRead, ae.GetAsyncCallback(), null)); currentBuffer++; ae.AddAsync <IAsyncResult>(readStream.BeginRead(buffer[currentBuffer % 2], 0, buffer[currentBuffer % 2].Length, ae.GetAsyncCallback(), null)); yield return(2); writeStream.EndWrite(ae.CompletedAsyncResults[0]); } ae.End(); yield break; }
static IEnumerator <int> ListenerFiber(AsyncEnumerator ae) { var listeningServer = new TcpListener(IPAddress.Loopback, 9998); listeningServer.Start(); while (!ae.IsCanceled()) { listeningServer.BeginAcceptTcpClient(ae.End(0, listeningServer.EndAcceptTcpClient), null); yield return(1); if (ae.IsCanceled()) { yield break; } var clientSocket = listeningServer.EndAcceptTcpClient(ae.DequeueAsyncResult()); var clientAe = new AsyncEnumerator() { SyncContext = null }; clientAe.BeginExecute( ClientFiber(clientAe, clientSocket), ar => { try { clientAe.EndExecute(ar); } catch { } }, null); } }
private static IEnumerator <Int32> FetchStockQuotesAsyncEnumerator(AsyncEnumerator ae, WebService svc) { svc.BeginFetchStockQuotes(ae.End(), null); yield return(1); IStockQuote qt = svc.EndFetchStockQuotes(ae.DequeueAsyncResult()); }
private IEnumerator <int> ProcessUpdateLookups(AsyncEnumerator asyncEnumerator, QuotePage[] pages) { QuotePage page; for (int i = 0; i < pages.Length; i++) { page = pages[i]; LookupResolver.BeginNormalizeTopicOmitChecks(page.Topic, page.Culture, asyncEnumerator.End(AsyncEnumeratorDiscardGroup, LookupResolver.EndNormalizeTopic), page); } IAsyncResult result; bool updateQuotes = false; for (int i = 0; i < pages.Length; i++) { yield return(1); if (asyncEnumerator.IsCanceled()) { yield break; } result = asyncEnumerator.DequeueAsyncResult(); page = result.AsyncState as QuotePage; try { page.Topic = LookupResolver.EndNormalizeTopic(result); page.Uri = LookupResolver.GetUri(page.Topic, page.Culture); } catch { OnTopicNotFound(new TopicNotFoundEventArgs(page.Topic, page.Culture)); yield break; } lock (_lookupsInProgress) { if (!_lookupsInProgress.Contains(page.Uri)) { _lookupsInProgress.Add(page.Uri); updateQuotes = true; } } if (updateQuotes) { QuoteCollector.UpdateQuotesAsync(page); } } lock (_asyncEnumerators) { _asyncEnumerators.Remove(asyncEnumerator); } }
private IEnumerator <Int32> UploadBlock(AsyncEnumerator ae, MemoryMappedFile mmf, CloudBlockBlob blob, Int32 blockNumber, Int64 length) { using (var stream = mmf.CreateViewStream(blockNumber * m_blockSize, length, MemoryMappedFileAccess.Read)) { blob.BeginPutBlock(blockNumber.ToBase64(), stream, null, ae.End(), null); yield return(1); blob.EndPutBlock(ae.DequeueAsyncResult()); } }
private static IEnumerator<Int32> CopyStream(AsyncEnumerator<Int64> ae, Stream source, Stream destination, Int32 bufferSize, Action<Int64> reportProgress) { Byte[] buffer = new Byte[bufferSize]; Int64 totalBytesRead = 0; while (true) { ae.SetOperationTag("Reading from source stream"); // Read whichever is smaller (number of bytes left to read OR the buffer size) source.BeginRead(buffer, 0, buffer.Length, ae.End(), null); yield return 1; Int32 bytesReadThisTime = source.EndRead(ae.DequeueAsyncResult()); totalBytesRead += bytesReadThisTime; ae.SetOperationTag("Writing to destination stream"); destination.BeginWrite(buffer, 0, bytesReadThisTime, ae.End(), null); yield return 1; destination.EndWrite(ae.DequeueAsyncResult()); if (reportProgress != null) reportProgress(totalBytesRead); if (bytesReadThisTime < buffer.Length) break; } ae.Result = totalBytesRead; }
private IEnumerator <int> ProcessLookup(AsyncEnumerator asyncEnumerator, string topic, CultureInfo culture) { LookupResolver.BeginNormalizeTopicOmitChecks(topic, culture, asyncEnumerator.End(AsyncEnumeratorDiscardGroup, LookupResolver.EndNormalizeTopic), null); yield return(1); if (asyncEnumerator.IsCanceled()) { yield break; } try { topic = LookupResolver.EndNormalizeTopic(asyncEnumerator.DequeueAsyncResult()); } catch { OnTopicNotFound(new TopicNotFoundEventArgs(topic, culture)); yield break; } Uri uri = LookupResolver.GetUri(topic, culture); bool collectQuotes = false; lock (_playlist) { if (_playlist.Contains(uri)) { OnTopicAlreadyExists(new TopicAlreadyExistsEventArgs(topic, culture)); yield break; } } lock (_lookupsInProgress) { if (!_lookupsInProgress.Contains(uri)) { _lookupsInProgress.Add(uri); collectQuotes = true; } } if (collectQuotes) { QuoteCollector.CollectQuotesAsync(topic, culture, uri); } lock (_asyncEnumerators) { _asyncEnumerators.Remove(asyncEnumerator); } }
private IEnumerator <int> GetPostEnumerator( Uri uri, AsyncEnumerator ae, Action <JsonRpcResponse, Exception> resultCallback) { var webReq = (HttpWebRequest)WebRequest.Create(uri); webReq.Method = "POST"; webReq.ContentType = "text/json"; webReq.BeginGetRequestStream(ae.End(), null); yield return(1); var reqStream = webReq.EndGetRequestStream(ae.DequeueAsyncResult()); using (var sw = new StreamWriter(reqStream, Encoding.UTF8)) { var json = JsonConvert.SerializeObject(this, Formatting.None); sw.Write(json); sw.Flush(); } webReq.BeginGetResponse(ae.End(), null); yield return(1); try { using (var webRep = webReq.EndGetResponse(ae.DequeueAsyncResult())) using (var repStream = webRep.GetResponseStream()) { var jsonRep = JsonRpcResponse.Deserialize(repStream); resultCallback(jsonRep, null); } } catch (Exception ex) { resultCallback(null, ex); yield break; } }
private IEnumerator <int> ProcessWebResponse(AsyncEnumerator ae, HttpWebResponse webResponse) { PerformanceCounterManager.AddEwsRequestResult(this.IsOkToProcess(webResponse)); this.HttpContext.Response.ContentType = webResponse.ContentType; using (Stream responseInStream = webResponse.GetResponseStream()) { AsyncResult asyncResult = ae.AddAsyncEnumerator((AsyncEnumerator ae1) => ProxyToEwsEventHandler.CopyStream(ae1, responseInStream, this.HttpContext.Response.OutputStream)); yield return(1); asyncResult.End(); } ae.End(); yield break; }
public static IEnumerator<int> GetInitData(SerializedInfo request,AsyncEnumerator ae) { Session session = request.ClientInfo.Session; Token token = SessionManager.Default.GetToken(session); Application.Default.StateServer.BeginGetInitData(token, null, ae.End(), null); yield return 1; try { int sequence; DataSet initData = Application.Default.StateServer.EndGetInitData(ae.DequeueAsyncResult(), out sequence); InitAndSendInitDataInPointer(request,initData); } catch (Exception ex) { SendErrorResult(request, ex); } }
public IEnumerator<int> AsyncGetInitData(Token token,AsyncEnumerator ae) { Token currentToken = new Token(token.UserID, token.UserType, AppType.TradingConsole); Application.Default.StateServer.BeginGetInitData(currentToken, null, ae.End(), null); yield return 1; try { int commandSequence; DataSet initData = Application.Default.StateServer.EndGetInitData(ae.DequeueAsyncResult(), out commandSequence); OnLoadInitDataCompleted(initData); } catch (Exception ex) { _Logger.Error("async getInitData", ex); OnLoadInitDataCompleted(null); yield break; } }
public static IEnumerator <int> GetInitData(SerializedInfo request, AsyncEnumerator ae) { Session session = request.ClientInfo.Session; Token token = SessionManager.Default.GetToken(session); Application.Default.StateServer.BeginGetInitData(token, null, ae.End(), null); yield return(1); try { int sequence; DataSet initData = Application.Default.StateServer.EndGetInitData(ae.DequeueAsyncResult(), out sequence); InitAndSendInitDataInPointer(request, initData); } catch (Exception ex) { SendErrorResult(request, ex); } }
public IEnumerator <int> AsyncGetInitData(Token token, AsyncEnumerator ae) { Token currentToken = new Token(token.UserID, token.UserType, AppType.TradingConsole); Application.Default.StateServer.BeginGetInitData(currentToken, null, ae.End(), null); yield return(1); try { int commandSequence; DataSet initData = Application.Default.StateServer.EndGetInitData(ae.DequeueAsyncResult(), out commandSequence); OnLoadInitDataCompleted(initData); } catch (Exception ex) { _Logger.Error("async getInitData", ex); OnLoadInitDataCompleted(null); yield break; } }
private IEnumerator <Int32> ExecuteWithAsyncEnumerator(AsyncEnumerator ae) { for (Int32 n = 0; n < c_iterations; n++) { ((WebService)m_webService).BeginGetStockQuotes(ae.End(), null); } // NOTE: AsyncEnumerator captures the calling thread's SynchronizationContext. // Set the Wintellect.Threading.AsyncProgModel.SynchronizationContext type to // null so that the callback continues on a ThreadPool thread. ae.SyncContext = null; yield return(c_iterations); for (Int32 n = 0; n < c_iterations; n++) { ((WebService)m_webService).EndGetStockQuotes(ae.DequeueAsyncResult()); } // AsyncEnumerator captures the synchronization context. SetStatus("AsyncEnumerator completed.", StatusState.Ready); }
private IEnumerator <Int32> ExecuteWithAsyncEnumerator(AsyncEnumerator ae) { for (Int32 n = 0; n < c_iterations; n++) { Cargo cargo = CargoFactory.CreateNew("Glyfada" + n, "Perachora" + n); App.Database.BeginSave <Cargo>(cargo, ae.End(), null); } // NOTE: AsyncEnumerator captures the calling thread's SynchronizationContext. // Set the Wintellect.Threading.AsyncProgModel.SynchronizationContext type to // null so that the callback continues on a ThreadPool thread. ae.SyncContext = null; yield return(c_iterations); for (Int32 n = 0; n < c_iterations; n++) { App.Database.EndSave(ae.DequeueAsyncResult()); } // AsyncEnumerator captures the synchronization context. SetStatus("AsyncEnumerator completed.", StatusState.Ready); }
public static IEnumerator<int> ReadBytes( byte[] buffer, Stream stream, AsyncEnumerator ae, string type, bool expectedToHaveNoData) { var totalBytesRead = 0; while (totalBytesRead < buffer.Length) { stream.BeginRead(buffer, totalBytesRead, buffer.Length - totalBytesRead, ae.End(), null); yield return 1; int bytesRead = stream.EndRead(ae.DequeueAsyncResult()); if(bytesRead == 0) { if (expectedToHaveNoData) yield break; throw new InvalidOperationException("Could not read value for " + type); } totalBytesRead += bytesRead; } }
private IEnumerator <int> SendInternal(AsyncEnumerator ae) { try { using (var client = new TcpClient()) { try { client.BeginConnect(Destination.Host, Destination.Port, ae.End(), null); } catch (Exception exception) { logger.WarnFormat("Failed to connect to {0} because {1}", Destination, exception); Failure(exception); yield break; } yield return(1); try { client.EndConnect(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.WarnFormat("Failed to connect to {0} because {1}", Destination, exception); Failure(exception); yield break; } logger.DebugFormat("Successfully connected to {0}", Destination); using (var stream = client.GetStream()) { var buffer = Messages.Serialize(); var bufferLenInBytes = BitConverter.GetBytes(buffer.Length); logger.DebugFormat("Writing length of {0} bytes to {1}", buffer.Length, Destination); try { stream.BeginWrite(bufferLenInBytes, 0, bufferLenInBytes.Length, ae.End(), null); } catch (Exception exception) { logger.WarnFormat("Could not write to {0} because {1}", Destination, exception); Failure(exception); yield break; } yield return(1); try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.WarnFormat("Could not write to {0} because {1}", Destination, exception); Failure(exception); yield break; } logger.DebugFormat("Writing {0} bytes to {1}", buffer.Length, Destination); try { stream.BeginWrite(buffer, 0, buffer.Length, ae.End(), null); } catch (Exception exception) { logger.WarnFormat("Could not write to {0} because {1}", Destination, exception); Failure(exception); yield break; } yield return(1); try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.WarnFormat("Could not write to {0} because {1}", Destination, exception); Failure(exception); yield break; } logger.DebugFormat("Successfully wrote to {0}", Destination); var recieveBuffer = new byte[ProtocolConstants.RecievedBuffer.Length]; var readConfirmationEnumerator = new AsyncEnumerator(); try { readConfirmationEnumerator.BeginExecute( StreamUtil.ReadBytes(recieveBuffer, stream, readConfirmationEnumerator, "recieve confirmation", false), ae.End()); } catch (Exception exception) { logger.WarnFormat("Could not read confirmation from {0} because {1}", Destination, exception); Failure(exception); yield break; } yield return(1); try { readConfirmationEnumerator.EndExecute(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.WarnFormat("Could not read confirmation from {0} because {1}", Destination, exception); Failure(exception); yield break; } var recieveRespone = Encoding.Unicode.GetString(recieveBuffer); if (recieveRespone == ProtocolConstants.QueueDoesNotExists) { logger.WarnFormat( "Response from reciever {0} is that queue does not exists", Destination); Failure(new QueueDoesNotExistsException()); yield break; } else if (recieveRespone != ProtocolConstants.Recieved) { logger.WarnFormat( "Response from reciever {0} is not the expected one, unexpected response was: {1}", Destination, recieveRespone); Failure(null); yield break; } try { stream.BeginWrite(ProtocolConstants.AcknowledgedBuffer, 0, ProtocolConstants.AcknowledgedBuffer.Length, ae.End(), null); } catch (Exception exception) { logger.WarnFormat("Failed to write acknowledgement to reciever {0} because {1}", Destination, exception); Failure(exception); yield break; } yield return(1); try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.WarnFormat("Failed to write acknowledgement to reciever {0} because {1}", Destination, exception); Failure(exception); yield break; } var bookmarks = Success(); buffer = new byte[ProtocolConstants.RevertBuffer.Length]; var readRevertMessage = new AsyncEnumerator(ae.ToString()); bool startingToReadFailed = false; try { readRevertMessage.BeginExecute( StreamUtil.ReadBytes(buffer, stream, readRevertMessage, "revert", true), ae.End()); } catch (Exception) { //more or less expected startingToReadFailed = true; } if (startingToReadFailed) { yield break; } yield return(1); try { readRevertMessage.EndExecute(ae.DequeueAsyncResult()); var revert = Encoding.Unicode.GetString(buffer); if (revert == ProtocolConstants.Revert) { logger.Warn("Got back revert message from receiver, reverting send"); Revert(bookmarks); } } catch (Exception) { // expected, there is nothing to do here, the // reciever didn't report anything for us } } } } finally { var completed = SendCompleted; if (completed != null) { completed(); } } }
private static IEnumerator<Int32> FetchStockQuotesAsyncEnumerator(AsyncEnumerator ae, WebService svc) { svc.BeginFetchStockQuotes(ae.End(), null); yield return 1; IStockQuote qt = svc.EndFetchStockQuotes(ae.DequeueAsyncResult()); }
private static IEnumerator<Int32> Process(AsyncEnumerator ae, TcpListener server) { server.BeginAcceptTcpClient(ae.End(), null); yield return 1; using (TcpClient client = server.EndAcceptTcpClient(ae.DequeueAsyncResult())) { Start(server); // Accept another client using (Stream stream = client.GetStream()) { // Read 1 byte from client which contains length of additional data Byte[] inputData = new Byte[1]; stream.BeginRead(inputData, 0, 1, ae.End(), null); yield return 1; // Client closed connection; abandon this client request if (stream.EndRead(ae.DequeueAsyncResult()) == 0) yield break; // Start to read 'length' bytes of data from client Int32 dataLength = inputData[0]; Array.Resize(ref inputData, 1 + dataLength); for (Byte bytesReadSoFar = 0; bytesReadSoFar < dataLength; ) { stream.BeginRead(inputData, 1 + bytesReadSoFar, inputData.Length - (bytesReadSoFar + 1), ae.End(), null); yield return 1; // Get number of bytes read from client Int32 numBytesReadThisTime = stream.EndRead(ae.DequeueAsyncResult()); // Client closed connection; abandon this client request if (numBytesReadThisTime == 0) yield break; // Continue to read bytes from client until all bytes are in bytesReadSoFar += (Byte)numBytesReadThisTime; } // All bytes have been read, process the input data Byte[] outputData = ProcessData(inputData); inputData = null; // Allow early GC // Write outputData back to client stream.BeginWrite(outputData, 0, outputData.Length, ae.End(), null); yield return 1; stream.EndWrite(ae.DequeueAsyncResult()); } } }
private IEnumerator<Int32> GetPhotos(AsyncEnumerator ae, String input) { WebRequest request = HttpWebRequest.Create( new Uri(String.Format("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key={0}&tags={1}&per_page=10", FlickrKey.Key, input))); ae.SetOperationTag("Querying " + request.RequestUri); request.BeginGetResponse(ae.End(), null); yield return 1; // Complete the Flickr request (this is guaranteed to run on the GUI thread) String data; using (HttpWebResponse response = (HttpWebResponse) request.EndGetResponse(ae.DequeueAsyncResult())) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { data = reader.ReadToEnd(); } } ae.SetOperationTag("Starting Storyboard"); EventApmFactory<EventArgs> eventArgsFactory = new EventApmFactory<EventArgs>(); EventHandler storyboardCompletedEventHandler = eventArgsFactory.PrepareOperation(ae.End()).EventHandler; SearchPanelStoryBoard.Completed += storyboardCompletedEventHandler; SearchPanelStoryBoard.Begin(); yield return 1; SearchPanelStoryBoard.Completed -= storyboardCompletedEventHandler; eventArgsFactory.EndInvoke(ae.DequeueAsyncResult()); PhotoBoard.Width = Application.Current.Host.Content.ActualWidth; PhotoBoard.Height = Application.Current.Host.Content.ActualHeight - 100.0; XDocument doc = XDocument.Parse(data); var photos = from results in doc.Descendants("photo") select new { id = results.Attribute("id").Value.ToString(), farm = results.Attribute("farm").Value.ToString(), server = results.Attribute("server").Value.ToString(), secret = results.Attribute("secret").Value.ToString() }; PhotoBoard.Children.Clear(); Int32 count = 0; EventApmFactory<OpenReadCompletedEventArgs> openReadCompletedEventArgsFactory = new EventApmFactory<OpenReadCompletedEventArgs>(); foreach (var photo in photos) { // Create a photo Border item = (Border) XamlReader.Load(String.Format(CultureInfo.InvariantCulture, c_template, count, (PhotoBoard.Width - c_cx) / 2, (PhotoBoard.Height - c_cy) / 2, // Initial position (center of workspace) c_cx + c_border, c_cy + c_border, // Width and height of photo border (c_cx + c_border) / 2, (c_cy + c_border) / 2, // Center of rotation c_cx, c_cy)); // Width and height of photo WebClient wc = new WebClient(); ae.SetOperationTag("Loading photo " + count); wc.OpenReadCompleted += openReadCompletedEventArgsFactory.PrepareOperation(ae.End()).EventHandler; wc.OpenReadAsync( new Uri(String.Format("http://farm{0}.static.flickr.com/{1}/{2}_{3}_m.jpg", photo.farm, photo.server, photo.id, photo.secret), UriKind.Absolute), item); count++; } while (count-- > 0) { yield return 1; // Process each image as it comes back OnReadCompleted(null, openReadCompletedEventArgsFactory.EndInvoke(ae.DequeueAsyncResult())); } }
private IEnumerator <Int32> UploadFileInBlocks(AsyncEnumerator ae, String pathname, CloudBlockBlob blob, Action <Int32> blockUploaded) { Int64 fileLength; using (var fs = new FileStream(pathname, FileMode.Open, FileAccess.Read, FileShare.Read)) using (var mmf = MemoryMappedFile.CreateFromFile(fs, null, fileLength = fs.Length, MemoryMappedFileAccess.Read, null, HandleInheritability.None, false)) { Byte[] uploadedBlocks = new Byte[(fileLength - 1) / m_blockSize + 1]; // Find out which blocks have been uploaded already? blob.BeginDownloadBlockList(BlockListingFilter.Uncommitted, AccessCondition.GenerateEmptyCondition(), null, null, ae.End(), null); yield return(1); try { foreach (ListBlockItem lbi in blob.EndDownloadBlockList(ae.DequeueAsyncResult())) { Int32 blockId = lbi.Name.FromBase64ToInt32(); uploadedBlocks[blockId] = 1; blockUploaded(blockId); } } catch (StorageException e) { if ((HttpStatusCode)e.RequestInformation.HttpStatusCode != HttpStatusCode.NotFound) { throw; } } // Start uploading the remaining blocks: Int32 blocksUploading = 0; foreach (var blockNumber in GetBlockNumbersFromArray(uploadedBlocks)) { // Start uploading up to 'm_concurrency' blocks blocksUploading++; var aeBlock = new AsyncEnumerator("Block #" + blockNumber); aeBlock.BeginExecute(UploadBlock(aeBlock, mmf, blob, blockNumber, (blockNumber == uploadedBlocks.Length - 1) ? fileLength % m_blockSize : m_blockSize), ae.End(), blockNumber); if (blocksUploading < m_concurrency) { continue; } // As each block completes uploading, start uploading a new block (if any are left) yield return(1); blocksUploading--; IAsyncResult result = ae.DequeueAsyncResult(); AsyncEnumerator.FromAsyncResult(result).EndExecute(result); blockUploaded((Int32)result.AsyncState); } // Wait until all blocks have finished uploading and then commit them all for (; blocksUploading > 0; blocksUploading--) { yield return(1); IAsyncResult result = ae.DequeueAsyncResult(); AsyncEnumerator.FromAsyncResult(result).EndExecute(result); blockUploaded((Int32)result.AsyncState); } // Commit all the blocks in order: blob.BeginPutBlockList(Enumerable.Range(0, uploadedBlocks.Length).Select(b => b.ToBase64()), ae.End(), null); yield return(1); blob.EndPutBlockList(ae.DequeueAsyncResult()); } }
public IEnumerator <int> AsyncLogin(LoginParameter parameter, AsyncEnumerator ae) { string connectionString = SettingManager.Default.ConnectionString; LoginInfo loginInfo = new LoginInfo() { Parameter = parameter }; if (LoginRetryTimeHelper.IsFailedCountExceeded(parameter.LoginId, ParticipantType.Customer, connectionString)) { loginInfo.Status = LoginStatus.ExceedMaxRetryCount; OnCompleted(loginInfo); yield break; } if (!parameter.LoginId.HasValue()) { loginInfo.Status = LoginStatus.LoginIdIsEmpty; OnCompleted(loginInfo); yield break; } Application.Default.ParticipantService.BeginLogin(parameter.LoginId, parameter.Password, ae.End(), null); yield return(1); try { loginInfo.UserID = Application.Default.ParticipantService.EndLogin(ae.DequeueAsyncResult()); } catch (Exception ex) { _Logger.Error(ex); loginInfo.Status = LoginStatus.ParticipantServiceLoginFailed; OnCompleted(loginInfo); yield break; } if (loginInfo.UserID == Guid.Empty) { loginInfo.Status = LoginStatus.UserIdIsEmpty; OnCompleted(loginInfo); yield break; } Guid programID = new Guid(SettingManager.Default.GetJavaTraderSettings("TradingConsole")); Guid permissionID = new Guid(SettingManager.Default.GetJavaTraderSettings("Run")); Application.Default.SecurityService.BeginCheckPermission(loginInfo.UserID, programID, permissionID, "", "", loginInfo.UserID, ae.End(), null); yield return(1); bool isAuthrized = false; try { string message; isAuthrized = Application.Default.SecurityService.EndCheckPermission(ae.DequeueAsyncResult(), out message); } catch (Exception ex) { _Logger.Error(ex); loginInfo.Status = LoginStatus.CheckPermissionFailed; OnCompleted(loginInfo); yield break; } if (!isAuthrized) { loginInfo.Status = LoginStatus.NotAuthrized; OnCompleted(loginInfo); yield break; } var token = new Token(Guid.Empty, UserType.Customer, parameter.AppType); token.UserID = loginInfo.UserID; token.SessionID = parameter.Request.ClientInfo.Session.ToString(); SessionManager.Default.AddToken(parameter.Request.ClientInfo.Session, token); var stateServerCallToken = new Token { UserID = token.UserID, AppType = AppType.TradingConsole, SessionID = token.SessionID, UserType = token.UserType }; Application.Default.StateServer.BeginLogin(stateServerCallToken, ae.End(), null); yield return(1); bool isStateServerLogined = false; try { isStateServerLogined = Application.Default.StateServer.EndLogin(ae.DequeueAsyncResult()); } catch (Exception ex) { _Logger.Error(ex); loginInfo.Status = LoginStatus.StateServerLoginFailed; OnCompleted(loginInfo); yield break; } if (!isStateServerLogined) { loginInfo.Status = LoginStatus.StateServerNotLogined; OnCompleted(loginInfo); yield break; } loginInfo.Status = LoginStatus.Success; OnCompleted(loginInfo); }
private static IEnumerator<Int32> Process(AsyncEnumerator ae, String server, String message) { TcpClient client = new TcpClient(server, 12000); Stream stream = client.GetStream(); Byte[] outputString = Encoding.UTF8.GetBytes(message); Byte[] outputData = new Byte[1 + outputString.Length]; outputData[0] = (Byte)outputString.Length; Array.Copy(outputString, 0, outputData, 1, outputString.Length); stream.BeginWrite(outputData, 0, outputData.Length, ae.End(), null); yield return 1; stream.EndWrite(ae.DequeueAsyncResult()); Byte[] inputData = new Byte[1 + 255]; stream.BeginRead(inputData, 0, 1, ae.End(), null); yield return 1; // Server closed connection if (stream.EndRead(ae.DequeueAsyncResult()) == 0) { client.Close(); yield break; } // Start to read 'length' bytes of data from server Int32 dataLength = inputData[0]; Array.Resize(ref inputData, 1 + dataLength); Int32 bytesReadSoFar = 0; while (bytesReadSoFar < dataLength) { stream.BeginRead(inputData, 1, dataLength, ae.End(), null); yield return 1; // Get number of bytes read from server Int32 numBytesReadThisTime = stream.EndRead(ae.DequeueAsyncResult()); // Server closed connection if (numBytesReadThisTime == 0) { client.Close(); yield break; } // Continue to read bytes from server until all bytes are in bytesReadSoFar += (Byte)numBytesReadThisTime; } // All bytes have been read, Show the server's result String result = Encoding.UTF8.GetString(inputData, 1, inputData[0]); Console.WriteLine("Received={0}", result); client.Close(); }
private IEnumerator <int> ProcessRequest(TcpClient client, AsyncEnumerator ae) { try { using (client) using (var stream = client.GetStream()) { var sender = client.Client.RemoteEndPoint; var lenOfDataToReadBuffer = new byte[sizeof(int)]; var lenEnumerator = new AsyncEnumerator(ae.ToString()); try { lenEnumerator.BeginExecute( StreamUtil.ReadBytes(lenOfDataToReadBuffer, stream, lenEnumerator, "length data", false), ae.End()); } catch (Exception exception) { logger.Warn("Unable to read length data from " + sender, exception); yield break; } yield return(1); try { lenEnumerator.EndExecute(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Unable to read length data from " + sender, exception); yield break; } var lengthOfDataToRead = BitConverter.ToInt32(lenOfDataToReadBuffer, 0); if (lengthOfDataToRead < 0) { logger.WarnFormat("Got invalid length {0} from sender {1}", lengthOfDataToRead, sender); yield break; } logger.DebugFormat("Reading {0} bytes from {1}", lengthOfDataToRead, sender); var buffer = new byte[lengthOfDataToRead]; var readBufferEnumerator = new AsyncEnumerator(ae.ToString()); try { readBufferEnumerator.BeginExecute( StreamUtil.ReadBytes(buffer, stream, readBufferEnumerator, "message data", false), ae.End()); } catch (Exception exception) { logger.Warn("Unable to read message data from " + sender, exception); yield break; } yield return(1); try { readBufferEnumerator.EndExecute(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Unable to read message data from " + sender, exception); yield break; } Message[] messages = null; try { messages = SerializationExtensions.ToMessages(buffer); logger.DebugFormat("Deserialized {0} messages from {1}", messages.Length, sender); } catch (Exception exception) { logger.Warn("Failed to deserialize messages from " + sender, exception); } if (messages == null) { try { stream.BeginWrite(ProtocolConstants.SerializationFailureBuffer, 0, ProtocolConstants.SerializationFailureBuffer.Length, ae.End(), null); } catch (Exception exception) { logger.Warn("Unable to send serialization format error to " + sender, exception); yield break; } yield return(1); try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Unable to send serialization format error to " + sender, exception); } yield break; } IMessageAcceptance acceptance = null; byte[] errorBytes = null; try { acceptance = acceptMessages(messages); logger.DebugFormat("All messages from {0} were accepted", sender); } catch (QueueDoesNotExistsException) { logger.WarnFormat("Failed to accept messages from {0} because queue does not exists", sender); errorBytes = ProtocolConstants.QueueDoesNoExiststBuffer; } catch (Exception exception) { errorBytes = ProtocolConstants.ProcessingFailureBuffer; logger.Warn("Failed to accept messages from " + sender, exception); } if (errorBytes != null) { try { stream.BeginWrite(errorBytes, 0, errorBytes.Length, ae.End(), null); } catch (Exception exception) { logger.Warn("Unable to send processing failure from " + sender, exception); yield break; } yield return(1); try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Unable to send processing failure from " + sender, exception); } yield break; } logger.DebugFormat("Sending reciept notice to {0}", sender); try { stream.BeginWrite(ProtocolConstants.RecievedBuffer, 0, ProtocolConstants.RecievedBuffer.Length, ae.End(), null); } catch (Exception exception) { logger.Warn("Could not send reciept notice to " + sender, exception); acceptance.Abort(); yield break; } yield return(1); try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Could not send reciept notice to " + sender, exception); acceptance.Abort(); yield break; } logger.DebugFormat("Reading acknowledgement about accepting messages to {0}", sender); var acknowledgementBuffer = new byte[ProtocolConstants.AcknowledgedBuffer.Length]; var readAcknoweldgement = new AsyncEnumerator(ae.ToString()); try { readAcknoweldgement.BeginExecute( StreamUtil.ReadBytes(acknowledgementBuffer, stream, readAcknoweldgement, "acknowledgement", false), ae.End()); } catch (Exception exception) { logger.Warn("Error reading acknowledgement from " + sender, exception); acceptance.Abort(); yield break; } yield return(1); try { readAcknoweldgement.EndExecute(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Error reading acknowledgement from " + sender, exception); acceptance.Abort(); yield break; } var senderResponse = Encoding.Unicode.GetString(acknowledgementBuffer); if (senderResponse != ProtocolConstants.Acknowledged) { logger.WarnFormat("Sender did not respond with proper acknowledgement, the reply was {0}", senderResponse); acceptance.Abort(); } bool commitSuccessful; try { acceptance.Commit(); commitSuccessful = true; } catch (Exception exception) { logger.Warn("Unable to commit messages from " + sender, exception); commitSuccessful = false; } if (commitSuccessful == false) { bool writeSuccessful; try { stream.BeginWrite(ProtocolConstants.RevertBuffer, 0, ProtocolConstants.RevertBuffer.Length, ae.End(), null); writeSuccessful = true; } catch (Exception e) { logger.Warn("Unable to send revert message to " + sender, e); writeSuccessful = false; } if (writeSuccessful) { yield return(1); try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Unable to send revert message to " + sender, exception); } } } } } finally { var copy = CompletedRecievingMessages; if (copy != null) { copy(); } } }
static IEnumerator<Int32> ServerConnectRemote(AsyncEnumerator ae, ServerState server, IPEndPoint ipe, TcpClient local) { // establish a client proxy -> real server connection var remote = new TcpClient(ipe.AddressFamily); var settings = server.settings; remote.NoDelay = true; remote.LingerState.Enabled = false; remote.BeginConnect(IPAddress.Parse(settings.addressforward), settings.portforward, ae.End(), ae); yield return 1; try { remote.EndConnect(ae.DequeueAsyncResult()); } catch (SocketException) { Console.WriteLine("A client failed to connect, has the real server started?"); local.Close(); remote.Close(); remote = null; } if(remote != null) { var bufParam = new ClientBufferParam(); { server.bufferPoolMutex.BeginRegion(SyncGateMode.Exclusive, ae.End()); yield return 1; var res = ae.DequeueAsyncResult(); server.AllocBuffer(ae, bufParam); server.bufferPoolMutex.EndRegion(res); } { var newClientState = new ClientState(local, remote); var remoteAe = new AsyncEnumerator(); var localAe = new AsyncEnumerator(); var bw1 = new BufferWrapper(bufParam.sendbuffer); var bw2 = new BufferWrapper(bufParam.recvbuffer); localAe.BeginExecute(HandleClient(localAe, server, newClientState, local, remote, bw1, server.filterSend), ae.End(), localAe); remoteAe.BeginExecute(HandleClient(remoteAe, server, newClientState, remote, local, bw2, server.filterRecv), ae.End(), remoteAe); Console.WriteLine("Client Connected {0}", local.Client.RemoteEndPoint); yield return 2; for (int x = 0; x < 2; x++) { IAsyncResult ar = ae.DequeueAsyncResult(); ((AsyncEnumerator)ar.AsyncState).EndExecute(ar); } bufParam.sendbuffer = bw1.buffer; bufParam.recvbuffer = bw2.buffer; } { server.bufferPoolMutex.BeginRegion(SyncGateMode.Exclusive, ae.End()); yield return 1; var res = ae.DequeueAsyncResult(); server.FreeBuffer(ae, bufParam); server.bufferPoolMutex.EndRegion(res); } } }
static IEnumerator<Int32> Server(AsyncEnumerator ae, ServerState server) { var sleeper = new CountdownTimer(); var settings = server.settings; var ipe = new IPEndPoint(IPAddress.Parse(settings.addressforward), settings.portforward); var serverSock = new TcpListener(IPAddress.Parse(settings.addresslisten), settings.portlisten); serverSock.Start(20); Console.WriteLine("Server started"); Console.WriteLine("Listening on {0}:{1}", settings.addresslisten, settings.portlisten); Console.WriteLine("Forwarding to {0}:{1}", settings.addressforward, settings.portforward); while (true) { serverSock.BeginAcceptTcpClient(ae.End(), null); yield return 1; TcpClient local = null; try { local = serverSock.EndAcceptTcpClient(ae.DequeueAsyncResult()); local.NoDelay = true; local.LingerState.Enabled = false; } catch (SocketException) { Console.WriteLine("A client failed to connect"); } if(local != null) { // handle client var localAe = new AsyncEnumerator(); localAe.BeginExecute(ServerConnectRemote(localAe, server, ipe, local), localAe.EndExecute, localAe); } } }
private IEnumerator<int> SendInternal(AsyncEnumerator ae) { try { using (var client = new TcpClient()) { try { client.BeginConnect(Destination.Host, Destination.Port, ae.End(), null); } catch (Exception exception) { logger.WarnFormat("Failed to connect to {0} because {1}", Destination, exception); Failure(exception); yield break; } yield return 1; try { client.EndConnect(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.WarnFormat("Failed to connect to {0} because {1}", Destination, exception); Failure(exception); yield break; } logger.DebugFormat("Successfully connected to {0}", Destination); using (var stream = client.GetStream()) { var buffer = Messages.Serialize(); var bufferLenInBytes = BitConverter.GetBytes(buffer.Length); logger.DebugFormat("Writing length of {0} bytes to {1}", buffer.Length, Destination); try { stream.BeginWrite(bufferLenInBytes, 0, bufferLenInBytes.Length, ae.End(), null); } catch (Exception exception) { logger.WarnFormat("Could not write to {0} because {1}", Destination, exception); Failure(exception); yield break; } yield return 1; try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.WarnFormat("Could not write to {0} because {1}", Destination, exception); Failure(exception); yield break; } logger.DebugFormat("Writing {0} bytes to {1}", buffer.Length, Destination); try { stream.BeginWrite(buffer, 0, buffer.Length, ae.End(), null); } catch (Exception exception) { logger.WarnFormat("Could not write to {0} because {1}", Destination, exception); Failure(exception); yield break; } yield return 1; try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.WarnFormat("Could not write to {0} because {1}", Destination, exception); Failure(exception); yield break; } logger.DebugFormat("Successfully wrote to {0}", Destination); var recieveBuffer = new byte[ProtocolConstants.RecievedBuffer.Length]; var readConfirmationEnumerator = new AsyncEnumerator(); try { readConfirmationEnumerator.BeginExecute( StreamUtil.ReadBytes(recieveBuffer, stream, readConfirmationEnumerator, "recieve confirmation", false), ae.End()); } catch (Exception exception) { logger.WarnFormat("Could not read confirmation from {0} because {1}", Destination, exception); Failure(exception); yield break; } yield return 1; try { readConfirmationEnumerator.EndExecute(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.WarnFormat("Could not read confirmation from {0} because {1}", Destination, exception); Failure(exception); yield break; } var recieveRespone = Encoding.Unicode.GetString(recieveBuffer); if (recieveRespone == ProtocolConstants.QueueDoesNotExists) { logger.WarnFormat( "Response from reciever {0} is that queue does not exists", Destination); Failure(new QueueDoesNotExistsException()); yield break; } else if(recieveRespone!=ProtocolConstants.Recieved) { logger.WarnFormat( "Response from reciever {0} is not the expected one, unexpected response was: {1}", Destination, recieveRespone); Failure(null); yield break; } try { stream.BeginWrite(ProtocolConstants.AcknowledgedBuffer, 0, ProtocolConstants.AcknowledgedBuffer.Length, ae.End(), null); } catch (Exception exception) { logger.WarnFormat("Failed to write acknowledgement to reciever {0} because {1}", Destination, exception); Failure(exception); yield break; } yield return 1; try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.WarnFormat("Failed to write acknowledgement to reciever {0} because {1}", Destination, exception); Failure(exception); yield break; } var bookmarks = Success(); buffer = new byte[ProtocolConstants.RevertBuffer.Length]; var readRevertMessage = new AsyncEnumerator(ae.ToString()); bool startingToReadFailed = false; try { readRevertMessage.BeginExecute( StreamUtil.ReadBytes(buffer, stream, readRevertMessage, "revert", true), ae.End()); } catch (Exception) { //more or less expected startingToReadFailed = true; } if (startingToReadFailed) yield break; yield return 1; try { readRevertMessage.EndExecute(ae.DequeueAsyncResult()); var revert = Encoding.Unicode.GetString(buffer); if (revert == ProtocolConstants.Revert) { logger.Warn("Got back revert message from receiver, reverting send"); Revert(bookmarks); } } catch (Exception) { // expected, there is nothing to do here, the // reciever didn't report anything for us } } } } finally { var completed = SendCompleted; if (completed != null) completed(); } }
private IEnumerator<Int32> ExecuteWithAsyncEnumerator(AsyncEnumerator ae) { for (Int32 n = 0; n < c_iterations; n++) { Cargo cargo = CargoFactory.CreateNew("Glyfada" + n, "Perachora" + n); App.Database.BeginSave<Cargo>(cargo, ae.End(), null); } // NOTE: AsyncEnumerator captures the calling thread's SynchronizationContext. // Set the Wintellect.Threading.AsyncProgModel.SynchronizationContext type to // null so that the callback continues on a ThreadPool thread. ae.SyncContext = null; yield return c_iterations; for (Int32 n = 0; n < c_iterations; n++) { App.Database.EndSave(ae.DequeueAsyncResult()); } // AsyncEnumerator captures the synchronization context. SetStatus("AsyncEnumerator completed.", StatusState.Ready); }
private IEnumerator <int> ProcessProxyRequest(AsyncEnumerator ae) { ExTraceGlobals.ProxyCallTracer.TraceDebug((long)this.GetHashCode(), "ProxyEventHandler.SendProxyRequest"); base.DontWriteHeaders = true; int newContentLength = 0; byte[] soapHeaderStuff = this.GetRequestSoapHeader(out newContentLength); HttpWebRequest webRequest = this.GetProxyRequest(newContentLength); WindowsImpersonationContext context = NetworkServiceImpersonator.Impersonate(); try { ae.AddAsync <IAsyncResult>(webRequest.BeginGetRequestStream(ae.GetAsyncCallback(), null)); } catch { context.Undo(); context = null; throw; } finally { if (context != null) { context.Undo(); context = null; } } yield return(1); Stream outStream = this.DoWebAction <Stream>(() => webRequest.EndGetRequestStream(ae.CompletedAsyncResults[0])); if (outStream == null) { ae.End(); } else { using (outStream) { ae.AddAsync <IAsyncResult>(outStream.BeginWrite(soapHeaderStuff, 0, soapHeaderStuff.Length, ae.GetAsyncCallback(), null)); yield return(1); outStream.EndWrite(ae.CompletedAsyncResults[0]); AsyncResult asyncResult = ae.AddAsyncEnumerator((AsyncEnumerator ae1) => ProxyToEwsEventHandler.CopyStream(ae1, this.HttpContext.Request.InputStream, outStream)); yield return(1); asyncResult.End(); } ae.AddAsync <IAsyncResult>(webRequest.BeginGetResponse(ae.GetAsyncCallback(), null)); yield return(1); HttpWebResponse webResponse = this.DoWebAction <HttpWebResponse>(() => (HttpWebResponse)webRequest.EndGetResponse(ae.CompletedAsyncResults[0])); if (webResponse != null) { using (webResponse) { ae.AddAsyncEnumerator((AsyncEnumerator ae1) => this.ProcessWebResponse(ae1, webResponse)); yield return(1); } } ae.End(); } yield break; }
private IEnumerator<Int32> ExecuteWithAsyncEnumerator(AsyncEnumerator ae) { for (Int32 n = 0; n < c_iterations; n++) { ((WebService)m_webService).BeginGetStockQuotes(ae.End(), null); } // NOTE: AsyncEnumerator captures the calling thread's SynchronizationContext. // Set the Wintellect.Threading.AsyncProgModel.SynchronizationContext type to // null so that the callback continues on a ThreadPool thread. ae.SyncContext = null; yield return c_iterations; for (Int32 n = 0; n < c_iterations; n++) { ((WebService)m_webService).EndGetStockQuotes(ae.DequeueAsyncResult()); } // AsyncEnumerator captures the synchronization context. SetStatus("AsyncEnumerator completed.", StatusState.Ready); }
private IEnumerator<Int32> Process(AsyncEnumerator ae) { StringBuilder sb = new StringBuilder(); while (true) { if (charPos == charLen) { do { charLen = 0; charPos = 0; byteLen = 0; stream.BeginRead(byteBuffer, 0, byteBuffer.Length, ae.End(), null); yield return 1; byteLen = stream.EndRead(ae.DequeueAsyncResult()); if (byteLen == 0) { if (sb.Length > 0) { LineRead(this, sb.ToString()); sb.Length = 0; } EOFReached(this); yield break; } charLen += decoder.GetChars(byteBuffer, 0, byteLen, charBuffer, charLen); } while (charLen ==0); } int i = charPos; do { char ch = charBuffer[i]; if (ch == '\r' || ch == '\n') { sb.Append(charBuffer, charPos, i - charPos); charPos = i + 1; if (ch == '\r' && (charPos < charLen )) //|| ReadBuffer() > 0) { if (charBuffer[charPos] == '\n') { charPos++; i++; } } LineRead(this, sb.ToString()); sb.Length=0; } i++; } while (i < charLen); i = charLen - charPos; sb.Append(charBuffer, charPos, i); charPos = charLen; } }
static IEnumerator <int> ForwardingFiber(AsyncEnumerator ae, NetworkStream inputStream, NetworkStream outputStream) { while (!ae.IsCanceled()) { byte[] outputRead = new byte[bufsize], outputWrite = new byte[bufsize]; byte[] inputRead = new byte[bufsize], inputWrite = new byte[bufsize]; // start off output and input reads. // NB ObjectDisposedExceptions can be raised here when a socket is closed while an async read is in progress. outputStream.BeginRead(outputRead, 0, bufsize, ae.End(1, ar => outputStream.EndRead(ar)), Operation.OutboundRead); inputStream.BeginRead(inputRead, 0, bufsize, ae.End(1, ar => inputStream.EndRead(ar)), Operation.InboundRead); var pendingops = 2; while (!ae.IsCanceled()) { // wait for the next operation to complete, the state object passed to each async // call can be used to find out what completed. if (pendingops == 0) { yield break; } yield return(1); if (!ae.IsCanceled()) { int byteCount; var latestEvent = ae.DequeueAsyncResult(); var currentOp = (Operation)latestEvent.AsyncState; if (currentOp == Operation.InboundRead) { byteCount = inputStream.EndRead(latestEvent); if (byteCount == 0) { pendingops--; outputStream.Close(); continue; } Array.Copy(inputRead, outputWrite, byteCount); outputStream.BeginWrite(outputWrite, 0, byteCount, ae.EndVoid(1, outputStream.EndWrite), Operation.OutboundWrite); inputStream.BeginRead(inputRead, 0, bufsize, ae.End(1, ar => inputStream.EndRead(ar)), Operation.InboundRead); } else if (currentOp == Operation.OutboundRead) { byteCount = outputStream.EndRead(latestEvent); if (byteCount == 0) { pendingops--; inputStream.Close(); continue; } Array.Copy(outputRead, inputWrite, byteCount); inputStream.BeginWrite(inputWrite, 0, byteCount, ae.EndVoid(1, inputStream.EndWrite), Operation.InboundWrite); outputStream.BeginRead(outputRead, 0, bufsize, ae.End(1, ar => outputStream.EndRead(ar)), Operation.OutboundRead); } else if (currentOp == Operation.InboundWrite) { inputStream.EndWrite(latestEvent); } else if (currentOp == Operation.OutboundWrite) { outputStream.EndWrite(latestEvent); } } } } }
private static IEnumerator<int> GenerateTransferTask( AsyncEnumerator ae, HttpContext context, string url) { WebRequest request = WebRequest.Create(url); request.BeginGetResponse(ae.End(), null); yield return 1; using (WebResponse response = request.EndGetResponse(ae.DequeueAsyncResult())) { Stream streamIn = response.GetResponseStream(); Stream streamOut = context.Response.OutputStream; byte[] buffer = new byte[1024]; while (true) { streamIn.BeginRead(buffer, 0, buffer.Length, ae.End(), null); yield return 1; int lengthRead = streamIn.EndRead(ae.DequeueAsyncResult()); if (lengthRead <= 0) break; streamOut.BeginWrite(buffer, 0, lengthRead, ae.End(), null); yield return 1; streamOut.EndWrite(ae.DequeueAsyncResult()); } } }
private IEnumerator <int> ProcessCollectQuotes(AsyncEnumerator asyncEnumerator, string topic, CultureInfo culture, Uri uri, AssignQuotePageDataDelegate assignQuotesDelegate) { Uri quoteSourceUri = GetQuoteSourceUri(culture, topic); Util.BeginFetchXmlPage(quoteSourceUri, asyncEnumerator.End(AsyncEnumeratorDiscardGroup, Util.EndFetchXmlPage), null); yield return(1); if (asyncEnumerator.IsCanceled()) { yield break; } string contents; try { XDocument xDocument = Util.EndFetchXmlPage(asyncEnumerator.DequeueAsyncResult()); if (xDocument == null) { throw new NullReferenceException(); } // extracting the page contents contents = GetXmlPageContents(xDocument); } catch (Exception ex) { OnErrorCollectingQuotes(new ErrorCollectingQuotesEventArgs(topic, culture, uri, ex)); yield break; } IAsyncResult getQuotesResult = BeginParsePageContentsAndExtractQuotes(topic, culture, contents, null, asyncEnumerator.End(AsyncEnumeratorDiscardGroup, EndParsePageContentsAndExtractQuotes), null); IAsyncResult getTopicTranslationsResult = BeginExtractTopicTranslations(contents, asyncEnumerator.End(AsyncEnumeratorDiscardGroup, EndExtractTopicTranslations), null); yield return(2); if (asyncEnumerator.IsCanceled()) { yield break; } try { TopicTranslation[] topicTranslations = EndExtractTopicTranslations(getTopicTranslationsResult); SelectableQuoteCollection quotes = EndParsePageContentsAndExtractQuotes(getQuotesResult); if (quotes.Count == 0) { OnNoQuotesCollected(new NoQuotesCollectedEventArgs(topic, culture, uri)); // Change by Ming Slogar on 26Apr2014 at 20:25 // Reason: The following line prevents the topic from being returned // when it has no listed quotes. //yield break; } assignQuotesDelegate.Invoke(quotes, topicTranslations); } catch (TopicAmbiguousException ex) { OnTopicAmbiguous(new TopicAmbiguousEventArgs(topic, culture, uri, ex.TopicChoices)); yield break; } catch (Exception ex) { OnErrorCollectingQuotes(new ErrorCollectingQuotesEventArgs(topic, culture, uri, ex)); yield break; } finally { // cleanup asyncEnumerator.DequeueAsyncResult(); asyncEnumerator.DequeueAsyncResult(); lock (asyncEnumerator) { _asyncEnumerators.Remove(asyncEnumerator); } } }
private IEnumerator<int> ProcessRequest(TcpClient client, AsyncEnumerator ae) { try { using (client) using (var stream = client.GetStream()) { var sender = client.Client.RemoteEndPoint; var lenOfDataToReadBuffer = new byte[sizeof(int)]; var lenEnumerator = new AsyncEnumerator(ae.ToString()); try { lenEnumerator.BeginExecute( StreamUtil.ReadBytes(lenOfDataToReadBuffer, stream, lenEnumerator, "length data",false), ae.End()); } catch (Exception exception) { logger.Warn("Unable to read length data from " + sender, exception); yield break; } yield return 1; try { lenEnumerator.EndExecute(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Unable to read length data from " + sender, exception); yield break; } var lengthOfDataToRead = BitConverter.ToInt32(lenOfDataToReadBuffer, 0); if (lengthOfDataToRead < 0) { logger.WarnFormat("Got invalid length {0} from sender {1}", lengthOfDataToRead, sender); yield break; } logger.DebugFormat("Reading {0} bytes from {1}", lengthOfDataToRead, sender); var buffer = new byte[lengthOfDataToRead]; var readBufferEnumerator = new AsyncEnumerator(ae.ToString()); try { readBufferEnumerator.BeginExecute( StreamUtil.ReadBytes(buffer, stream, readBufferEnumerator, "message data", false), ae.End()); } catch (Exception exception) { logger.Warn("Unable to read message data from " + sender, exception); yield break; } yield return 1; try { readBufferEnumerator.EndExecute(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Unable to read message data from " + sender, exception); yield break; } Message[] messages = null; try { messages = SerializationExtensions.ToMessages(buffer); logger.DebugFormat("Deserialized {0} messages from {1}", messages.Length, sender); } catch (Exception exception) { logger.Warn("Failed to deserialize messages from " + sender, exception); } if (messages == null) { try { stream.BeginWrite(ProtocolConstants.SerializationFailureBuffer, 0, ProtocolConstants.SerializationFailureBuffer.Length, ae.End(), null); } catch (Exception exception) { logger.Warn("Unable to send serialization format error to " + sender, exception); yield break; } yield return 1; try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Unable to send serialization format error to " + sender, exception); } yield break; } IMessageAcceptance acceptance = null; byte[] errorBytes = null; try { acceptance = acceptMessages(messages); logger.DebugFormat("All messages from {0} were accepted", sender); } catch (QueueDoesNotExistsException) { logger.WarnFormat("Failed to accept messages from {0} because queue does not exists", sender); errorBytes = ProtocolConstants.QueueDoesNoExiststBuffer; } catch (Exception exception) { errorBytes = ProtocolConstants.ProcessingFailureBuffer; logger.Warn("Failed to accept messages from " + sender, exception); } if (errorBytes != null) { try { stream.BeginWrite(errorBytes, 0, errorBytes.Length, ae.End(), null); } catch (Exception exception) { logger.Warn("Unable to send processing failure from " + sender, exception); yield break; } yield return 1; try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Unable to send processing failure from " + sender, exception); } yield break; } logger.DebugFormat("Sending reciept notice to {0}", sender); try { stream.BeginWrite(ProtocolConstants.RecievedBuffer, 0, ProtocolConstants.RecievedBuffer.Length, ae.End(), null); } catch (Exception exception) { logger.Warn("Could not send reciept notice to " + sender, exception); acceptance.Abort(); yield break; } yield return 1; try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Could not send reciept notice to " + sender, exception); acceptance.Abort(); yield break; } logger.DebugFormat("Reading acknowledgement about accepting messages to {0}", sender); var acknowledgementBuffer = new byte[ProtocolConstants.AcknowledgedBuffer.Length]; var readAcknoweldgement = new AsyncEnumerator(ae.ToString()); try { readAcknoweldgement.BeginExecute( StreamUtil.ReadBytes(acknowledgementBuffer, stream, readAcknoweldgement, "acknowledgement", false), ae.End()); } catch (Exception exception) { logger.Warn("Error reading acknowledgement from " + sender, exception); acceptance.Abort(); yield break; } yield return 1; try { readAcknoweldgement.EndExecute(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Error reading acknowledgement from " + sender, exception); acceptance.Abort(); yield break; } var senderResponse = Encoding.Unicode.GetString(acknowledgementBuffer); if (senderResponse != ProtocolConstants.Acknowledged) { logger.WarnFormat("Sender did not respond with proper acknowledgement, the reply was {0}", senderResponse); acceptance.Abort(); } bool commitSuccessful; try { acceptance.Commit(); commitSuccessful = true; } catch (Exception exception) { logger.Warn("Unable to commit messages from " + sender, exception); commitSuccessful = false; } if (commitSuccessful == false) { bool writeSuccessful; try { stream.BeginWrite(ProtocolConstants.RevertBuffer, 0, ProtocolConstants.RevertBuffer.Length, ae.End(), null); writeSuccessful = true; } catch (Exception e) { logger.Warn("Unable to send revert message to " + sender, e); writeSuccessful = false; } if (writeSuccessful) { yield return 1; try { stream.EndWrite(ae.DequeueAsyncResult()); } catch (Exception exception) { logger.Warn("Unable to send revert message to " + sender, exception); } } } } } finally { var copy = CompletedRecievingMessages; if (copy != null) copy(); } }
public static IEnumerator <int> ReadBytes( byte[] buffer, Stream stream, AsyncEnumerator ae, string type, bool expectedToHaveNoData) { var totalBytesRead = 0; while (totalBytesRead < buffer.Length) { stream.BeginRead(buffer, totalBytesRead, buffer.Length - totalBytesRead, ae.End(), null); yield return(1); int bytesRead = stream.EndRead(ae.DequeueAsyncResult()); if (bytesRead == 0) { if (expectedToHaveNoData) { yield break; } throw new InvalidOperationException("Could not read value for " + type); } totalBytesRead += bytesRead; } }
static IEnumerator<Int32> HandleClient(AsyncEnumerator ae, ServerState server, ClientState client, TcpClient tcpRecv, TcpClient tcpSend, BufferWrapper bw, FilterFunc filterFunc) { // add the client to the clients list { server.clientsMutex.BeginRegion(SyncGateMode.Exclusive, ae.End()); yield return 1; var mutexResult = ae.DequeueAsyncResult(); { if (!server.clients.ContainsKey(client.localtcp)) { server.clients[client.localtcp] = client; } } server.clientsMutex.EndRegion(mutexResult); } Socket sockRecv = tcpRecv.Client; Socket sockSend = tcpSend.Client; bool wantDisconnect = false; int len = 0; while (true) { // read message try { // resize buffer if needed so that it has initialbuffersize spaces at the end if((bw.buffer.Length - len) < server.settings.initialbuffersize) { Array.Resize(ref bw.buffer, len + server.settings.initialbuffersize); } sockRecv.BeginReceive(bw.buffer, len, server.settings.initialbuffersize, SocketFlags.None, ae.End(), null); } catch (Exception) { break; } yield return 1; try { int tmplen = sockRecv.EndReceive(ae.DequeueAsyncResult()); if (tmplen == 0) { break; } else { len += tmplen; } } catch (Exception) { break; } // filter the packets here switch (filterFunc(client, bw.buffer, len)) { case FilterIntent.Buffer: break; case FilterIntent.Accept: int sent = 0; while(sent < len) { // echo the data back to the client try { sockSend.BeginSend(bw.buffer, sent, len-sent, SocketFlags.None, ae.End(), null); } catch (Exception) { wantDisconnect = true; break; } yield return 1; try { sent += sockSend.EndSend(ae.DequeueAsyncResult()); } catch (Exception) { wantDisconnect = true; break; } } len = 0; break; case FilterIntent.Drop: len = 0; break; case FilterIntent.Disconnect: wantDisconnect = true; break; } if(wantDisconnect) break; } // remove the client from the list { server.clientsMutex.BeginRegion(SyncGateMode.Exclusive, ae.End()); yield return 1; var mutexResult = ae.DequeueAsyncResult(); { if (server.clients.ContainsKey(client.localtcp)) { var removed = server.clients.Remove(client.localtcp); Console.WriteLine("Client disconnected {0} - {1}", client.localtcp.Client.RemoteEndPoint, removed); // dont forget to dispose it tcpRecv.Close(); tcpSend.Close(); } } server.clientsMutex.EndRegion(mutexResult); } }
public IEnumerator<int> AsyncLogin(LoginParameter parameter,AsyncEnumerator ae) { string connectionString = SettingManager.Default.ConnectionString; LoginInfo loginInfo = new LoginInfo() { Parameter=parameter}; if (LoginRetryTimeHelper.IsFailedCountExceeded(parameter.LoginId, ParticipantType.Customer, connectionString)) { loginInfo.Status = LoginStatus.ExceedMaxRetryCount; OnCompleted(loginInfo); yield break; } if (!parameter.LoginId.HasValue()) { loginInfo.Status = LoginStatus.LoginIdIsEmpty; OnCompleted(loginInfo); yield break; } Application.Default.ParticipantService.BeginLogin(parameter.LoginId, parameter.Password,ae.End(), null); yield return 1; try { loginInfo.UserID = Application.Default.ParticipantService.EndLogin(ae.DequeueAsyncResult()); } catch (Exception ex) { _Logger.Error(ex); loginInfo.Status = LoginStatus.ParticipantServiceLoginFailed; OnCompleted(loginInfo); yield break; } if (loginInfo.UserID == Guid.Empty) { loginInfo.Status = LoginStatus.UserIdIsEmpty; OnCompleted(loginInfo); yield break; } Guid programID = new Guid(SettingManager.Default.GetJavaTraderSettings("TradingConsole")); Guid permissionID = new Guid(SettingManager.Default.GetJavaTraderSettings("Run")); Application.Default.SecurityService.BeginCheckPermission(loginInfo.UserID, programID, permissionID, "", "", loginInfo.UserID, ae.End(), null); yield return 1; bool isAuthrized = false; try { string message; isAuthrized = Application.Default.SecurityService.EndCheckPermission(ae.DequeueAsyncResult(), out message); } catch (Exception ex) { _Logger.Error(ex); loginInfo.Status = LoginStatus.CheckPermissionFailed; OnCompleted(loginInfo); yield break; } if (!isAuthrized) { loginInfo.Status = LoginStatus.NotAuthrized; OnCompleted(loginInfo); yield break; } var token = new Token(Guid.Empty, UserType.Customer, parameter.AppType); token.UserID = loginInfo.UserID; token.SessionID = parameter.Request.ClientInfo.Session.ToString(); SessionManager.Default.AddToken(parameter.Request.ClientInfo.Session, token); var stateServerCallToken = new Token { UserID = token.UserID, AppType = AppType.TradingConsole, SessionID = token.SessionID, UserType=token.UserType }; Application.Default.StateServer.BeginLogin(stateServerCallToken, ae.End(), null); yield return 1; bool isStateServerLogined = false; try { isStateServerLogined = Application.Default.StateServer.EndLogin(ae.DequeueAsyncResult()); } catch (Exception ex) { _Logger.Error(ex); loginInfo.Status = LoginStatus.StateServerLoginFailed; OnCompleted(loginInfo); yield break; } if (!isStateServerLogined) { loginInfo.Status = LoginStatus.StateServerNotLogined; OnCompleted(loginInfo); yield break; } loginInfo.Status = LoginStatus.Success; OnCompleted(loginInfo); }