public void Perform(WorkContext context) { var from = context.Request.QueryString["from"].AsInt(1); var to = context.Request.QueryString["to"].AsInt(10); if (to-from>1000) to = from + 1000;//limit so no infinite loop possible context.Response.ContentType = ContentType.TEXT; for(var i=from;i<=to;i++) context.Response.WriteLine("{0} times and counting".Args(i)); }
protected override MethodInfo FindMatchingAction(WorkContext work, string action, out object[] args) { if (action.IndexOf('-') > 3) // pattern: xxx-... { try { var el = new ELink(action); args = new object[] {el.ID}; return mi_Resolve; } catch { } } args = null; return null; }
protected override void DoFilterWork(WorkContext work, IList<WorkFilter> filters, int thisFilterIndex) { foreach (var match in m_Matches.OrderedValues) { var matched = match.Make(work); if (matched == null) continue; var newAction = matched[VAR_NEW_ACTION].AsString(); if (newAction.IsNullOrWhiteSpace()) continue; var oldUrl = work.Request.Url.ToString(); var newUrl = changeMvcUrlAction(oldUrl, newAction); if (newUrl == null) continue; work.Response.RedirectAndAbort(newUrl); } this.InvokeNextWorker(work, filters, thisFilterIndex); }
/// <summary> /// Translates the named content into desired language trying to infer language from work context/locality/session. /// The search is first done in this portal then in inherited portals. /// Returns an empty string if no translation is possible /// </summary> public virtual string TranslateContent(string contentKey, string isoLang = null, WorkContext work = null) { if (isoLang.IsNullOrWhiteSpace()) isoLang = GetLanguageISOCode(work); string result; var portal = this; while(portal!=null) { var content = portal.m_LocalizableContent; if (content.TryGetValue(contentKey+"_"+isoLang, out result)) return result; if (!isoLang.EqualsOrdIgnoreCase(portal.DefaultLanguageISOCode)) { if (content.TryGetValue(contentKey+"_"+portal.DefaultLanguageISOCode, out result)) return result; } if (content.TryGetValue(contentKey, out result)) return result; portal = portal.Parent; } return string.Empty; }
protected virtual bool Check_UserHosts(WorkContext work) { if (m_UserHosts==null) return true; return m_UserHosts.Any(uh=> work.Request.UserHostName.IndexOf(uh, StringComparison.InvariantCultureIgnoreCase)>=0); }
protected virtual bool Check_Ports(WorkContext work) { if (m_Ports==null) return true; return m_Ports.Any(p=>p.Equals(work.Request.Url.Port.ToString(), StringComparison.Ordinal)); }
protected virtual bool Check_Methods(WorkContext work) { if (m_Methods==null) return true; return m_Methods.Any(m => m.Equals(work.Request.HttpMethod, StringComparison.OrdinalIgnoreCase)); }
protected virtual bool Check_IsLocal(WorkContext work) { if (!m_IsLocal.HasValue) return true; return work.Request.IsLocal == m_IsLocal; }
/// <summary> /// Translates the named content into desired language trying to infer language from work context/locality/session. /// The search is first done in this portal then in inherited portals. /// Returns an empty string if no translation is possible /// </summary> public virtual string TranslateContent(string contentKey, string isoLang = null, WorkContext work = null) { if (isoLang.IsNullOrWhiteSpace()) { isoLang = GetLanguageISOCode(work); } string result; var portal = this; while (portal != null) { var content = portal.m_LocalizableContent; if (content.TryGetValue(contentKey + "_" + isoLang, out result)) { return(result); } if (!isoLang.EqualsOrdIgnoreCase(portal.DefaultLanguageISOCode)) { if (content.TryGetValue(contentKey + "_" + portal.DefaultLanguageISOCode, out result)) { return(result); } } if (content.TryGetValue(contentKey, out result)) { return(result); } portal = portal.Parent; } return(string.Empty); }
/// <summary> /// Tries to determine session/work context lang and returns it or DefaultLanguageISOCode /// </summary> public virtual string GetLanguageISOCode(WorkContext work = null) { string lang = null; if (work==null) work = ExecutionContext.Request as WorkContext; if (work==null) { var session = ExecutionContext.Session; if (session!=null) lang = session.LanguageISOCode; } else { // 9/13/2016 OGee session can be exists but not acquired work.NeedsSession(onlyExisting: true); var session = work.Session; if (session!=null) lang = session.LanguageISOCode; if (lang.IsNullOrWhiteSpace() && work.GeoEntity!=null && work.GeoEntity.Location.HasValue) { var country = work.GeoEntity.CountryISOName; lang = CountryISOCodeToLanguageISOCode(country); } } return lang.IsNullOrWhiteSpace() ? this.DefaultLanguageISOCode : lang; }
internal Response(WorkContext work, HttpListenerResponse netResponse) { Work = work; m_NetResponse = netResponse; m_NetResponse.Headers[HttpResponseHeader.Server] = Work.Server.Name; }
/// <summary> /// Override to handle the work - i.e. render a template page or call MVC controller method. /// Note: This method is re-entrant by multiple threads /// </summary> protected abstract void DoHandleWork(WorkContext work);
/// <summary> /// Handles processing exception - this implementation uses server-wide behavior. /// All parameters except ERROR can be null - which indicates error that happened during WorkContext dispose /// </summary> public virtual void HandleException(WorkContext work, WorkFilter filter, WorkHandler handler, Exception error) { ComponentDirector.HandleException(work, filter, handler, error); }
/// <summary> /// Finds the most appropriate work handler to do the work. /// The default implementation finds first handler with matching URI pattern or null /// </summary> public virtual WorkHandler GetWorkHandler(WorkContext work) { return(m_Handlers.OrderedValues.FirstOrDefault(handler => handler.MakeMatch(work))); }
/// <summary> /// Handles the work - first involes all filters then calls HandleWork to do actual processing /// Note: This method is re-entrant by multiple threads /// </summary> public void FilterAndHandleWork(WorkContext work) { var filters = m_Filters.OrderedValues.ToList().AsReadOnly();//captures context var filter = filters.FirstOrDefault(); if (filter!=null) filter.FilterWork(work, filters, 0); else HandleWork(work); }
/// <summary> /// Returns true when the particular work request matches the pattern match of this handler. /// Also sets the WorkHandler's MatchedVars property filled with matched values /// </summary> public virtual bool MakeMatch(WorkContext work) { foreach(var match in m_Matches.OrderedValues) { var matched = match.Make(work); if (matched!=null) { work.___SetWorkMatch(match, matched); return true; } } return false; }
/// <summary> /// Override to filter the work - i.e. extract some security name from cookies and check access, turn exception in error page etc. /// Note: This method is re-entrant by multiple threads /// </summary> /// <param name="work">Work context</param> /// <param name="filters"> /// The filters that participated in a call. /// Note the Dipatcher.Filters may yield different results as it may change with time, whereas this parameter captures all filters during the call start /// </param> /// <param name="thisFilterIndex"> /// The index of THIS filter in filters /// </param> public void FilterWork(WorkContext work, IList<WorkFilter> filters, int thisFilterIndex) { try { DoFilterWork(work, filters, thisFilterIndex); } catch(Exception error) { work.LastError = error; throw new FilterPipelineException(this, error); } }
protected virtual bool Check_Hosts(WorkContext work) { if (m_Hosts==null) return true; return m_Hosts.Any(h=>h.Equals(work.Request.Url.Host, StringComparison.OrdinalIgnoreCase)); }
/// <summary> /// Override to filter the work - i.e. extract some security name from cookies and check access, turn exception in error page etc. /// Note: This method is re-entrant by multiple threads. Do not forget to call InvokeNextWorker() to continue request processing, otherwise the work will /// not be handled (which may be a desired behavior) /// </summary> /// <param name="work">Work context</param> /// <param name="filters"> /// The filters that participated in a call. /// Note the Dipatcher.Filters may yield different results as it may change with time, whereas this parameter captures all filters during the call start /// </param> /// <param name="thisFilterIndex"> /// The index of THIS filter in filters /// </param> protected abstract void DoFilterWork(WorkContext work, IList<WorkFilter> filters, int thisFilterIndex);
protected virtual bool Check_IsSocialNetBot(WorkContext work) { if (!m_IsSocialNetBot.HasValue) return true; var isBot = Web.Social.SocialNetwork.IsAnySocialNetBotUserAgent(work.Request.UserAgent); return m_IsSocialNetBot == isBot; }
/// <summary> /// Invokes next processing body be it the next filter or handler (when all filters are iterated through). /// The filter implementors must call this method to pass WorkContext processing along the line. /// Does nothing if work is Aborted or Handled /// </summary> protected void InvokeNextWorker(WorkContext work, IList<WorkFilter> filters, int thisFilterIndex) { if (work==null) return; if (work.Aborted || work.Handled) return; var idxNext = thisFilterIndex+1; if (idxNext<filters.Count) { filters[idxNext].FilterWork(work, filters, idxNext); } else { WorkHandler handler = m_Handler; if (handler!=null)//if we are under Handler already then call the handler directly handler.HandleWork(work); else //if we are under dispatcher then call dipatcher to locate and invoke the matching handler m_Dispatcher.InvokeHandler(work, out handler); } }
protected virtual bool Check_Permissions(WorkContext work) { if (m_Permissions==null) return true; var failed = m_Permissions.FirstOrDefault(prm => !prm.Check(work.Session)); return failed == null; }
/// <summary> /// Decides whether the specified WorkContext makes the match per this instance and if it does, returns the match variables. /// Returns null if match was not made /// </summary> public virtual JSONDataMap Make(WorkContext work) { if ( !Check_Methods(work) || !Check_AcceptTypes(work) || !Check_ContentTypes(work) || !Check_IsLocal(work) || !Check_Hosts(work) || !Check_Ports(work) || !Check_Schemes(work) || !Check_UserAgents(work)|| !Check_UserHosts(work) || !Check_Permissions(work) || !Check_Cookies(work) || !Check_AbsentCookies(work) || !Check_IsSocialNetBot(work) || !Check_Headers(work) || !Check_ApiVersions(work) ) return null; JSONDataMap result = null; if (m_PathPattern!=null) { result = m_PathPattern.MatchURIPath(work.Request.Url); if (result==null) return null; } if (m_NotPathPattern!=null) { if (m_NotPathPattern.MatchURIPath(work.Request.Url)!=null) return null; } if (!Check_VariablesAndGetValues(work, ref result)) return null; return result ?? new JSONDataMap(false); }
protected virtual bool Check_Schemes(WorkContext work) { if (m_Schemes==null) return true; return m_Schemes.Any(s=>s.Equals(work.Request.Url.Scheme, StringComparison.OrdinalIgnoreCase)); }
protected virtual bool Check_AcceptTypes(WorkContext work) { if (m_AcceptJson) { if (!work.RequestedJSON) return false; } if (m_AcceptTypes==null) return true; var atps = work.Request.AcceptTypes; if (atps==null || atps.Length==0) return false; var found = false; foreach(var at in m_AcceptTypes) if (atps.Any(t=>at.Equals(t, StringComparison.OrdinalIgnoreCase))) { found = true; break; } return found; }
protected virtual bool Check_VariablesAndGetValues(WorkContext work, ref JSONDataMap result) { if (m_Variables.Count==0) return true; result = result ?? new JSONDataMap(false); foreach(var cvar in m_Variables) { if (cvar.QueryName==Variable.QUERY_NAME_WC) { foreach(var qk in work.Request.QueryString.AllKeys) if (qk.IsNotNullOrWhiteSpace())//20150528 DKh fixed: ?a=1&b result[qk] = work.Request.QueryString[qk]; continue; } var qv = cvar.QueryName.IsNotNullOrWhiteSpace() ? work.Request.QueryString[cvar.QueryName] : string.Empty; if (qv.IsNullOrWhiteSpace()) qv = cvar.Default ?? string.Empty; result[cvar.Name] = qv; if (cvar.MatchEquals.IsNotNullOrWhiteSpace()) if (!cvar.MatchEquals.Equals(qv, cvar.MatchCaseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase)) return false; if (cvar.MatchContains.IsNotNullOrWhiteSpace()) if (qv.IndexOf(cvar.MatchContains, cvar.MatchCaseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase)<0) return false; } return true; }
protected virtual bool Check_ApiVersions(WorkContext work) { if (!m_ApiMinVer.HasValue && !m_ApiMaxVer.HasValue) return true; var hdr = work.Request.Headers[SysConsts.HEADER_API_VERSION]; if (hdr.IsNullOrWhiteSpace()) return false; int v; if (!Int32.TryParse(hdr, out v)) return false; if (m_ApiMinVer.HasValue && m_ApiMinVer.Value>v) return false; if (m_ApiMaxVer.HasValue && m_ApiMaxVer.Value<v) return false; return true; }
/// <summary> /// Tries to determine session/work context lang and returns it or DefaultLanguageISOCode /// </summary> public virtual string GetLanguageISOCode(WorkContext work = null) { string lang = null; if (work==null) work = ExecutionContext.Request as WorkContext; if (work==null) { var session = ExecutionContext.Session; if (session!=null) lang = session.LanguageISOCode; } else { var session = work.Session; if (session!=null) lang = session.LanguageISOCode; if (lang.IsNullOrWhiteSpace() && work.GeoEntity!=null && work.GeoEntity.Location.HasValue) { var country = work.GeoEntity.Location.Value.CountryISOName.Value; lang = CountryISOCodeToLanguageISOCode(country); } } return lang.IsNullOrWhiteSpace() ? this.DefaultLanguageISOCode : lang; }
protected virtual bool Check_ContentTypes(WorkContext work) { if (m_ContentTypes==null) return true; var ct = work.Request.ContentType; if (ct.IsNullOrWhiteSpace()) return false; return m_ContentTypes.Any(t=>ct.Equals(t, StringComparison.OrdinalIgnoreCase)); }
/// <summary> /// Handles processing exception by calling ErrorFilter.HandleException(work, error). /// All parameters except ERROR can be null - which indicates error that happened during WorkContext dispose /// </summary> public virtual void HandleException(WorkContext work, WorkFilter filter, WorkHandler handler, Exception error) { try { if (m_InstrumentationEnabled) Interlocked.Increment(ref m_Stat_ServerHandleException); //work may be null (when WorkContext is already disposed) if (work!=null) ErrorFilter.HandleException(work, error, m_ErrorShowDumpMatches, m_ErrorLogMatches); else Log(MessageType.Error, StringConsts.SERVER_DEFAULT_ERROR_WC_NULL_ERROR + error.ToMessageWithType(), "HandleException()", error); } catch(Exception error2) { if (m_LogHandleExceptionErrors) try { Log(MessageType.Error, StringConsts.SERVER_DEFAULT_ERROR_HANDLER_ERROR + error2.ToMessageWithType(), "HandleException.catch()", error2, pars: new { OriginalError = error.ToMessageWithType() }.ToJSON() ); } catch{} } }
protected virtual bool Check_Cookies(WorkContext work) { if (m_Cookies==null) return true; foreach(var pair in m_Cookies) { var cookie = work.Request.Cookies[pair.Name]; if (cookie==null) continue; if (string.Equals( cookie.Value, pair.Value, StringComparison.InvariantCultureIgnoreCase)) return true; } return false; }
/// <summary> /// Handles the work - i.e. renders a template page or calls MVC controller method. /// This method does not pass through handler's filters /// Note: This method is re-entrant by multiple threads /// </summary> public void HandleWork(WorkContext work) { try { work.m_Handler = this; DoHandleWork(work); } finally { work.m_Handled = true; } }
protected virtual bool Check_Headers(WorkContext work) { if (m_Headers==null) return true; foreach(var pair in m_Headers) if (string.Equals( work.Request.Headers[pair.Name], pair.Value, StringComparison.InvariantCultureIgnoreCase)) return true; return false; }
/// <summary> /// Override to filter the work - i.e. extract some security name from cookies and check access, turn exception in error page etc. /// Note: This method is re-entrant by multiple threads. Do not forget to call InvokeNextWorker() to continue request processing, otherwise the work will /// not be handled (which may be a desired behavior) /// </summary> /// <param name="work">Work context</param> /// <param name="filters"> /// The filters that participated in a call. /// Note the Dipatcher.Filters may yield different results as it may change with time, whereas this parameter captures all filters during the call start /// </param> /// <param name="thisFilterIndex"> /// The index of THIS filter in filters /// </param> protected abstract void DoFilterWork(WorkContext work, IList <WorkFilter> filters, int thisFilterIndex);