public ThreadEntity(System.Web.HttpContext webApp, WebSetting.WebSettingItem webSetting, URLManage.URLItem urlItem, Xy.Tools.Web.UrlAnalyzer currentURL) { _webContext = webApp; _webSetting = webSetting; _urlItem = urlItem; _url = currentURL; _content = new HTMLContainer(_webSetting.Encoding); }
public WebProcess(System.Web.HttpContext context, fpTextOutputCallback_t callback) { this.m_HttpContext = context; if (callback == null) this.m_TextOutputCallback = new fpTextOutputCallback_t(DefaultTextOutput); else this.m_TextOutputCallback = callback; }
public void RelativeRootInWebApp() { var request = new System.Web.HttpRequest("~/abc.html", "http://www.google.com/", "?123=123"); var response = new System.Web.HttpResponse(new StringWriter()); var context = new System.Web.HttpContext(request, response); System.Web.HttpContext.Current = context; GetMockCache("~/temp"); }
public static MerchantTribe.Commerce.RequestContext GetFakeRequestContext(string fileName, string url, string querystring) { var result = new MerchantTribe.Commerce.RequestContext(); var request = new System.Web.HttpRequest(fileName, url, querystring); var response = new System.Web.HttpResponse(new System.IO.StringWriter()); System.Web.HttpContext httpContext = new System.Web.HttpContext(request, response); System.Web.HttpContextWrapper httpWrapper = new System.Web.HttpContextWrapper(httpContext); result.RoutingContext = new System.Web.Routing.RequestContext(httpWrapper, new System.Web.Routing.RouteData()); return result; }
public FitbitService(System.Web.UI.Page page, System.Web.HttpContext context) { _page = page; _context = context; // Create OAuthService object, containing oauth consumer configuration _oAuthService = OAuthService.Create( new EndPoint(RequestTokenUrl, "POST"), // requestTokenEndPoint new Uri(AuthorizationUrl), // authorizationUri new EndPoint(AccessTokenUrl, "POST"), // accessTokenEndPoint true, // useAuthorizationHeader "https://api.fitbit.com", // realm "HMAC-SHA1", // signatureMethod "1.0", // oauthVersion new OAuthConsumer(ConsumerKey, ConsumerSecret) // consumer ); }
public void UpdateValues(System.Web.HttpContext context, System.Web.UI.Control control) { }
public CacheSelectionEventArgs(System.Web.HttpContext context, IResponseArgs responseArgs, ICache defaultCache) { this.context = context; this.responseArgs = responseArgs; this.selectedCache = defaultCache; }
/// <summary> /// Generates a WMS 1.3.0 compliant response based on a <see cref="SharpMap.Map"/> and the current HttpRequest. /// </summary> /// <remarks> /// <para> /// The Web Map Server implementation in SharpMap requires v1.3.0 compatible clients, /// and support the basic operations "GetCapabilities" and "GetMap" /// as required by the WMS v1.3.0 specification. SharpMap does not support the optional /// GetFeatureInfo operation for querying. /// </para> /// <example> /// Creating a WMS server in ASP.NET is very simple using the classes in the SharpMap.Web.Wms namespace. /// <code lang="C#"> /// void page_load(object o, EventArgs e) /// { /// //Get the path of this page /// string url = (Request.Url.Query.Length>0?Request.Url.AbsoluteUri.Replace(Request.Url.Query,""):Request.Url.AbsoluteUri); /// SharpMap.Web.Wms.Capabilities.WmsServiceDescription description = /// new SharpMap.Web.Wms.Capabilities.WmsServiceDescription("Acme Corp. Map Server", url); /// /// // The following service descriptions below are not strictly required by the WMS specification. /// /// // Narrative description and keywords providing additional information /// description.Abstract = "Map Server maintained by Acme Corporation. Contact: [email protected]. High-quality maps showing roadrunner nests and possible ambush locations."; /// description.Keywords.Add("bird"); /// description.Keywords.Add("roadrunner"); /// description.Keywords.Add("ambush"); /// /// //Contact information /// description.ContactInformation.PersonPrimary.Person = "John Doe"; /// description.ContactInformation.PersonPrimary.Organisation = "Acme Inc"; /// description.ContactInformation.Address.AddressType = "postal"; /// description.ContactInformation.Address.Country = "Neverland"; /// description.ContactInformation.VoiceTelephone = "1-800-WE DO MAPS"; /// //Impose WMS constraints /// description.MaxWidth = 1000; //Set image request size width /// description.MaxHeight = 500; //Set image request size height /// /// //Call method that sets up the map /// //We just add a dummy-size, since the wms requests will set the image-size /// SharpMap.Map myMap = MapHelper.InitializeMap(new System.Drawing.Size(1,1)); /// /// //Parse the request and create a response /// SharpMap.Web.Wms.WmsServer.ParseQueryString(myMap,description); /// } /// </code> /// </example> /// </remarks> /// <param name="map">Map to serve on WMS</param> /// <param name="description">Description of map service</param> public static void ParseQueryString(SharpMap.Map map, Capabilities.WmsServiceDescription description) { if (map == null) { throw (new ArgumentException("Map for WMS is null")); } if (map.Layers.Count == 0) { throw (new ArgumentException("Map doesn't contain any layers for WMS service")); } if (System.Web.HttpContext.Current == null) { throw (new ApplicationException("An attempt was made to access the WMS server outside a valid HttpContext")); } System.Web.HttpContext context = System.Web.HttpContext.Current; //IgnoreCase value should be set according to the VERSION parameter //v1.3.0 is case sensitive, but since it causes a lot of problems with several WMS clients, we ignore casing anyway. bool ignorecase = true; //Check for required parameters //Request parameter is mandatory if (context.Request.Params["REQUEST"] == null) { WmsException.ThrowWmsException("Required parameter REQUEST not specified"); return; } //Check if version is supported if (context.Request.Params["VERSION"] != null) { if (String.Compare(context.Request.Params["VERSION"], "1.3.0", ignorecase) != 0) { WmsException.ThrowWmsException("Only version 1.3.0 supported"); return; } } else //Version is mandatory if REQUEST!=GetCapabilities. Check if this is a capabilities request, since VERSION is null { if (String.Compare(context.Request.Params["REQUEST"], "GetCapabilities", ignorecase) != 0) { WmsException.ThrowWmsException("VERSION parameter not supplied"); return; } } //If Capabilities was requested if (String.Compare(context.Request.Params["REQUEST"], "GetCapabilities", ignorecase) == 0) { //Service parameter is mandatory for GetCapabilities request if (context.Request.Params["SERVICE"] == null) { WmsException.ThrowWmsException("Required parameter SERVICE not specified"); return; } if (String.Compare(context.Request.Params["SERVICE"], "WMS") != 0) { WmsException.ThrowWmsException("Invalid service for GetCapabilities Request. Service parameter must be 'WMS'"); } System.Xml.XmlDocument capabilities = Wms.Capabilities.GetCapabilities(map, description); context.Response.Clear(); context.Response.ContentType = "text/xml"; System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(context.Response.OutputStream); capabilities.WriteTo(writer); writer.Close(); context.Response.End(); } else if (String.Compare(context.Request.Params["REQUEST"], "GetMap", ignorecase) == 0) //Map requested { //Check for required parameters if (context.Request.Params["LAYERS"] == null) { WmsException.ThrowWmsException("Required parameter LAYERS not specified"); return; } if (context.Request.Params["STYLES"] == null) { WmsException.ThrowWmsException("Required parameter STYLES not specified"); return; } if (context.Request.Params["CRS"] == null) { WmsException.ThrowWmsException("Required parameter CRS not specified"); return; } else if (context.Request.Params["CRS"] != "EPSG:" + map.Layers[0].SRID.ToString()) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidCRS, "CRS not supported"); return; } if (context.Request.Params["BBOX"] == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter BBOX not specified"); return; } if (context.Request.Params["WIDTH"] == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter WIDTH not specified"); return; } if (context.Request.Params["HEIGHT"] == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter HEIGHT not specified"); return; } if (context.Request.Params["FORMAT"] == null) { WmsException.ThrowWmsException("Required parameter FORMAT not specified"); return; } //Set background color of map if (String.Compare(context.Request.Params["TRANSPARENT"], "TRUE", ignorecase) == 0) { map.BackColor = System.Drawing.Color.Transparent; } else if (context.Request.Params["BGCOLOR"] != null) { try { map.BackColor = System.Drawing.ColorTranslator.FromHtml(context.Request.Params["BGCOLOR"]); } catch { WmsException.ThrowWmsException("Invalid parameter BGCOLOR"); return; }; } else { map.BackColor = System.Drawing.Color.White; } //Get the image format requested System.Drawing.Imaging.ImageCodecInfo imageEncoder = GetEncoderInfo(context.Request.Params["FORMAT"]); if (imageEncoder == null) { WmsException.ThrowWmsException("Invalid MimeType specified in FORMAT parameter"); return; } //Parse map size int width = 0; int height = 0; if (!int.TryParse(context.Request.Params["WIDTH"], out width)) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Invalid parameter WIDTH"); return; } else if (description.MaxWidth > 0 && width > description.MaxWidth) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Parameter WIDTH too large"); return; } if (!int.TryParse(context.Request.Params["HEIGHT"], out height)) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Invalid parameter HEIGHT"); return; } else if (description.MaxHeight > 0 && height > description.MaxHeight) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Parameter HEIGHT too large"); return; } map.Size = new System.Drawing.Size(width, height); SharpMap.Geometries.BoundingBox bbox = ParseBBOX(context.Request.Params["bbox"]); if (bbox == null) { WmsException.ThrowWmsException("Invalid parameter BBOX"); return; } map.PixelAspectRatio = ((double)width / (double)height) / (bbox.Width / bbox.Height); map.Center = bbox.GetCentroid(); map.Zoom = bbox.Width; //Set layers on/off if (!String.IsNullOrEmpty(context.Request.Params["LAYERS"])) //If LAYERS is empty, use default layer on/off settings { string[] layers = context.Request.Params["LAYERS"].Split(new char[] { ',' }); if (description.LayerLimit > 0) { if (layers.Length == 0 && map.Layers.Count > description.LayerLimit || layers.Length > description.LayerLimit) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Too many layers requested"); return; } } foreach (SharpMap.Layers.ILayer layer in map.Layers) { layer.Enabled = false; } foreach (string layer in layers) { //SharpMap.Layers.ILayer lay = map.Layers.Find(delegate(SharpMap.Layers.ILayer findlay) { return findlay.LayerName == layer; }); SharpMap.Layers.ILayer lay = null; for (int i = 0; i < map.Layers.Count; i++) { if (String.Equals(map.Layers[i].LayerName, layer, StringComparison.InvariantCultureIgnoreCase)) { lay = map.Layers[i]; } } if (lay == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.LayerNotDefined, "Unknown layer '" + layer + "'"); return; } else { lay.Enabled = true; } } } //Render map System.Drawing.Image img = map.GetMap(); //Png can't stream directy. Going through a memorystream instead System.IO.MemoryStream MS = new System.IO.MemoryStream(); img.Save(MS, imageEncoder, null); img.Dispose(); byte[] buffer = MS.ToArray(); context.Response.Clear(); context.Response.ContentType = imageEncoder.MimeType; context.Response.OutputStream.Write(buffer, 0, buffer.Length); context.Response.End(); } else { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Invalid request"); } }
/// <summary> /// CTOR /// </summary> /// <param name="context"></param> public HeaderCollection(System.Web.HttpContext context) { _context = context; }
/// <summary> /// Recupera o valor. /// </summary> /// <param name="context"></param> /// <param name="control"></param> /// <returns></returns> protected override object Evaluate(System.Web.HttpContext context, System.Web.UI.Control control) { return(System.Web.UI.DataBinder.Eval(control.Page.GetDataItem(), PropertyName)); }
/// <summary> /// Returns the language for the current request inferred from the request context: /// that is, attributes of the request other that the URL. /// </summary> /// <remarks> /// The language is infered from the following attributes of the request, /// in order of preference:<br/> /// i18n.langtag cookie<br/> /// Accept-Language header<br/> /// fall back to i18n.LocalizedApplication.Current.DefaultLanguage<br/> /// Additionally, each language is matched by the language matching algorithm /// against the set of application languages available. /// </remarks> /// <param name="context">Context of the current request.</param> /// <returns> /// Returns language tag describing the inferred language. /// </returns> /// <exception cref="System.InvalidOperationException"> /// Expected GetRequestUserLanguages to fall back to default language. /// </exception> public static LanguageTag GetInferredLanguage(this System.Web.HttpContext context) { return(context.GetHttpContextBase().GetInferredLanguage()); }
/// <summary> /// Add a Content-Language HTTP header to the response, based on any languages /// that have provided resources during the request. /// </summary> /// <param name="context">Context of the current request.</param> /// <returns> /// true if header added; false if no languages provided content during the request and /// so no header was added. /// </returns> public static bool SetContentLanguageHeader(this System.Web.HttpContext context) { return(context.GetHttpContextBase().SetContentLanguageHeader()); }
/// <summary> /// Returns a collection of languages supported by the user-agent, in descending order /// of preference. The first item in the collection refers to any Principle Application Language (PAL) /// for the request determined by EarlyUrlLocalization (which calls SetPrincipalAppLanguageForRequest), /// or is null if EarlyUrlLocalization is disabled. /// </summary> /// <param name="context">Context of the current request.</param> /// <returns> /// Array of languages items sorted in order or language preference. /// </returns> /// <remarks> /// This method is optimised such that the collection is built only once per request. /// </remarks> /// <see> /// See LanguageItem.ParseHttpLanguageHeader for more details. /// </see> public static LanguageItem[] GetRequestUserLanguages(this System.Web.HttpContext context) { return(context.GetHttpContextBase().GetRequestUserLanguages()); }
public override void ProcessMubbleRequest(System.Web.HttpContext context) { this.Context = context; throw new Exception("The method or operation is not implemented."); }
public APIException(HttpResponseMessage response, HttpContext context) { Response = response; RequestContext = context; }
/// <summary> /// 51book通知 /// </summary> public static ExternalPlatformNotifyView _51BookNotify(System.Web.HttpContext context) { var processor = _51book.NotifyProcessor.CreateProcessor(context); return(processor.Execute()); }
/// <summary> /// Runs the Language Matching Algorithm for the UserLanguages of the current request against /// the specified array of AppLanguages, returning the AppLanguage determined to be the best match. /// </summary> /// <param name="context">Context of the current request.</param> /// <param name="AppLanguages"> /// The list of languages in which an arbitrary resource is available. /// </param> /// <returns> /// LanguageTag instance selected from AppLanguages with the best match, or null if there is no match /// at all (or UserLanguages and/or AppLanguages is empty). /// It is possible for there to be no match at all if no language subtag in the UserLanguages tags /// matches the same of any of the tags in AppLanguages list. /// </returns> public static LanguageTag ChooseAppLanguage(this System.Web.HttpContext context, IEnumerable <LanguageTag> AppLanguages) { return(context.GetHttpContextBase().ChooseAppLanguage(AppLanguages)); }
public HttpContext(System.Web.HttpContext httpContext) { _httpContext = httpContext; }
/// <summary> /// Returns the translation of the passed string entity which may contain zero or more fully-formed nugget. /// </summary> /// <param name="context">Describes the current request.</param> /// <param name="entity">String containing zero or more fully-formed nuggets which are to be translated according to the language selection of the current request.</param> /// <returns>Localized (translated) entity.</returns> public static string ParseAndTranslate(this System.Web.HttpContext context, string entity) { return(context.GetHttpContextBase().ParseAndTranslate(entity)); }
public System.Web.IHttpHandler GetHandler(System.Web.HttpContext context, string requestType, string url, string pathTranslated) { throw new NotImplementedException(); }
//+ //- @Ctor -// public IndexEntryTemplate(ListItemType type) { this.type = type; //+ httpContext = System.Web.HttpContext.Current; }
/// <summary> /// CTOR /// </summary> /// <param name="context"></param> public HeaderCollection(Microsoft.AspNetCore.Http.HttpContext context) { _context = context; }
public void ProcessRequest(System.Web.HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Write(this.GetGoodsDetails(context)); }
// Constructors public ProfileEventArgs(System.Web.HttpContext context) { }
private static void LogDb(string msg, string msgEr, string stackTrace, string targetSite, string source, System.Web.HttpContext current) { try { string keys = ""; int idUsuario = 0; Kart_log_erro erro = new Kart_log_erro { dtErro = DateTime.Now }; Usuario user = null; if (current.Session?["Usuario"] != null) { user = (Usuario)current.Session["Usuario"]; } if (user != null) { idUsuario = user.idUsuario; } foreach (string s in current.Request.Form.AllKeys) { if (s != "__VIEWSTATE") { keys += s + ":" + current.Request.Form[s] + Environment.NewLine; } } if (!string.IsNullOrEmpty(keys)) { erro.Keys = keys; } erro.URL = current.Request.Url.ToString(); erro.RawUrl = current.Request.RawUrl; erro.QueryString = current.Request.QueryString.ToString(); erro.UserAgent = current.Request.UserAgent; erro.UserIP = current.Request.ServerVariables["REMOTE_ADDR"]; erro.Referrer = current.Request.UrlReferrer != null?current.Request.UrlReferrer.ToString() : ""; erro.Erro = msgEr; erro.idUsuario = idUsuario <= 0 ? null : (int?)idUsuario; erro.Mensagem = msg; erro.StackTrace = stackTrace; erro.TargetSite = targetSite; erro.Source = source; DataKartDataContext db = new DataKartDataContext(); db.GetTable <Kart_log_erro>().InsertOnSubmit(erro); db.SubmitChanges(); } catch { // ignored } }
/// <summary> /// 日志格式化 /// </summary> /// <param name="appid"></param> /// <param name="message"></param> /// <returns></returns> private string TextFormat(object message) { System.Diagnostics.StackTrace stackTrance = new System.Diagnostics.StackTrace(true); var _frame = stackTrance.GetFrame(4); if (_frame != null) { var msgModel = (Models.LogEvent)message; Models.LogEventClassInfo _message = new Models.LogEventClassInfo(); _message.uuid = msgModel.uuid; _message.module = msgModel.module; _message.uuidtag = msgModel.uuidtag; _message.message = msgModel.message; _message.request = msgModel.request; _message.response = msgModel.response; _message.otherMsg = msgModel.otherMsg; _message.methodName = _frame.GetMethod().Name; _message.className = _frame.GetMethod().DeclaringType?.FullName; _message.fileName = _frame.GetFileName(); _message.lineNumber = _frame.GetFileLineNumber(); var fullinfoFormat = "{0}.{1}({2}:{3})"; _message.fullInfo = string.Format(fullinfoFormat, _message.className, _message.methodName, _message.fileName, _message.lineNumber); // .NET Compact Framework 1.0 has no support for ASP.NET // SSCLI 1.0 has no support for ASP.NET #if !NETCF && !SSCLI && !NETSTANDARD //ASP.NET,获取上下文 System.Web.HttpContext context = null; if (System.Web.HttpContext.Current != null) { context = System.Web.HttpContext.Current; _message.SERVER_NAME = context.Request.Params["SERVER_NAME"]; _message.HTTP_HOST = context.Request.Params["HTTP_HOST"]; _message.SERVER_PORT = context.Request.Params["SERVER_PORT"]; _message.LOCAL_ADDR = context.Request.Params["LOCAL_ADDR"]; _message.Appl_Physical_Path = context.Request.Params["Appl_Physical_Path"]; } #elif NETSTANDARD //NETSTANDARD var context = ExtensionMethods.GetHttpContext(); if (context != null) { _message.SERVER_NAME = context.Request.Host.Value; _message.HTTP_HOST = context.Request.Host.Host; _message.SERVER_PORT = context.Request.Host.Port.ToString(); _message.LOCAL_ADDR = context.Connection.LocalIpAddress.ToString(); _message.Appl_Physical_Path = AppDomain.CurrentDomain.BaseDirectory; } else { _message.SERVER_NAME = AppDomain.CurrentDomain.FriendlyName; _message.Appl_Physical_Path = AppDomain.CurrentDomain.BaseDirectory; } #endif return(SerializeObject(_message)); } else { return(SerializeObject(message)); } }
public static void Logar(string msg, System.Web.HttpContext current) { Logar(msg, null, current); }
public NeoWebContext(System.Web.HttpContext inner) { this.Inner = inner; }
public static void Logar(string msg, Exception ex, System.Web.HttpContext current) { try { Exception tmp = ex; string msgEr = ""; string stackTrace = ""; string targetSite = ""; string source = ""; string path = PathUtil.GetFullPathRoot() + "\\log\\"; string fileName = path + DateTime.Now.ToString("dd-MM-yyyy") + ".log"; Usuario user = null; if (current.Session?["Usuario"] != null) { user = (Usuario)current.Session["Usuario"]; } if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } if (!File.Exists(fileName)) { File.Create(fileName); } while (tmp != null) { msgEr += ex.Message + Environment.NewLine; stackTrace += ex.StackTrace + Environment.NewLine; targetSite += ex.TargetSite + Environment.NewLine; source += ex.Source + Environment.NewLine; tmp = tmp.InnerException; } LogDb(msg, msgEr, stackTrace, targetSite, source, current); using (var file = new StreamWriter(fileName, true)) { file.WriteLine($"---------------{DateTime.Now:HH:mm:ss}------------------"); file.WriteLine(""); file.WriteLine("Mensagem: " + msg); file.WriteLine(""); file.WriteLine("Erro: " + msgEr); file.WriteLine("StackTrace: " + stackTrace); file.WriteLine("TargetSite: " + targetSite); file.WriteLine("Source: " + source); file.WriteLine(""); file.WriteLine("URL: " + current.Request.Url); file.WriteLine("RawUrl: " + current.Request.RawUrl); file.WriteLine("QueryString: " + current.Request.QueryString); if (current.Request.UserAgent != null) { file.WriteLine("User Agent: " + current.Request.UserAgent); } file.WriteLine("User IP: " + current.Request.ServerVariables["REMOTE_ADDR"]); if (current.Request.UrlReferrer != null) { file.WriteLine(current.Request.UrlReferrer.ToString()); } string keys = ""; foreach (string s in current.Request.Form.AllKeys) { if (s != "__VIEWSTATE") { keys += s + ":" + current.Request.Form[s] + Environment.NewLine; } } if (!string.IsNullOrEmpty(keys)) { file.WriteLine("Keys: " + keys); } if (user != null) { file.WriteLine(user.idUsuario); } file.WriteLine(""); file.WriteLine("-------------------"); file.WriteLine(""); file.Flush(); } } catch { // ignored } }
public System.Collections.Specialized.IOrderedDictionary GetValues(System.Web.HttpContext context, System.Web.UI.Control control) { return(default(System.Collections.Specialized.IOrderedDictionary)); }
/// <summary> /// 根据分类id获取分页商品 /// </summary> /// <param name="context"></param> private void getProductsByCategoryId(System.Web.HttpContext context) { int numCategoryid = 0; int categoryid = 0; if (int.TryParse(context.Request["categoryid"], out numCategoryid)) { categoryid = numCategoryid; } int numStoreId = 0; int StoreId = 0; if (int.TryParse(context.Request["StoreId"], out numStoreId)) { StoreId = numStoreId; } int numP = 0; int p = 1; if (int.TryParse(context.Request["p"], out numP)) { p = numP; } string where = "Where SaleStatus in (1,4) and storeid=" + StoreId; string whereSku = "where salestatus in (1,4) and storeid=" + StoreId; string orderbyProduct = "displaysequence "; //默认根据主键排序(分页最快) string orderbySku = "skuid"; if (categoryid != 0) { where += string.Format(" And categoryid={0}", categoryid); } int pagesize = 100;//该接口暂时返回100条商品,超过了100之后再做分页处理 int currPage = p; string productFrom = @"( SELECT (select top 1 skuid from Hishop_SKUs where Hishop_SKUs.ProductId = Hishop_Products.ProductId)as skuid, (select top 1 Stock from Hishop_SKUs where Hishop_SKUs.ProductId = Hishop_Products.ProductId) as stock, (select top 1 SalePrice from Hishop_SKUs where Hishop_SKUs.ProductId = Hishop_Products.ProductId) as saleprice, salestatus,displaysequence,categoryid,typeid,productid,productname,shortdescription,showsalecounts,ImageUrl1,ImageUrl2,ImageUrl3,ImageUrl4,ImageUrl5,marketprice,hasSKU,Range FROM Hishop_Products " + where + " ) t"; string skuFrom = "(SELECT SkuId, ProductId, SKU,Weight, Stock, CostPrice, SalePrice FROM Hishop_SKUs s WHERE ProductId in(Select ProductId From Hishop_Products " + where + ")"; int productCount = ProductBrowser.GetDataCount(productFrom, where); int pageCount = productCount / pagesize + (productCount % pagesize == 0 ? 0 : 1); int nextPage = (currPage < pageCount) ? (currPage + 1) : 0; //下一页为0时,表示无数据可加载(数据加载完毕) DataSet ds = new DataSet(); DataTable dtProduct = ProductBrowser.GetPageData(productFrom, orderbyProduct, "*", currPage, pagesize, where); dtProduct.TableName = "dtproduct"; //根据查询出来当前分页的商品id拼接sku的productid whereSku += " and productid in ({0})"; string strs = ""; foreach (DataRow row in dtProduct.Rows) { strs += row["productid"] + ","; } if (dtProduct.Rows.Count == 0) { strs = "0"; } whereSku = string.Format(whereSku, strs.TrimEnd(',')); DataTable dtSku = ProductBrowser.getSkusByWhere(whereSku); dtSku.TableName = "dtsku"; ds.Tables.Add(dtProduct); ds.Tables.Add(dtSku); DataRelation dataRelation = new DataRelation("Products2SKUs", ds.Tables[0].Columns["ProductId"], ds.Tables[1].Columns["ProductId"]); ds.Relations.Add(dataRelation); //输出JSON string result = string.Format("{{\"state\":{0},\r\"count\":{1},\r\"pageCount\":{2},\r\"nextPage\":{3},\r\"data\":" , (dtProduct.Rows.Count > 0) ? 0 : 1, productCount, pageCount, nextPage); result += JsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented); result += "}"; context.Response.Write(result); }
public APIException(string message, Exception inner, HttpResponseMessage response, HttpContext context) : base(message, inner) { Response = response; RequestContext = context; }
/// <summary> /// 调用微信接口获取所有门店信息 /// </summary> /// <param name="context"></param> private void getPoiList(System.Web.HttpContext context) { context.Response.ContentType = "application/json"; try { Thread.Sleep(1000); DataTable dtPoiInfo = WxPoiHelper.GetPoiListInfo(); List <PoiInfoList> poiInfoList = new List <PoiInfoList>(); if (dtPoiInfo.Rows.Count == 0)//如果没有同步,则调用微信接口重新获取 { //获取access_token string token = Access_token.GetAccess_token(Access_token.Access_Type.weixin, true); //门店列表接口提交url string url = "https://api.weixin.qq.com/cgi-bin/poi/getpoilist?access_token=" + token; //提交json串,门店列表索引开始:begin,门店列表返回数量限制:limit string json = @"{""begin"":0,""limit"":10}"; //调用post提交方法 string strPOIList = new Hishop.Weixin.MP.Util.WebUtils().DoPost(url, json); //将传回的json字符串转换为json对象 JObject obj3 = JsonConvert.DeserializeObject(strPOIList) as JObject; //将json对象转换为实体类对象 poiInfoList = JsonHelper.JsonToList <PoiInfoList>(obj3["business_list"].ToString()); //同步微信门店信息 if (WxPoiHelper.SyncPoiListInfo(poiInfoList)) { dtPoiInfo = WxPoiHelper.GetPoiListInfo(); } } //获取所有门店的坐标 string offset = string.Empty; foreach (DataRow row in dtPoiInfo.Rows) { offset += row["longitude"] + "," + row["latitude"] + ";";//增加精度纬度 } offset = offset.TrimEnd(';'); //将门店坐标放入数组 string[] offsetList = offset.Split(';'); /****************根据配送范围将门店的坐标循环匹配用户当前的坐标,误差范围:1公里*******************/ //允许的误差值(配送范围) double range = Convert.ToDouble(context.Request["range"]); //获取用户的坐标 double userLongtitude = Convert.ToDouble(context.Request["userLontitude"]); double userLatitude = Convert.ToDouble(context.Request["userLatitude"]); //循环判断获取距离,得到配送范围内的门店poi_id List <string> poi_id = new List <string>(); List <double> poi_user_distance = new List <double>(); for (int i = 0; i < offsetList.Length; i++) { string[] oa = offsetList[i].Split(',');//获取门店经度,纬度 double distance = GetDistance(userLatitude, userLongtitude, Convert.ToDouble(oa[1]), Convert.ToDouble(oa[0])); if (distance <= range) { poi_id.Add(dtPoiInfo.Rows[i]["poi_id"].ToString()); poi_user_distance.Add(distance); } } bool isUserInRange = false; string matchIds = ""; string matchDistance = ""; if (poi_id.Count > 0)//如果有配送范围内的用户,则返回第一个匹配到的门店后台id { for (int i = 0; i < poi_id.Count; i++) { DataTable dtSender = WxPoiHelper.GetSenderByPoiId(poi_id[i]); foreach (DataRow row in dtSender.Rows) { if (row["clientUserId"].ToString() != "") { matchIds += row["clientUserId"] + ","; matchDistance += poi_user_distance[i] + ","; } } } isUserInRange = true; //如果匹配到的微信门店还没有绑定至后台账号,给出提示 if (matchIds.Length == 0) { context.Response.Write("{\"success\":false,\"errMsg\":\"匹配到了未绑定的门店,或者门店还未通过审核!\"}"); return; } //根据门店id匹配到对应的子账号id:sender matchDistance = matchDistance.TrimEnd(','); matchIds = matchIds.TrimEnd(','); //string[] sender = matchId.Split(','); //string[] clientUserId = matchId.Split(','); /* * //将匹配到的所有门店以门店名字进行展示 (目前更换为街道名) * DataTable dtStoreName = WxPoiHelper.GetStoreName(matchIds); * string storeNameBtns = ""; * foreach (DataRow row in dtStoreName.Rows) * { * storeNameBtns += "<span role='btnStreet' distributorId='" + row["userid"].ToString() + "'>" + row["storeName"].ToString() + "</span>"; * } */ //将匹配到的所有街道以街道名字进行展示 DataTable dtStreetName = WxPoiHelper.GetStoreStreets(matchIds); string streetNameBtns = ""; foreach (DataRow row in dtStreetName.Rows) { streetNameBtns += "<span role='btnStreet' la='" + row["latitude"] + "' lo='" + row["longitude"] + "' distributorId='" + row["distributorid"].ToString() + "'>" + row["regionName"].ToString() + "</span>"; } context.Response.Write("{\"success\":true,\"isUserInRange\":\"" + isUserInRange + "\",\"distributorId\":\"" + streetNameBtns + "\"}"); } else { context.Response.Write("{\"success\":true,\"isUserInRange\":\"" + isUserInRange + "\"}"); } /* * //调试 * string[] la0 = offsetList[0].Split(','); * double distance = GetDistance(userLatitude,userLongtitude,Convert.ToDouble(la0[1]),Convert.ToDouble(la0[0])); * context.Response.Write("{\"success\":true,\"userLo\":" + userLongtitude + ",\"userLa\":" + userLatitude + ",\"poiLA\":\"" + offsetList[0] + "\",\"distance\":"+distance+"}"); */ } catch (Exception ex) { context.Response.Write("{\"success\":false,\"errMsg\":\"" + ex.Message + "\"}"); } }
/// <summary> /// 易行通知 /// </summary> public static ExternalPlatformNotifyView YeexingNotify(System.Web.HttpContext context) { var processor = Yeexing.NotifyProcessor.CreateProcessor(context); return(processor.Execute()); }
public void HandlePollVote(System.Web.HttpContext context) { var user = TEApi.Users.AccessingUser; if (user.IsSystemAccount.HasValue && user.IsSystemAccount.Value) { context.Response.RedirectLocation = TEApi.CoreUrls.LogIn(new CoreUrlLoginOptions() { ReturnToCurrentUrl = true }); context.Response.StatusCode = 302; context.Response.End(); } var pollContextItem = TEApi.Url.CurrentContext.ContextItems.GetItemByContentType(PublicApi.Polls.ContentTypeId); Poll poll = null; if (pollContextItem != null && pollContextItem.ContentId.HasValue) { poll = InternalApi.PollingService.GetPoll(pollContextItem.ContentId.Value); } if (poll == null) { throw new PollException(_translatablePluginController.GetLanguageResourceValue("poll_NotFound")); } var pollAnswerIdObj = TEApi.Url.CurrentContext.GetTokenValue("PollAnswerId"); Guid pollAnswerId; if (pollAnswerIdObj != null && Guid.TryParse(pollAnswerIdObj.ToString(), out pollAnswerId)) { var answer = InternalApi.PollingService.GetPollAnswer(pollAnswerId); if (answer != null) { try { InternalApi.PollingService.AddUpdatePollVote(new Telligent.BigSocial.Polling.InternalApi.PollVote() { PollId = poll.Id, UserId = user.Id.Value, PollAnswerId = pollAnswerId }); var url = TEApi.Url.Adjust(InternalApi.PollingUrlService.PollUrl(poll.Id), "voted=" + pollAnswerId.ToString()); context.Response.RedirectLocation = url; context.Response.StatusCode = 302; context.Response.End(); } catch (Exception ex) { throw new PollException(_translatablePluginController.GetLanguageResourceValue("vote_UnknownError"), ex); } } else { var url = TEApi.Url.Adjust(InternalApi.PollingUrlService.PollUrl(poll.Id), "votefailed=true"); context.Response.RedirectLocation = url; context.Response.StatusCode = 302; context.Response.End(); } } }
public TranslateSvc_HttpContext(System.Web.HttpContext context) { if (context == null) { throw new ArgumentNullException("context"); } m_context = context; }
//--------------------------------------------------------------- // This method is called from the generic server at startup, when the first client connects. // It defines the application specific server parameters and operating modes. // The configuration definitions are read from the file "DANSrv.exe.config" // and the item set from the ConfigBuilder file "DANSrv.Items.XML" new public int GetServerParameters(out int UpdatePeriod, out int BrowseMode, out int validateMode, out char BranchDelemitter) { if (TraceLog != null) { LogFile.Write("GetServerParameters"); } // Default Values UpdatePeriod = 100; // ms BrowseMode = (int)BROWSEMODE.REAL; // browse the real address space (generic part internally) validateMode = (int)ValidateMode.Never; // never call Plugin.ValidateItems BranchDelemitter = '.'; AppSettingsReader ar = new AppSettingsReader(); object val = null; //------- UpdatePeriod Definition try { val = null; val = ar.GetValue("UpdatePeriod", typeof(int)); if (val != null) { UpdatePeriod = Convert.ToInt32(val); } } catch { } //------ BowseMode definition try { val = null; val = ar.GetValue("BrowseMode", typeof(string)); if (val != null) { if (val.ToString().ToUpper() == "VIRTUAL") { BrowseMode = (int)BROWSEMODE.VIRTUAL; } } } catch { } //------ ValidateMode definition try { val = null; val = ar.GetValue("ValidateMode", typeof(string)); if (val != null) { if (val.ToString().ToUpper() == "UNKNOWNITEMS") { validateMode = (int)ValidateMode.UnknownItems; } else if (val.ToString().ToUpper() == "ALWAYS") { validateMode = (int)ValidateMode.Always; } } } catch { } //------ BranchDelemitter definition try { val = null; val = ar.GetValue("BranchDelemitter", typeof(char)); if (val != null) { BranchDelemitter = Convert.ToChar(val); } } catch { } //------ Item definitions XML File. If exists then use BranchDelimitter definition from XML file string xmlFileName = "DANSrv.Items.XML"; try { val = null; val = ar.GetValue("ItemConfigFile", typeof(string)); if (val != null) { xmlFileName = (string)val; } } catch { } if (TraceLog != null) { LogFile.Write("ItemConfigFile = " + xmlFileName); } string path = null; System.Reflection.Assembly asm = System.Reflection.Assembly.GetEntryAssembly(); if (asm != null) { path = asm.Location; int idx = path.LastIndexOf("\\"); if (idx >= 0) { path = path.Substring(0, idx + 1); } else { path = ""; } } else // seems to be a web service { System.Web.HttpContext hc = System.Web.HttpContext.Current; if (hc != null) // asmx web service { path = hc.Server.MapPath(".") + "\\"; // web dir } else // WCF service { #if !VS2003 path = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath; #endif } } string itemxml = path + xmlFileName; if (TraceLog != null) { LogFile.Write("ItemConfigFile path = " + itemxml); } bool isLoaded = false; Config = new ConfigBuilder.ConfigLoader(); if (File.Exists(itemxml)) { try { if (TraceLog != null) { LogFile.Write("LoadFromExeDir"); } Config.LoadFromExeDir(xmlFileName); // load from external file if (Config.BranchSeparator != null) { BranchDelemitter = Config.BranchSeparator[0]; } isLoaded = true; if (TraceLog != null) { LogFile.Write(" file loaded"); } } catch { } } if (!isLoaded) { try { if (TraceLog != null) { LogFile.Write("LoadEmbedded"); } Config.LoadEmbedded("NSPlugin." + xmlFileName); // load from embedded file isLoaded = true; if (TraceLog != null) { LogFile.Write(" file loaded"); } } catch { } } if (!isLoaded) { Config = null; System.Diagnostics.EventLog elog = new System.Diagnostics.EventLog("Application"); elog.Source = "DANSrv"; elog.WriteEntry("File " + itemxml + " not found", System.Diagnostics.EventLogEntryType.Error); } return(HRESULTS.S_OK); }
public SessionStateImpl(System.Web.HttpContext context) { _context = context; }