// TODO -- let's thin this down from CurrentRequest public void AddReport(IDebugReport report, CurrentRequest request) { if(_filters.Any(f => f.Exclude(request))) { return; } _reports.Enqueue(report); while (_reports.Count > _configuration.MaxRequests) { _reports.Dequeue(); } }
private static String processPageIndex(String apath, Route x) { String[] arrP = apath.Split(separator[0]); String lastItem = arrP[arrP.Length - 1]; if (isPageNumber(lastItem)) { int pageIndex = cvt.ToInt(lastItem.TrimStart('p')); x.setPage(pageIndex); CurrentRequest.setCurrentPage(pageIndex); apath = strUtil.TrimEnd(apath, lastItem).TrimEnd(separator[0]); } return(apath); }
public static DataPage <T> GetPage(List <T> list, int pageSize) { ObjectPage op = new ObjectPage(); if (pageSize <= 0) { pageSize = 20; } op.setSize(pageSize); op.RecordCount = list.Count; // 计算页数 op.computePageCount(); // 矫正当前页码 int currentPageNumber = CurrentRequest.getCurrentPage(); op.setCurrent(currentPageNumber); op.resetCurrent(); currentPageNumber = op.getCurrent(); // 得到结果集 List <T> results = new List <T>(); int start = (currentPageNumber - 1) * pageSize; int count = 1; for (int i = start; i < list.Count; i++) { if (count > pageSize) { break; } results.Add(list[i]); count++; } // 填充分页数据 DataPage <T> page = new DataPage <T>(); page.Results = results; page.Current = currentPageNumber; page.Size = pageSize; page.RecordCount = list.Count; page.PageCount = op.PageCount; page.PageBar = op.PageBar; return(page); }
internal static IDictionary getContextCache() { Object dic = null; try { dic = CurrentRequest.getItem(_contextCacheKey); } catch { } if (dic == null) { dic = new Hashtable(); CurrentRequest.setItem(_contextCacheKey, dic); } return(dic as IDictionary); }
private static IEntity getNullUser(long realUserId) { IUserFactory userFactory = CurrentRequest.getItem("_user_factory") as IUserFactory; if (userFactory == null) { return(null); } IEntity user = userFactory.NullUser() as IEntity; if (user != null) { user.set("RealId", realUserId); } return(user); }
/// <summary> /// 将日志写入磁盘 /// </summary> /// <param name="msg"></param> public static void WriteFile(ILogMsg msg) { if (!SystemInfo.IsWeb || LogConfig.Instance.InRealTime) { writeFilePrivate(msg); return; } StringBuilder sb = CurrentRequest.getItem("currentLogList") as StringBuilder; if (sb == null) { sb = new StringBuilder(); CurrentRequest.setItem("currentLogList", sb); } sb.AppendFormat("{0} {1} {2} - {3} \r\n", msg.LogTime, msg.LogLevel, msg.TypeName, msg.Message); }
internal void HandleCallback() { HandleProgressCallback(); if (State == HTTPConnectionStates.Upgraded) { if (CurrentRequest != null && CurrentRequest.Response != null && CurrentRequest.Response.IsUpgraded) { CurrentRequest.UpgradeCallback(); } State = HTTPConnectionStates.WaitForProtocolShutdown; } else { CurrentRequest.CallCallback(); } }
private static void setStrongTypeValue(Route result) { if (result.getItem("controller") != null) { result.setController(result.getItem("controller")); } if (result.getItem("action") != null) { result.setAction(result.getItem("action")); } if (result.getItem("query") != null) { result.setQuery(result.getItem("query")); } if (result.getItem("owner") != null) { result.setOwner(result.getItem("owner")); } if (result.getItem("ownertype") != null) { result.setOwnerType(result.getItem("ownertype")); } if (result.getItem("id") != null) { result.setId(cvt.ToLong(result.getItem("id"))); } if (result.getItem("appid") != null) { result.setAppId(cvt.ToLong(result.getItem("appid"))); } int page = 1; if (result.getItem("page") != null) { int routePage = Requirements.getPageNumber(result.getItem("page")); if (routePage > 1) { page = routePage; } } result.setItem("page", page); result.setPage(page); CurrentRequest.setCurrentPage(page); }
public QueryParserBenchmarks() { IJsonApiOptions options = new JsonApiOptions { EnableLegacyFilterNotation = true }; IResourceGraph resourceGraph = DependencyFactory.CreateResourceGraph(options); var currentRequest = new CurrentRequest { PrimaryResource = resourceGraph.GetResourceContext(typeof(BenchmarkResource)) }; _queryStringReaderForSort = CreateQueryParameterDiscoveryForSort(resourceGraph, currentRequest, options, _queryStringAccessor); _queryStringReaderForAll = CreateQueryParameterDiscoveryForAll(resourceGraph, currentRequest, options, _queryStringAccessor); }
public void should_exclude_diagnostics_requests() { IRequestHistoryCacheFilter filter = null; _registry .Services(x => { filter = x.FindAllValues <IRequestHistoryCacheFilter>().First(); }); _registry.BuildGraph(); var request = new CurrentRequest { Path = "/{0}/requests".ToFormat(DiagnosticUrlPolicy.DIAGNOSTICS_URL_ROOT) }; filter.Exclude(request).ShouldBeTrue(); }
/// <summary> /// 将日志写入磁盘 /// </summary> /// <param name="msg"></param> public static void WriteFile(ILogMsg msg) { if (SystemInfo.IsWeb == false) { writeFilePrivate(msg); return; } StringBuilder sb = CurrentRequest.getItem(_contextLogItem) as StringBuilder; if (sb == null) { sb = new StringBuilder(); CurrentRequest.setItem(_contextLogItem, sb); } sb.AppendFormat("{0} {1} {2} - {3} \r\n", msg.LogTime, msg.LogLevel, msg.TypeName, msg.Message); }
public void ChangeRequest(object selectedObject) { CurrentRequest = selectedObject as RequestNode; if (!CurrentRequest.ReEvaluate(Id)) { if (CurrentRequest.Response != null && CurrentRequest.Response != string.Empty) { RequestString = CurrentRequest.Request.ToString(); Response = CurrentRequest.Response; HttpStatusCode = "Retrieved From Cache"; return; } } RequestString = CurrentRequest.Request.ToString(); Response = "Waitin for a reply from the server..."; HttpStatusCode = ""; Connection.MakeRequest(Dispatcher, CurrentRequest.Request); }
public void findPage() { int pageSize = 5; //------------- 第1页 --------------- int current = 1; CurrentRequest.setCurrentPage(current); DataPage <TBoard> list = TBoard.findPage("Id>0", pageSize); Assert.AreEqual(current, list.Current); Assert.AreEqual(12, list.RecordCount); Assert.AreEqual(3, list.PageCount); Assert.AreEqual(pageSize, list.Size); Assert.AreEqual(pageSize, list.Results.Count); //------------- 第2页 --------------- current = 2; CurrentRequest.setCurrentPage(current); list = TBoard.findPage("Id>0", pageSize); Assert.AreEqual(current, list.Current); Assert.AreEqual(12, list.RecordCount); Assert.AreEqual(3, list.PageCount); Assert.AreEqual(pageSize, list.Size); Assert.AreEqual(pageSize, list.Results.Count); //------------- 第3页 --------------- current = 3; CurrentRequest.setCurrentPage(current); list = TBoard.findPage("Id>0", pageSize); Assert.AreEqual(current, list.Current); Assert.AreEqual(12, list.RecordCount); Assert.AreEqual(3, list.PageCount); Assert.AreEqual(pageSize, list.Size); Assert.AreEqual(2, list.Results.Count); }
private static QueryStringReader CreateQueryParameterDiscoveryForAll(IResourceGraph resourceGraph, CurrentRequest currentRequest, IJsonApiOptions options, FakeRequestQueryStringAccessor queryStringAccessor) { var resourceFactory = new ResourceFactory(new ServiceContainer()); var filterReader = new FilterQueryStringParameterReader(currentRequest, resourceGraph, resourceFactory, options); var sortReader = new SortQueryStringParameterReader(currentRequest, resourceGraph); var sparseFieldSetReader = new SparseFieldSetQueryStringParameterReader(currentRequest, resourceGraph); var paginationReader = new PaginationQueryStringParameterReader(currentRequest, resourceGraph, options); var defaultsReader = new DefaultsQueryStringParameterReader(options); var nullsReader = new NullsQueryStringParameterReader(options); var readers = new List <IQueryStringParameterReader> { filterReader, sortReader, sparseFieldSetReader, paginationReader, defaultsReader, nullsReader }; return(new QueryStringReader(options, queryStringAccessor, readers, NullLoggerFactory.Instance)); }
public void TestRemoteProtocol() { var protocol = new Protocol(); var request = new CurrentRequest() { Request = new Request(Encoding.UTF8, "test"), Id = 636 }; ((Request)request.Request).Writer.Write("abc"); var bytes = protocol.FromRequest(request); var request2 = protocol.ToRequest(new Never.Sockets.AsyncArgs.OnReceivedSocketEventArgs(null, bytes) { }); var abc = Encoding.UTF8.GetString((((Request)request2.Request).Body as MemoryStream).ToArray()); var response1 = protocol.ToResponse(new Never.Sockets.AsyncArgs.OnReceivedSocketEventArgs(null, bytes) { }); abc = Encoding.UTF8.GetString((((Response)response1.Response).Body as MemoryStream).ToArray()); var response = new CurrentResponse() { Response = new Response(Encoding.UTF8, "test"), Id = 636, }; var handlerresponse = new ResponseResult() { Query = new System.Collections.Specialized.NameValueCollection(), }; handlerresponse.Query.Add("abc", "efg"); handlerresponse.Body = new MemoryStream(Encoding.UTF8.GetBytes("abc")); bytes = protocol.FromResponse(request, handlerresponse); var response2 = protocol.ToResponse(new Never.Sockets.AsyncArgs.OnReceivedSocketEventArgs(null, bytes) { }); abc = Encoding.UTF8.GetString((((Response)response2.Response).Body as MemoryStream).ToArray()); }
protected void btnSubmitAnswer_Click(object sender, EventArgs e) { Page.Validate("vgAnswer"); if (Page.IsValid) { try { string szUser = CurrentRequest.UserName; TempPassword = Membership.GetUser(szUser).ResetPassword(txtAnswer.Text); mvResetPass.SetActiveView(vwNewPass); } catch (MembershipPasswordException ex) { CurrentRequest.Status = PasswordResetRequest.RequestStatus.Failed; CurrentRequest.FCommit(); lblErr.Text = ex.Message; } } }
private static QueryParameterDiscovery CreateQueryParameterDiscoveryForAll(IResourceGraph resourceGraph, CurrentRequest currentRequest, IResourceDefinitionProvider resourceDefinitionProvider, IJsonApiOptions options) { IIncludeService includeService = new IncludeService(resourceGraph, currentRequest); IFilterService filterService = new FilterService(resourceDefinitionProvider, resourceGraph, currentRequest); ISortService sortService = new SortService(resourceDefinitionProvider, resourceGraph, currentRequest); ISparseFieldsService sparseFieldsService = new SparseFieldsService(resourceGraph, currentRequest); IPageService pageService = new PageService(options, resourceGraph, currentRequest); IOmitDefaultService omitDefaultService = new OmitDefaultService(options); IOmitNullService omitNullService = new OmitNullService(options); var queryServices = new List <IQueryParameterService> { includeService, filterService, sortService, sparseFieldsService, pageService, omitDefaultService, omitNullService }; return(new QueryParameterDiscovery(options, queryServices)); }
private static void setConnection(String key, IDbConnection cn) { Dictionary <String, IDbConnection> dic; dic = CurrentRequest.getItem(_connectionKey) as Dictionary <String, IDbConnection>; if (dic == null) { dic = new Dictionary <String, IDbConnection>(); } if (dic.ContainsKey(key)) { dic[key] = cn; } else { dic.Add(key, cn); } CurrentRequest.setItem(_connectionKey, dic); }
private static void setTransaction(String key, IDbTransaction trans) { Dictionary <String, IDbTransaction> dic; dic = CurrentRequest.getItem(_transactionKey) as Dictionary <String, IDbTransaction>; if (dic == null) { dic = new Dictionary <String, IDbTransaction>(); } if (dic.ContainsKey(key)) { dic[key] = trans; } else { dic.Add(key, trans); } CurrentRequest.setItem(_transactionKey, dic); }
private static QueryParameterParser CreateQueryParameterDiscoveryForAll(IResourceGraph resourceGraph, CurrentRequest currentRequest, IResourceDefinitionProvider resourceDefinitionProvider, IJsonApiOptions options, FakeRequestQueryStringAccessor queryStringAccessor) { IIncludeService includeService = new IncludeService(resourceGraph, currentRequest); IFilterService filterService = new FilterService(resourceDefinitionProvider, resourceGraph, currentRequest); ISortService sortService = new SortService(resourceDefinitionProvider, resourceGraph, currentRequest); ISparseFieldsService sparseFieldsService = new SparseFieldsService(resourceGraph, currentRequest); IPageService pageService = new PageService(options, resourceGraph, currentRequest); IDefaultsService defaultsService = new DefaultsService(options); INullsService nullsService = new NullsService(options); var queryServices = new List <IQueryParameterService> { includeService, filterService, sortService, sparseFieldsService, pageService, defaultsService, nullsService }; return(new QueryParameterParser(options, queryStringAccessor, queryServices, NullLoggerFactory.Instance)); }
private JsonApiResourceService <TodoItem> GetService() { var options = new JsonApiOptions(); var changeTracker = new ResourceChangeTracker <TodoItem>(options, _resourceGraph, new TargetedFields()); var serviceProvider = new ServiceContainer(); var resourceFactory = new ResourceFactory(serviceProvider); var resourceDefinitionProvider = new ResourceDefinitionProvider(_resourceGraph, new TestScopedServiceProvider(serviceProvider)); var paginationContext = new PaginationContext(); var composer = new QueryLayerComposer(new List <IQueryConstraintProvider>(), _resourceGraph, resourceDefinitionProvider, options, paginationContext); var currentRequest = new CurrentRequest { PrimaryResource = _resourceGraph.GetResourceContext <TodoItem>(), SecondaryResource = _resourceGraph.GetResourceContext <TodoItemCollection>(), Relationship = _resourceGraph.GetRelationships(typeof(TodoItem)) .Single(x => x.PublicName == "collection") }; return(new JsonApiResourceService <TodoItem>(_repositoryMock.Object, composer, paginationContext, options, NullLoggerFactory.Instance, currentRequest, changeTracker, resourceFactory, null)); }
protected ParseTestsBase() { Options = new JsonApiOptions(); ResourceGraph = new ResourceGraphBuilder(Options, NullLoggerFactory.Instance) .AddResource <Blog>() .AddResource <Article>() .AddResource <Author>() .AddResource <Address>() .AddResource <Country>() .AddResource <Revision>() .AddResource <Tag>() .Build(); CurrentRequest = new CurrentRequest { PrimaryResource = ResourceGraph.GetResourceContext <Blog>(), IsCollection = true }; }
public static string PrepareJson(List<Comanda.Ordine> ordini, string tipo, string returnurl, string cancelurl) { CurrentRequest Request = new CurrentRequest(); float Totale = 0f; ItemList item_list = new ItemList(); item_list.items = new List<item>(); //currentitem = null; foreach(Comanda.Ordine o in ordini) { item currentitem = new item(); currentitem.name = o.Nome; currentitem.quantity = o.Quantità.ToString(); currentitem.description = ""; currentitem.price = o.PrezzoBase.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture); currentitem.currency = "EUR"; //item_list.items.Capacity = item_list.items.Capacity + 1; item_list.items.Add(currentitem); Totale += o.Prezzo; } Transaction transaction = new Transaction(); transaction.amount = new Amount { total = Totale.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture), currency = "EUR" }; transaction.item_list = item_list; transaction.description = tipo; transaction.invoice_number = ""; Request.intent = "sale"; Request.redirect_urls = new RedirectUrls { return_url = returnurl, cancel_url = cancelurl }; Request.payer = new Payer { payment_method = "paypal" }; Request.transactions = new List<Transaction>(); Request.transactions.Add(transaction); InputFields inputfields = new InputFields {no_shipping = 1, address_override = 1 }; Experience exp = new Experience (); exp.input_fields = inputfields; Request.experience = exp; string json = JsonConvert.SerializeObject(Request); File.WriteAllText(Path.Combine(Application.persistentDataPath, "PaymentRequest.json"), json); return json; // File.WriteAllText(Path.Combine(Application.persistentDataPath, "PaymentRequest.json"), json); // print(Application.persistentDataPath); }
protected void RecycleNow() { if (State == HTTPConnectionStates.TimedOut || State == HTTPConnectionStates.Closed) { LastProcessTime = DateTime.MinValue; } State = HTTPConnectionStates.Free; if (CurrentRequest != null) { CurrentRequest.Dispose(); } CurrentRequest = null; if (OnConnectionRecycled != null) { OnConnectionRecycled(this); OnConnectionRecycled = null; } }
//-------------------------------- viewer ---------------------------------- public void InitViewer(MvcContext ctx) { ctx.setCacheCondition(new CacheCondition()); CurrentRequest.setItem("_user_factory", new UserFactory()); User user = this.getViewer(ctx); if (user.Id == UserFactory.Guest.Id && ctx.web.UserIsLogin) { signOut(ctx); return; } else if (user.Status == MemberStatus.Deleted || user.Status == MemberStatus.Approving) { signOut(ctx); return; } if (ctx.web.UserIsLogin) { loginService.UpdateLastLogin(user, ctx.Ip); } ViewerContext context = new ViewerContext(); context.Id = user.Id; context.obj = user; context.IsLogin = ctx.web.UserIsLogin; ctx.utils.setViewerContext(context); // 编辑器 if (context.IsLogin) { Link lnk = new Link(ctx); ctx.SetItem("editorUploadUrl", lnk.To(user, "Users/Admin/UserUpload", "UploadForm", -1, -1)); ctx.SetItem("editorMyPicsUrl", lnk.To(user, "Users/Admin/UserUpload", "MyPics", -1, -1)); } }
internal void HandleCallback() { try { HandleProgressCallback(); if (State == HTTPConnectionStates.Upgraded) { if (CurrentRequest != null && CurrentRequest.Response != null && CurrentRequest.Response.IsUpgraded) { CurrentRequest.UpgradeCallback(); } State = HTTPConnectionStates.WaitForProtocolShutdown; } else { CurrentRequest.CallCallback(); } } catch (Exception ex) { HTTPManager.Logger.Exception("ConnectionBase", "HandleCallback", ex); } }
public void Like() { setWaterfallView(); String userUrl = ctx.route.getItem("user"); User u = userService.GetByUrl(userUrl); if (u == null) { echoRedirect("用户不存在"); return; } DataPage <PhotoPost> list = likeService.GetByUser(u.Id, 12); // 2) 或者超过实际页数,也不再自动翻页 if (CurrentRequest.getCurrentPage() > list.PageCount && list.PageCount > 0) { echoText("."); return; } PhotoBinder.BindPhotoList(this, list, ctx.viewer.Id); }
/// <summary> /// 获取当前语言字符(比如 zh-cn,或 en-us) /// </summary> /// <returns></returns> public static String getLangString() { String defaultLang = "zh-cn"; String langCookie = CurrentRequest.getLangCookie(); if (strUtil.HasText(langCookie) && langLocaleAll.ContainsKey(langCookie)) { return(langCookie); } if (CurrentRequest.getUserLanguages() == null) { return(defaultLang); } String[] reqLangs = CurrentRequest.getUserLanguages(); if (reqLangs.Length == 0) { return(defaultLang); } if (langLocaleAll.ContainsKey(reqLangs[0])) { return(reqLangs[0]); } return(defaultLang); }
public async Task <ActionResult <BaseParameters> > Master([FromServices] ModuleManager moduleManager, [FromServices] ResetSiteCacheCommand resetSiteCacheCommand, [FromServices] IRouteManager routeManager, [FromServices] IOptions <ApplicationConfig> options, [FromQuery] string url, [FromQuery] string port = "") { var fullRequestUrl = HttpUtility.UrlDecode(url); var fullUrl = fullRequestUrl.Split('?')[0]; if (fullUrl.Contains(":")) { fullUrl = fullUrl.Replace($":{port}", ""); } var parameters = new BaseParameters(); var simpleUrl = fullUrl.Replace("https://", "").Replace("http://", ""); var findRouteInput = new FindRouteInput(); findRouteInput.Url = simpleUrl; findRouteInput.FullUrl = fullRequestUrl; findRouteInput.IsSecure = true; findRouteInput.Port = Request.Host.Port.ToString(); var findRouteResult = await routeManager.FindRouteAsync(findRouteInput); if (!findRouteResult.IsSuccess) { return(NotFound()); } var currentRequest = new CurrentRequest(); var siteId = findRouteResult.SiteId; currentRequest.SiteId = siteId; currentRequest.DomainId = findRouteResult.DomainId; currentRequest.DomainDatas = new Dictionary <string, string>(); currentRequest.IsSecure = true; currentRequest.Port = findRouteInput.Port; if (findRouteResult.DomainDatas != null) { foreach (var domainData in findRouteResult.DomainDatas) { currentRequest.DomainDatas.Add(domainData); } } dynamic master; try { master = await moduleManager.GetMasterAsync(currentRequest); } catch (Exception exception) { _logger.LogError(exception, "This catch should be remove"); master = await Business.InvokeAsync <ResetSiteCacheCommand, ResetSiteCacheInput, CommandResult <dynamic> >( resetSiteCacheCommand, new ResetSiteCacheInput { Site = currentRequest }); } var value = options.Value; var baseUrlJs = value.MainDomainUrl; parameters.Master = JsonConvert.SerializeObject(master, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); parameters.Version = value.Version; parameters.MainDomainUrl = @UrlHelper.Concat(baseUrlJs); parameters.IsDebug = value.IsDebug; parameters.BaseUrlJs = baseUrlJs; parameters.Header = HomeController.GetHeader(findRouteResult, master, Request, fullRequestUrl); parameters.BaseUrlSite = parameters.Header.BaseUrlSite; return(parameters); }
void ThreadFunc(object param) { bool alreadyReconnected = false; bool redirected = false; RetryCauses cause = RetryCauses.None; #if LOCK_ON_FILE object uriLock = null; #endif #if UNITY_WEBPLAYER // Right now, no caching supported in the webplayer if (!CurrentRequest.DisableCache) { CurrentRequest.DisableCache = true; } #endif try { if (!HasProxy && CurrentRequest.HasProxy) { Proxy = CurrentRequest.Proxy; } // Lock only if we will use the cached entity. #if LOCK_ON_FILE if (!CurrentRequest.DisableCache) { Monitor.Enter(uriLock = HTTPCacheFileLock.Acquire(CurrentRequest.CurrentUri)); } #endif // Try load the full response from an already saved cache entity. If the response if (TryLoadAllFromCache()) { return; } if (Client != null && !Client.IsConnected()) { Close(); } do // of while (reconnect) { if (cause == RetryCauses.Reconnect) { Close(); #if NETFX_CORE await Task.Delay(100); #else Thread.Sleep(100); #endif } LastProcessedUri = CurrentRequest.CurrentUri; cause = RetryCauses.None; // Connect to the server Connect(); if (State == HTTPConnectionStates.AbortRequested) { throw new Exception("AbortRequested"); } // Setup cache control headers before we send out the request if (!CurrentRequest.DisableCache) { HTTPCacheService.SetHeaders(CurrentRequest); } // Write the request to the stream // sentRequest will be true if the request sent out successfully(no SocketException), so we can try read the response bool sentRequest = CurrentRequest.SendOutTo(Stream); // sentRequest only true if there are no exceptions during CurrentRequest.SendOutTo. if (!sentRequest) { Close(); if (State == HTTPConnectionStates.TimedOut) { throw new Exception("AbortRequested"); } // We will try again only once if (!alreadyReconnected) { alreadyReconnected = true; cause = RetryCauses.Reconnect; } } // If sending out the request succeded, we will try read the response. if (sentRequest) { bool received = Receive(); if (State == HTTPConnectionStates.TimedOut) { throw new Exception("AbortRequested"); } if (!received && !alreadyReconnected) { alreadyReconnected = true; cause = RetryCauses.Reconnect; } if (CurrentRequest.Response != null) { switch (CurrentRequest.Response.StatusCode) { // Not authorized // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2 case 401: { string authHeader = CurrentRequest.Response.GetFirstHeaderValue("www-authenticate"); if (!string.IsNullOrEmpty(authHeader)) { var digest = DigestStore.GetOrCreate(CurrentRequest.CurrentUri); digest.ParseChallange(authHeader); if (CurrentRequest.Credentials != null && digest.IsUriProtected(CurrentRequest.CurrentUri) && (!CurrentRequest.HasHeader("Authorization") || digest.Stale)) { cause = RetryCauses.Authenticate; } } goto default; } // Proxy authentication required // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.8 case 407: { if (CurrentRequest.HasProxy) { string authHeader = CurrentRequest.Response.GetFirstHeaderValue("proxy-authenticate"); if (!string.IsNullOrEmpty(authHeader)) { var digest = DigestStore.GetOrCreate(CurrentRequest.Proxy.Address); digest.ParseChallange(authHeader); if (CurrentRequest.Proxy.Credentials != null && digest.IsUriProtected(CurrentRequest.Proxy.Address) && (!CurrentRequest.HasHeader("Proxy-Authorization") || digest.Stale)) { cause = RetryCauses.ProxyAuthenticate; } } } goto default; } // Redirected case 301: // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.2 case 302: // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.3 case 307: // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.8 case 308: // http://tools.ietf.org/html/rfc7238 { if (CurrentRequest.RedirectCount >= CurrentRequest.MaxRedirects) { goto default; } CurrentRequest.RedirectCount++; string location = CurrentRequest.Response.GetFirstHeaderValue("location"); if (!string.IsNullOrEmpty(location)) { Uri redirectUri = GetRedirectUri(location); // Let the user to take some control over the redirection if (!CurrentRequest.CallOnBeforeRedirection(redirectUri)) { HTTPManager.Logger.Information("HTTPConnection", "OnBeforeRedirection returned False"); goto default; } // Remove the previously set Host header. CurrentRequest.RemoveHeader("Host"); // Set the Referer header to the last Uri. CurrentRequest.SetHeader("Referer", CurrentRequest.CurrentUri.ToString()); // Set the new Uri, the CurrentUri will return this while the IsRedirected property is true CurrentRequest.RedirectUri = redirectUri; // Discard the redirect response, we don't need it any more CurrentRequest.Response = null; redirected = CurrentRequest.IsRedirected = true; } else #if !NETFX_CORE { throw new MissingFieldException(string.Format("Got redirect status({0}) without 'location' header!", CurrentRequest.Response.StatusCode.ToString())); } #else { throw new Exception(string.Format("Got redirect status({0}) without 'location' header!", CurrentRequest.Response.StatusCode.ToString())); } #endif goto default; } default: if (CurrentRequest.IsCookiesEnabled) { CookieJar.Set(CurrentRequest.Response); } TryStoreInCache(); break; } // If we have a response and the server telling us that it closed the connection after the message sent to us, then // we will colse the connection too. if (CurrentRequest.Response == null || CurrentRequest.Response.HasHeaderWithValue("connection", "close") || CurrentRequest.UseAlternateSSL) { Close(); } } } } while (cause != RetryCauses.None); } catch (TimeoutException e) { CurrentRequest.Response = null; CurrentRequest.Exception = e; CurrentRequest.State = HTTPRequestStates.ConnectionTimedOut; Close(); } catch (Exception e) { if (CurrentRequest.UseStreaming) { HTTPCacheService.DeleteEntity(CurrentRequest.CurrentUri); } // Something gone bad, Response must be null! CurrentRequest.Response = null; switch (State) { case HTTPConnectionStates.AbortRequested: CurrentRequest.State = HTTPRequestStates.Aborted; break; case HTTPConnectionStates.TimedOut: CurrentRequest.State = HTTPRequestStates.TimedOut; break; default: CurrentRequest.Exception = e; CurrentRequest.State = HTTPRequestStates.Error; break; } Close(); } finally { #if LOCK_ON_FILE if (!CurrentRequest.DisableCache && uriLock != null) { Monitor.Exit(uriLock); } #endif // Avoid state changes. While we are in this block changing the connection's State, on Unity's main thread // the HTTPManager's OnUpdate will check the connections's State and call functions that can change the inner state of // the object. (Like setting the CurrentRequest to null in function Recycle() causing a NullRef exception) lock (HTTPManager.Locker) { if (CurrentRequest != null && CurrentRequest.Response != null && CurrentRequest.Response.IsUpgraded) { State = HTTPConnectionStates.Upgraded; } else { State = redirected ? HTTPConnectionStates.Redirected : (Client == null ? HTTPConnectionStates.Closed : HTTPConnectionStates.WaitForRecycle); } // Change the request's state only when the whole processing finished if (CurrentRequest.State == HTTPRequestStates.Processing && (State == HTTPConnectionStates.Closed || State == HTTPConnectionStates.WaitForRecycle)) { CurrentRequest.State = HTTPRequestStates.Finished; } if (CurrentRequest.State == HTTPRequestStates.ConnectionTimedOut) { State = HTTPConnectionStates.Closed; } LastProcessTime = DateTime.UtcNow; } HTTPCacheService.SaveLibrary(); CookieJar.Persist(); } }
private void Connect() { Uri uri = CurrentRequest.HasProxy ? CurrentRequest.Proxy.Address : CurrentRequest.CurrentUri; if (Client == null) { Client = new TcpClient(); } if (!Client.Connected) { Client.ConnectTimeout = CurrentRequest.ConnectTimeout; #if NETFX_CORE Client.UseHTTPSProtocol = !CurrentRequest.UseAlternateSSL && HTTPProtocolFactory.IsSecureProtocol(uri); // On WinRT and >WP8 we use the more secure Tls12 protocol, but on WP8 only Ssl is available... #if UNITY_WP_8_1 || UNITY_METRO_8_1 Client.HTTPSProtocol = (int)SocketProtectionLevel.Tls12; #else Client.HTTPSProtocol = (int)SocketProtectionLevel.Ssl; #endif #endif Client.Connect(uri.Host, uri.Port); HTTPManager.Logger.Information("HTTPConnection", "Connected to " + uri.Host); } else { HTTPManager.Logger.Information("HTTPConnection", "Already connected to " + uri.Host); } lock (HTTPManager.Locker) StartTime = DateTime.UtcNow; if (Stream == null) { if (HasProxy && !Proxy.IsTransparent) { Stream = Client.GetStream(); var outStream = new BinaryWriter(Stream); outStream.Write(string.Format("CONNECT {0}:{1} HTTP/1.1", CurrentRequest.CurrentUri.Host, CurrentRequest.CurrentUri.Port).GetASCIIBytes()); outStream.Write(HTTPRequest.EOL); outStream.Write(string.Format("Proxy-Connection: Keep-Alive")); outStream.Write(HTTPRequest.EOL); outStream.Write(string.Format("Connection: Keep-Alive")); outStream.Write(HTTPRequest.EOL); outStream.Write(string.Format("Host: {0}:{1}", CurrentRequest.CurrentUri.Host, CurrentRequest.CurrentUri.Port).GetASCIIBytes()); outStream.Write(HTTPRequest.EOL); outStream.Write(HTTPRequest.EOL); outStream.Flush(); CurrentRequest.ProxyResponse = new HTTPProxyResponse(CurrentRequest, Stream, false, false); if (!CurrentRequest.ProxyResponse.Receive()) { throw new Exception("Connection to the Proxy Server failed!"); } // TODO: check & handle proxy status code? } // We have to use CurrentRequest.CurrentUri here, becouse uri can be a proxy uri with a different protocol if (HTTPProtocolFactory.IsSecureProtocol(CurrentRequest.CurrentUri)) { // On WP8 there are no Mono, so we must use the 'alternate' TlsHandlers if (CurrentRequest.UseAlternateSSL) { var handler = new TlsClientProtocol(Client.GetStream(), new Org.BouncyCastle.Security.SecureRandom()); if (CurrentRequest.CustomCertificateVerifyer == null) { handler.Connect(new LegacyTlsClient(new AlwaysValidVerifyer())); } else { handler.Connect(new LegacyTlsClient(CurrentRequest.CustomCertificateVerifyer)); } Stream = handler.Stream; } else { #if !UNITY_WP8 && !NETFX_CORE SslStream sslStream = new SslStream(Client.GetStream(), false, (sender, cert, chain, errors) => { return(CurrentRequest.CallCustomCertificationValidator(cert, chain)); }); if (!sslStream.IsAuthenticated) { sslStream.AuthenticateAsClient(uri.Host); } Stream = sslStream; #else Stream = Client.GetStream(); #endif } } else { Stream = Client.GetStream(); } } }
public bool Exclude(CurrentRequest request) { return _shouldExclude(request); }