/// <summary> /// Begins an asynchronous <c>LoadUser</c> operation. /// </summary> /// <param name="callback">The callback to invoke when the asynchronous call completes</param> /// <param name="state">The optional result state</param> /// <returns>An <see cref="IAsyncResult"/> that represents the asynchronous call</returns> /// <exception cref="InvalidOperationException"> is thrown if the /// <see cref="WebAuthenticationService.DomainContext"/> is <c>null</c> and a new instance /// cannot be created. /// </exception> protected internal override IAsyncResult BeginLoadUser(AsyncCallback callback, object state) { this.Initialize(); WebAsyncResult result = new WebAsyncResult(callback, state); EntityQuery query; try { query = (EntityQuery)this.DomainContext.GetType().GetMethod( WebAuthenticationService.LoadUserQueryName, TypeUtility.EmptyTypes).Invoke( this.DomainContext, TypeUtility.EmptyTypes); } catch (TargetInvocationException tie) { if (tie.InnerException != null) { throw tie.InnerException; } throw; } result.InnerOperation = this.DomainContext.Load( query, LoadBehavior.MergeIntoCurrent, (Action <LoadOperation>) this.HandleOperationComplete, result); return(result); }
/// <summary> /// Cancels an asynchronous <c>Logout</c> operation. /// </summary> /// <param name="asyncResult">A result returned from <see cref="BeginLogout"/> that represents /// the asynchronous call to cancel. /// </param> /// <exception cref="InvalidOperationException"> is thrown if <paramref name="asyncResult"/> /// was not returned from <see cref="BeginLogout"/> or the asynchronous call has already been /// concluded with a previous call to cancel or end. /// </exception> protected internal override void CancelLogout(IAsyncResult asyncResult) { WebAsyncResult result = AsyncResultBase.EndAsyncOperation <WebAsyncResult>(asyncResult, true); if (result.InnerOperation.CanCancel) { result.InnerOperation.Cancel(); } }
/// <summary> /// Cancels an asynchronous <c>SaveUser</c> operation. /// </summary> /// <param name="asyncResult">A result returned from <see cref="BeginSaveUser"/> that represents /// the asynchronous call to cancel. /// </param> /// <exception cref="InvalidOperationException"> is thrown if <paramref name="asyncResult"/> /// was not returned from <see cref="BeginSaveUser"/> or the asynchronous call has already been /// concluded with a previous call to cancel or end. /// </exception> protected override void CancelSaveUser(IAsyncResult asyncResult) { WebAsyncResult result = AsyncResultBase.EndAsyncOperation <WebAsyncResult>(asyncResult, true); if (result.InnerOperation.CanCancel) { result.InnerOperation.Cancel(); } }
//异步结束时,由ASP.NET调用此方法 public void EndProcessRequest(IAsyncResult result) { WebAsyncResult webresult = (WebAsyncResult)result; //Log.WriteLog("行情调用", ""); //webresult.Context.Response.Write("\tEnd:"); //webresult.Context.Response.Write(DateTime.Now.ToString("mm:ss,ffff")); ////输出当前线程 //webresult.Context.Response.Write("\tThreadId:"); //webresult.Context.Response.Write(Thread.CurrentThread.ManagedThreadId); }
public override void EndWrite(IAsyncResult r) { if (r == null) { throw new ArgumentNullException("r"); } WebAsyncResult result = r as WebAsyncResult; if (result == null) { throw new ArgumentException("Invalid IAsyncResult"); } if (result.EndCalled) { return; } result.EndCalled = true; if (result.AsyncWriteAll) { result.WaitUntilComplete(); if (result.GotException) { throw result.Exception; } return; } if (allowBuffering && !sendChunked) { return; } if (result.GotException) { throw result.Exception; } if (sendChunked) { lock (locker) { pendingWrites--; if (pendingWrites == 0) { pending.Set(); } } } }
/// <summary> /// Handles completion of the underlying operation in the <see cref="DomainContext"/>. /// </summary> /// <param name="operation">The operation that completed</param> private void HandleOperationComplete(OperationBase operation) { WebAsyncResult result = ((WebAsyncResult)operation.UserState); if (operation.HasError) { operation.MarkErrorAsHandled(); } if (!operation.IsCanceled) { result.Complete(); } }
public override int Read(byte[] buffer, int offset, int size) { AsyncCallback cb = cb_wrapper; WebAsyncResult res = (WebAsyncResult)BeginRead(buffer, offset, size, cb, null); if (!res.IsCompleted && !res.WaitUntilComplete(ReadTimeout, false)) { nextReadCalled = true; cnc.Close(true); throw new WebException("The operation has timed out.", WebExceptionStatus.Timeout); } return(EndRead(res)); }
/// <summary> /// Ends an asynchronous <c>Login</c> operation. /// </summary> /// <param name="asyncResult">A result returned from <see cref="BeginLogin"/> that represents /// the asynchronous call to conclude. /// </param> /// <returns>The result of the asynchronous <c>Login</c> call</returns> /// <exception cref="InvalidOperationException"> is thrown if <paramref name="asyncResult"/> /// was not returned from <see cref="BeginLogin"/> or the asynchronous call has already been /// concluded with a previous call to cancel or end. /// </exception> protected override LoginResult EndLogin(IAsyncResult asyncResult) { WebAsyncResult result = AsyncResultBase.EndAsyncOperation <WebAsyncResult>(asyncResult); if (result.InnerOperation.HasError) { throw result.InnerOperation.Error; } IPrincipal user = (IPrincipal)((LoadOperation)result.InnerOperation).Entities.SingleOrDefault(); this.PrepareUser(user); return(new LoginResult(user, (user != null))); }
public override void Write(byte[] buffer, int offset, int size) { AsyncCallback cb = cb_wrapper; WebAsyncResult res = (WebAsyncResult)BeginWrite(buffer, offset, size, cb, null); if (!res.IsCompleted && !res.WaitUntilComplete(WriteTimeout, false)) { KillBuffer(); nextReadCalled = true; cnc.Close(true); throw new IOException("Write timed out."); } EndWrite(res); }
/// <summary> /// Begins an asynchronous <c>SaveUser</c> operation. /// </summary> /// <param name="user">The authenticated user to save</param> /// <param name="callback">The callback to invoke when the asynchronous call completes</param> /// <param name="state">The optional result state</param> /// <returns>An <see cref="IAsyncResult"/> that represents the asynchronous call</returns> /// <exception cref="InvalidOperationException"> is thrown if the user is anonymous.</exception> /// <exception cref="InvalidOperationException"> is thrown if the /// <see cref="WebAuthenticationService.DomainContext"/> is <c>null</c> and a new instance /// cannot be created. /// </exception> protected override IAsyncResult BeginSaveUser(IPrincipal user, AsyncCallback callback, object state) { this.Initialize(); if (!user.Identity.IsAuthenticated) { throw new InvalidOperationException(Resources.ApplicationServices_CannotSaveAnonymous); } WebAsyncResult result = new WebAsyncResult(callback, state); result.InnerOperation = this.DomainContext.SubmitChanges( (Action <SubmitOperation>) this.HandleOperationComplete, result); return(result); }
/// <summary> /// Ends an asynchronous <c>LoadUser</c> operation. /// </summary> /// <param name="asyncResult">A result returned from <see cref="BeginLoadUser"/> that represents /// the asynchronous call to conclude. /// </param> /// <returns>The result of the asynchronous <c>LoadUser</c> call</returns> /// <exception cref="InvalidOperationException"> is thrown if <paramref name="asyncResult"/> /// was not returned from <see cref="BeginLoadUser"/> or the asynchronous call has already been /// concluded with a previous call to cancel or end. /// </exception> protected override LoadUserResult EndLoadUser(IAsyncResult asyncResult) { WebAsyncResult result = AsyncResultBase.EndAsyncOperation <WebAsyncResult>(asyncResult); if (result.InnerOperation.HasError) { throw result.InnerOperation.Error; } IPrincipal user = (IPrincipal)((LoadOperation)result.InnerOperation).Entities.SingleOrDefault(); if (user == null) { throw new InvalidOperationException(Resources.ApplicationServices_LoadNoUser); } this.PrepareUser(user); return(new LoadUserResult(user)); }
//请求开始时由ASP.NET调用此方法 public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) { context.Response.ContentType = "text/plain"; string code = AppRequest.GetQueryString("code", true); int flag = AppRequest.GetQueryInt("flag", 0); if (code.Length < 6) { context.Response.Write("fail"); } else { context.Response.Write(RedisHelper.GetValues(Utils.GetFullStockCode(code, flag)) + ",0"); } //构建异步结果并返回 var result = new WebAsyncResult(cb, context); result.SetComplete(); return result; }
//请求开始时由ASP.NET调用此方法 public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) { context.Response.ContentType = "text/plain"; string code = AppRequest.GetQueryString("code"); if (code.Length < 6) { context.Response.Write("fail"); } else { context.Response.Write(RedisHelper.GetValues(code)); } //构建异步结果并返回 var result = new WebAsyncResult(cb, context); result.SetComplete(); return(result); }
/// <summary> /// Ends an asynchronous <c>SaveUser</c> operation. /// </summary> /// <param name="asyncResult">A result returned from <see cref="BeginSaveUser"/> that represents /// the asynchronous call to conclude. /// </param> /// <returns>The result of the asynchronous <c>SaveUser</c> call</returns> /// <exception cref="InvalidOperationException"> is thrown if <paramref name="asyncResult"/> /// was not returned from <see cref="BeginSaveUser"/> or the asynchronous call has already been /// concluded with a previous call to cancel or end. /// </exception> protected override SaveUserResult EndSaveUser(IAsyncResult asyncResult) { WebAsyncResult result = AsyncResultBase.EndAsyncOperation <WebAsyncResult>(asyncResult); if (result.InnerOperation.HasError) { throw result.InnerOperation.Error; } if (((SubmitOperation)result.InnerOperation).EntitiesInError.Any()) { throw new InvalidOperationException(Resources.ApplicationServices_SaveErrors); } IPrincipal user = (IPrincipal)((SubmitOperation)result.InnerOperation).ChangeSet.OfType <IPrincipal>().SingleOrDefault(); this.PrepareUser(user); return(new SaveUserResult(user)); }
/// <summary> /// Handles completion of the underlying operation in the <see cref="DomainContext"/>. /// </summary> /// <param name="operation">The operation that completed</param> private void HandleOperationComplete(OperationBase operation) { WebAsyncResult result = ((WebAsyncResult)operation.UserState); // If the submic callback is executed before the BeginMethod has set InnerOparation // then do so here before calling Complete. // Since there is a race condition otherwise if (result.InnerOperation == null) { result.InnerOperation = operation; } if (operation.HasError) { operation.MarkErrorAsHandled(); } if (!operation.IsCanceled) { result.Complete(); } }
/// <summary> /// Begins an asynchronous <c>Login</c> operation. /// </summary> /// <param name="parameters">Login parameters that specify the user to authenticate</param> /// <param name="callback">The callback to invoke when the asynchronous call completes</param> /// <param name="state">The optional result state</param> /// <returns>An <see cref="IAsyncResult"/> that represents the asynchronous call</returns> /// <exception cref="InvalidOperationException"> is thrown if the /// <see cref="WebAuthenticationService.DomainContext"/> is <c>null</c> and a new instance /// cannot be created. /// </exception> protected override IAsyncResult BeginLogin(LoginParameters parameters, AsyncCallback callback, object state) { this.Initialize(); if (parameters == null) { throw new ArgumentNullException("parameters"); } WebAsyncResult result = new WebAsyncResult(callback, state); EntityQuery query; try { query = (EntityQuery)this.DomainContext.GetType().GetMethod( WebAuthenticationService.LoginQueryName, new Type[] { typeof(string), typeof(string), typeof(bool), typeof(string) }).Invoke( this.DomainContext, new object[] { parameters.UserName, parameters.Password, parameters.IsPersistent, parameters.CustomData }); } catch (TargetInvocationException tie) { if (tie.InnerException != null) { throw tie.InnerException; } throw; } result.InnerOperation = this.DomainContext.Load( query, LoadBehavior.MergeIntoCurrent, (Action <LoadOperation>) this.HandleOperationComplete, result); return(result); }
//请求开始时由ASP.NET调用此方法 public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) { context.Response.ContentType = "text/plain"; string code = AppRequest.GetQueryString("code", true); int flag = AppRequest.GetQueryInt("flag", 0); if (code.Length != 6) { context.Response.Write("fail"); } else { string key = code + "kw" + (flag > 0 ? flag.ToString() : ""); string hq = RedisHelper.GetValues(key); if (hq.Trim().Length < 32) { RedisHelper.Remove(key); StringBuilder sErrInfo = new StringBuilder(256); StringBuilder sResult = new StringBuilder(1024 * 1024); bool bRet = TradeX.TdxHq_Connect(AppKeys.QuotationAPI, 7709, sResult, sErrInfo); if (bRet == true) { DateTime dt = DateTime.Now; byte stock_market = 0; string cyb = Utils.subStr(code, 0, 1); if (flag == 0) { switch (cyb) { case "6": stock_market = 1; break; case "5": stock_market = 1; break; default: break; } } else { switch (cyb) { case "0": stock_market = 1; break; default: break; } } #region ====================查询接口数据 short nCount = 300; if (flag == 1) { bRet = TradeX.TdxHq_GetIndexBars(5, stock_market, code, 0, ref nCount, sResult, sErrInfo); } else { bRet = TradeX.TdxHq_GetSecurityBars(5, stock_market, code, 0, ref nCount, sResult, sErrInfo); } if (bRet == true) { string[] k_list = sResult.ToString().Replace("\n", "#").Replace("\t", ",").Replace("-", "").Split('#'); if (k_list.Length > 2) { for (int z = 1; z < k_list.Length; z++) { string[] k_split = k_list[z].Split(','); if (k_split.Length >= 7) { #region ====================更新redis,K线数据 //开盘价、收盘价、最高、最低、当前价、成交量、成交额 decimal open = Utils.StrToDecimal(k_split[1], 0), preClose = Utils.StrToDecimal(k_split[2], 0), highest = Utils.StrToDecimal(k_split[3], 0), lowest = Utils.StrToDecimal(k_split[4], 0), fprice = Utils.StrToDecimal(k_split[2], 0), deal_num = Utils.StrToDecimal(k_split[5], 0), deal_price = Utils.StrToDecimal(k_split[6], 0); //redis-Key值、行情时间、旧数据 string old_str = RedisHelper.GetValues(key), time_hhmm = k_split[0]; int time_hhmm_int = Utils.StrToInt(time_hhmm, 0); //时间数字化 if (old_str.Trim().Length < 32) //第一次插入 { #region ====================初始数据 Model.StockKLine modelk = new Model.StockKLine(); Model.kmins minsk = new Model.kmins() { time = time_hhmm_int, preClose = preClose, open = open, highest = highest, lowest = lowest, price = fprice, volume = deal_num, amount = deal_price }; modelk.kmins.Add(minsk); string json_kline = JsonHelper.GetJson <Model.StockKLine>(modelk); RedisHelper.Set <string>(key, json_kline); #endregion ; } else { #region ====================更新数据 Model.StockKLine modelk = JsonHelper.ParseFromJson <Model.StockKLine>(old_str); bool is_has = modelk.kmins.Any(p => p.time == time_hhmm_int); if (is_has == true) { modelk.kmins.Remove(modelk.kmins.Where(p => p.time == time_hhmm_int).Single()); } Model.kmins minsk = new Model.kmins() { time = time_hhmm_int, preClose = preClose, open = open, highest = highest, lowest = lowest, price = fprice, volume = deal_num, amount = deal_price }; modelk.kmins.Add(minsk); string json_kline = JsonHelper.GetJson <Model.StockKLine>(modelk); RedisHelper.Set <string>(key, json_kline); #endregion } #endregion } } } } #endregion } } context.Response.Write(RedisHelper.GetValues(key)); } //构建异步结果并返回 var result = new WebAsyncResult(cb, context); result.SetComplete(); return(result); }
//异步结束时,由ASP.NET调用此方法 public void EndProcessRequest(IAsyncResult result) { WebAsyncResult webresult = (WebAsyncResult)result; }
/// <summary> /// Begins an asynchronous <c>SaveUser</c> operation. /// </summary> /// <param name="user">The authenticated user to save</param> /// <param name="callback">The callback to invoke when the asynchronous call completes</param> /// <param name="state">The optional result state</param> /// <returns>An <see cref="IAsyncResult"/> that represents the asynchronous call</returns> /// <exception cref="InvalidOperationException"> is thrown if the user is anonymous.</exception> /// <exception cref="InvalidOperationException"> is thrown if the /// <see cref="WebAuthenticationService.DomainContext"/> is <c>null</c> and a new instance /// cannot be created. /// </exception> protected override IAsyncResult BeginSaveUser(IPrincipal user, AsyncCallback callback, object state) { this.Initialize(); if (!user.Identity.IsAuthenticated) { throw new InvalidOperationException(Resources.ApplicationServices_CannotSaveAnonymous); } WebAsyncResult result = new WebAsyncResult(callback, state); result.InnerOperation = this.DomainContext.SubmitChanges( (Action<SubmitOperation>)this.HandleOperationComplete, result); return result; }
/// <summary> /// Begins an asynchronous <c>LoadUser</c> operation. /// </summary> /// <param name="callback">The callback to invoke when the asynchronous call completes</param> /// <param name="state">The optional result state</param> /// <returns>An <see cref="IAsyncResult"/> that represents the asynchronous call</returns> /// <exception cref="InvalidOperationException"> is thrown if the /// <see cref="WebAuthenticationService.DomainContext"/> is <c>null</c> and a new instance /// cannot be created. /// </exception> protected override IAsyncResult BeginLoadUser(AsyncCallback callback, object state) { this.Initialize(); WebAsyncResult result = new WebAsyncResult(callback, state); EntityQuery query; try { query = (EntityQuery)this.DomainContext.GetType().GetMethod( WebAuthenticationService.LoadUserQueryName, Type.EmptyTypes).Invoke( this.DomainContext, Type.EmptyTypes); } catch (TargetInvocationException tie) { if (tie.InnerException != null) { throw tie.InnerException; } throw; } result.InnerOperation = this.DomainContext.Load( query, LoadBehavior.MergeIntoCurrent, (Action<LoadOperation>)this.HandleOperationComplete, result); return result; }
/// <summary> /// Begins an asynchronous <c>Login</c> operation. /// </summary> /// <param name="parameters">Login parameters that specify the user to authenticate</param> /// <param name="callback">The callback to invoke when the asynchronous call completes</param> /// <param name="state">The optional result state</param> /// <returns>An <see cref="IAsyncResult"/> that represents the asynchronous call</returns> /// <exception cref="InvalidOperationException"> is thrown if the /// <see cref="WebAuthenticationService.DomainContext"/> is <c>null</c> and a new instance /// cannot be created. /// </exception> protected override IAsyncResult BeginLogin(LoginParameters parameters, AsyncCallback callback, object state) { this.Initialize(); if (parameters == null) { throw new ArgumentNullException("parameters"); } WebAsyncResult result = new WebAsyncResult(callback, state); EntityQuery query; try { query = (EntityQuery)this.DomainContext.GetType().GetMethod( WebAuthenticationService.LoginQueryName, new Type[] { typeof(string), typeof(string), typeof(bool), typeof(string) }).Invoke( this.DomainContext, new object[] { parameters.UserName, parameters.Password, parameters.IsPersistent, parameters.CustomData }); } catch (TargetInvocationException tie) { if (tie.InnerException != null) { throw tie.InnerException; } throw; } result.InnerOperation = this.DomainContext.Load( query, LoadBehavior.MergeIntoCurrent, (Action<LoadOperation>)this.HandleOperationComplete, result); return result; }
public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback cb, object state) { if (disposed) { throw new WebException("stream is closed", WebExceptionStatus.ConnectionClosed); } if (!isRead) { throw new NotSupportedException("this stream does not allow reading"); } if (buffer == null) { throw new ArgumentNullException("buffer"); } int length = buffer.Length; if (offset < 0 || length < offset) { throw new ArgumentOutOfRangeException("offset"); } if (size < 0 || (length - offset) < size) { throw new ArgumentOutOfRangeException("size"); } lock (locker) { pendingReads++; pending.Reset(); } WebAsyncResult result = new WebAsyncResult(cb, state, buffer, offset, size); if (totalRead >= contentLength) { result.SetCompleted(true, -1); result.DoCallback(); return(result); } int remaining = readBufferSize - readBufferOffset; if (remaining > 0) { int copy = (remaining > size) ? size : remaining; Buffer.BlockCopy(readBuffer, readBufferOffset, buffer, offset, copy); readBufferOffset += copy; offset += copy; size -= copy; totalRead += copy; if (size == 0 || totalRead >= contentLength) { result.SetCompleted(true, copy); result.DoCallback(); return(result); } result.NBytes = copy; } if (cb != null) { cb = cb_wrapper; } if (contentLength != Int32.MaxValue && contentLength - totalRead < size) { size = contentLength - totalRead; } if (!read_eof) { result.InnerAsyncResult = cnc.BeginRead(request, buffer, offset, size, cb, result); } else { result.SetCompleted(true, result.NBytes); result.DoCallback(); } return(result); }
public override int EndRead(IAsyncResult r) { WebAsyncResult result = (WebAsyncResult)r; if (result.EndCalled) { int xx = result.NBytes; return((xx >= 0) ? xx : 0); } result.EndCalled = true; if (!result.IsCompleted) { int nbytes = -1; try { nbytes = cnc.EndRead(request, result); } catch (Exception exc) { lock (locker) { pendingReads--; if (pendingReads == 0) { pending.Set(); } } nextReadCalled = true; cnc.Close(true); result.SetCompleted(false, exc); result.DoCallback(); throw; } if (nbytes < 0) { nbytes = 0; read_eof = true; } totalRead += nbytes; result.SetCompleted(false, nbytes + result.NBytes); result.DoCallback(); if (nbytes == 0) { contentLength = totalRead; } } lock (locker) { pendingReads--; if (pendingReads == 0) { pending.Set(); } } if (totalRead >= contentLength && !nextReadCalled) { ReadAll(); } int nb = result.NBytes; return((nb >= 0) ? nb : 0); }
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback cb, object state) { if (request.Aborted) { throw new WebException("The request was canceled.", null, WebExceptionStatus.RequestCanceled); } if (disposed) { throw new WebException("stream is closed", WebExceptionStatus.ConnectionClosed); } if (isRead) { throw new NotSupportedException("this stream does not allow writing"); } if (buffer == null) { throw new ArgumentNullException("buffer"); } int length = buffer.Length; if (offset < 0 || length < offset) { throw new ArgumentOutOfRangeException("offset"); } if (size < 0 || (length - offset) < size) { throw new ArgumentOutOfRangeException("size"); } if (sendChunked) { lock (locker) { pendingWrites++; pending.Reset(); } } WebAsyncResult result = new WebAsyncResult(cb, state); AsyncCallback callback = new AsyncCallback(WriteAsyncCB); if (sendChunked) { requestWritten = true; string cSize = String.Format("{0:X}\r\n", size); byte[] head = Encoding.ASCII.GetBytes(cSize); int chunkSize = 2 + size + head.Length; byte[] newBuffer = new byte[chunkSize]; Buffer.BlockCopy(head, 0, newBuffer, 0, head.Length); Buffer.BlockCopy(buffer, offset, newBuffer, head.Length, size); Buffer.BlockCopy(crlf, 0, newBuffer, head.Length + size, crlf.Length); if (allowBuffering) { if (writeBuffer == null) { writeBuffer = new MemoryStream(); } writeBuffer.Write(buffer, offset, size); totalWritten += size; } buffer = newBuffer; offset = 0; size = chunkSize; } else { CheckWriteOverflow(request.ContentLength, totalWritten, size); if (allowBuffering) { if (writeBuffer == null) { writeBuffer = new MemoryStream(); } writeBuffer.Write(buffer, offset, size); totalWritten += size; if (request.ContentLength <= 0 || totalWritten < request.ContentLength) { result.SetCompleted(true, 0); result.DoCallback(); return(result); } result.AsyncWriteAll = true; requestWritten = true; buffer = writeBuffer.GetBuffer(); offset = 0; size = (int)totalWritten; } } try { result.InnerAsyncResult = cnc.BeginWrite(request, buffer, offset, size, callback, result); if (result.InnerAsyncResult == null) { if (!result.IsCompleted) { result.SetCompleted(true, 0); } result.DoCallback(); } } catch (Exception) { if (!IgnoreIOErrors) { throw; } result.SetCompleted(true, 0); result.DoCallback(); } totalWritten += size; return(result); }
//请求开始时由ASP.NET调用此方法 public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) { context.Response.ContentType = "text/plain"; string code = AppRequest.GetQueryString("code", true); int flag = AppRequest.GetQueryInt("flag", 0); if (flag == 100) { #region 使用自身行情 string keys_bak = code + "t_bak"; context.Response.Write(RedisHelper.GetValues(keys_bak)); #endregion } else { #region 使用接口行情 if (code.Length != 6) { context.Response.Write("fail"); } else { string key = code + "t" + (flag > 0 ? flag.ToString() : ""); string hq = RedisHelper.GetValues(key); int count = 0; DateTime dt = DateTime.Now; int time_hhmm = Utils.StrToInt(dt.ToString("HHmm"), 0);//行情时间; if (hq.Length > 32) { Model.StockTLine modelt = JsonHelper.ParseFromJson <Model.StockTLine>(hq); count = modelt.mins.Count; if (count > 0) { //检查交易时间是否已经有数据 if (((time_hhmm > 930 && time_hhmm < 1130) || (time_hhmm > 1300 && time_hhmm < 1500))) { int countCk = modelt.mins.Where(t => t.time == time_hhmm.ToString()).Count(); if (countCk > 0) { count = 240; } else { count = 0; } } } } if (count < 240 || count > 245) { StringBuilder sErrInfo = new StringBuilder(256); StringBuilder sResult = new StringBuilder(1024 * 1024); bool bRet = TradeX.TdxHq_Connect(AppKeys.QuotationAPI, 7709, sResult, sErrInfo); //Log.WriteLog("行情", sResult.ToString() + "++++" + sErrInfo.ToString()); if (bRet == true) { string stock_code_s = Utils.GetFullStockCode(code, flag); if (time_hhmm >= 1500) { dt = Utils.StrToDateTime(DateTime.Now.ToString("yyyy-MM-dd 15:00:00")); } byte stock_market = 0; string cyb = Utils.subStr(code, 0, 1); if (flag == 0) { switch (cyb) { case "6": stock_market = 1; break; case "5": stock_market = 1; break; default: break; } } else { switch (cyb) { case "0": stock_market = 1; break; case "5": stock_market = 1; break; default: break; } } //股票最新行情 string[] stock_info = RedisHelper.GetValues(stock_code_s).Split(','); if (stock_info.Length < 30) { stock_info = Utils.GetStockData(code, 0, 0).Split(','); } bool bRet2 = TradeX.TdxHq_GetMinuteTimeData(stock_market, code, sResult, sErrInfo); if (bRet2 == true && stock_info.Length > 30) { string[] hq_time = AppKeys.CACHE_HQ_TIME.ToString().Split(','); string[] k_list = sResult.ToString().Replace("\n", "#").Replace("\t", ",").Replace("-", "").Split('#'); if (k_list.Length > 2 && hq_time.Length >= 240) { int lgt = k_list.Length, lgt_ck = hq_time.Length; if (lgt > lgt_ck) { lgt = lgt_ck; } for (int z = 1; z < lgt; z++) { string[] k_split = k_list[z].Split(','); if (k_split.Length >= 2) { //现价,成交量,保留 decimal price_now = Utils.StrToDecimal(k_split[0], 0), price_num = Utils.StrToDecimal(k_split[1], 0), price_keep = Utils.StrToDecimal(k_split[2], 0); //开盘价、收盘价、最高、最低、当前价、成交量、成交额 decimal open = Utils.StrToDecimal(stock_info[1], 0), preClose = Utils.StrToDecimal(stock_info[2], 0), highest = Utils.StrToDecimal(stock_info[4], 0), lowest = Utils.StrToDecimal(stock_info[5], 0), fprice = Utils.StrToDecimal(stock_info[3], 0), deal_num = Utils.StrToDecimal(stock_info[8], 0), deal_price = Utils.StrToDecimal(stock_info[9], 0); #region ====================行情数据 if (z == 1) { #region ====================初始数据 Model.StockTLine modelt = new Model.StockTLine() { quote = new Model.quote() { stock_name = stock_info[0], time = dt.ToString("yyyyMMddHHmmss"), open = open, preClose = preClose, highest = highest, lowest = lowest, price = fprice, volume = deal_num, amount = deal_price } }; Model.mins mins = new Model.mins() { price = price_now, volume = price_num, amount = 0, time = hq_time[z - 1] }; modelt.mins.Add(mins); string json_first = JsonHelper.GetJson <Model.StockTLine>(modelt); RedisHelper.Set <string>(key, json_first); #endregion } else { #region ====================更新数据 string old_str = RedisHelper.GetValues(key);//旧分时数据 if (!string.IsNullOrEmpty(old_str)) { Model.StockTLine modelt = JsonHelper.ParseFromJson <Model.StockTLine>(old_str); Model.quote quote = new Model.quote() { stock_name = stock_info[0], time = dt.ToString("yyyyMMddHHmmss"), open = open, preClose = preClose, highest = highest, lowest = lowest, price = fprice, volume = deal_num, amount = deal_price }; Model.mins mins = new Model.mins() { price = price_now, volume = price_num, amount = 0, time = hq_time[z - 1] }; modelt.quote = quote; modelt.mins.Add(mins); string json_first = JsonHelper.GetJson <Model.StockTLine>(modelt); RedisHelper.Set <string>(key, json_first); } #endregion } #endregion } } } //断开连接 //TradeX.TdxHq_Disconnect(); } } hq = RedisHelper.GetValues(key); } else { hq = RedisHelper.GetValues(key); } context.Response.Write(hq); } #endregion } //构建异步结果并返回 var result = new WebAsyncResult(cb, context); result.SetComplete(); return(result); }
//请求开始时由ASP.NET调用此方法 public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) { context.Response.ContentType = "text/plain"; string code = AppRequest.GetQueryString("code"); if (code.Length < 6) { context.Response.Write("fail"); } else { StringBuilder sErrInfo = new StringBuilder(256); StringBuilder sResult = new StringBuilder(1024 * 1024); byte[] market = null; List <byte> market_list = new List <byte>(); string[] code_list = code.Split(','); short count = (short)code_list.Length; if (count > 50 || count < 1) { context.Response.Write("The array limit 1 to 50"); } else { for (int i = 0; i < count; i++) { if (Utils.subStr(code_list[i], 0, 1) == "6") { market_list.Add(1); } else { market_list.Add(0); } } market = market_list.ToArray(); string connid = RedisHelper.GetValues("connid"); if (connid == "-1" || connid == "") { connid = TradeX.TdxL2Hq_Connect("183.3.223.36", 7709, "srx1314520", "qaz852147wsx", sResult, sErrInfo).ToString(); if (sErrInfo.ToString().Contains("行情连接已满")) { connid = "0"; } RedisHelper.Set <string>("connid", connid, DateTime.Now.AddSeconds(30)); } bool isRet3 = TradeX.TdxL2Hq_GetSecurityQuotes10(market, code_list, ref count, sResult, sErrInfo); if (isRet3 == true) { context.Response.Write(sResult); } else { if (sErrInfo.ToString().Contains("发送数据失败") || sErrInfo.ToString().Contains("无效行情连接")) { TradeX.TdxL2Hq_Disconnect(); context.Response.Write(ConnHq(market, code_list, count)); } else { context.Response.Write(sErrInfo); } } } } //构建异步结果并返回 var result = new WebAsyncResult(cb, context); result.SetComplete(); return(result); }