From 8a105efe126e577d66690a37e87e95e620941cbf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=A1s=20Cardelino?= Date: Mon, 9 Nov 2020 18:43:49 -0300 Subject: [PATCH 1/2] Unify criteria for auto adding cache busting Unified the criteria used in Java standard classes for adding a cache invalidation token for cache busting of static resources --- .../GxClasses/Core/GXApplication.cs | 419 ++++++++++-------- .../GxClasses/Middleware/GXHttp.cs | 163 ++++--- 2 files changed, 304 insertions(+), 278 deletions(-) diff --git a/dotnet/src/dotnetframework/GxClasses/Core/GXApplication.cs b/dotnet/src/dotnetframework/GxClasses/Core/GXApplication.cs index 1b0ac5b8c..45947e802 100644 --- a/dotnet/src/dotnetframework/GxClasses/Core/GXApplication.cs +++ b/dotnet/src/dotnetframework/GxClasses/Core/GXApplication.cs @@ -142,7 +142,7 @@ public interface IGxContext byte DeleteFile(string fileName); byte FileExists(string fileName); string GetDynUrl(); - + int GetSoapErr(); string GetSoapErrMsg(); bool isRemoteGXDB(); @@ -199,7 +199,7 @@ public interface IGxContext void DoAjaxRefreshForm(); void DoAjaxRefreshCmp(String sPrefix); #if !NETCORE - void DoAjaxLoad(int SId, GXWebRow row); + void DoAjaxLoad(int SId, GXWebRow row); #endif void DoAjaxAddLines(int SId, int lines); void DoAjaxSetFocus(string ControlName); @@ -261,12 +261,14 @@ public interface IGxContext String getJSONResponse(); LocalUtil localUtil { get; } IGxSession GetSession(); - CookieContainer GetCookieContainer(string url, bool includeCookies=true); + CookieContainer GetCookieContainer(string url, bool includeCookies = true); bool WillRedirect(); GXSOAPContext SoapContext { get; set; } #if NETCORE void UpdateSessionCookieContainer(); #endif + string GetCacheInvalidationToken(); + string GetURLBuildNumber(string styleSheet, string urlBuildNumber); } [Serializable] public class GxContext : IGxContext @@ -359,6 +361,8 @@ public class GxContext : IGxContext private const string _webAppManifestFileName = "manifest.json"; private bool? _isWebAppManifestDefined = null; + private static string CACHE_INVALIDATION_TOKEN; + private bool IsServiceWorkerDefined { get @@ -434,7 +438,7 @@ public void UpdateSessionCookieContainer() IGxSession tempStorage = GetSession(); tempStorage.SetObject(COOKIE_CONTAINER, cookieContainers); } - public CookieContainer GetCookieContainer(string url, bool includeCookies=true) + public CookieContainer GetCookieContainer(string url, bool includeCookies = true) { try { @@ -456,12 +460,12 @@ public CookieContainer GetCookieContainer(string url, bool includeCookies=true) container = new CookieContainer(); cookieContainers[domain] = container; } - return container; + return container; } catch (Exception ex) { GXLogging.Debug(log, ex, "GetCookieContainer error url:", url); - + } return new CookieContainer(); } @@ -473,19 +477,19 @@ static public GxContext Current get { #if !NETCORE - if (HttpContext.Current != null) - { - - GxContext currCtx = (GxContext)HttpContext.Current.Items["CURRENT_GX_CONTEXT"]; - if (currCtx != null) - return currCtx; - } - else - { - - return _currentGxContext; - } - return null; + if (HttpContext.Current != null) + { + + GxContext currCtx = (GxContext)HttpContext.Current.Items["CURRENT_GX_CONTEXT"]; + if (currCtx != null) + return currCtx; + } + else + { + + return _currentGxContext; + } + return null; #else return _currentGxContext; #endif @@ -494,11 +498,11 @@ static public GxContext Current static void setContext(GxContext ctx) { #if !NETCORE - if (HttpContext.Current != null) - HttpContext.Current.Items["CURRENT_GX_CONTEXT"] = ctx; - else + if (HttpContext.Current != null) + HttpContext.Current.Items["CURRENT_GX_CONTEXT"] = ctx; + else #endif - _currentGxContext = ctx; + _currentGxContext = ctx; } public LocalUtil localUtil @@ -559,7 +563,7 @@ public void setWebReturnParmsMetadata(Object[] retParmsMetadata) { this.returnParmsMetadata = retParmsMetadata; } - public static string GetHttpRequestPostedFileType(HttpContext httpContext, string varName) + public static string GetHttpRequestPostedFileType(HttpContext httpContext, string varName) { try { @@ -734,7 +738,7 @@ public void DisableSpaRequest() } private StringCollection deferredFragments = new StringCollection(); - private StringCollection javascriptSources = new StringCollection(); + private StringCollection javascriptSources = new StringCollection(); private StringCollection styleSheets = new StringCollection(); private HashSet deferredJavascriptSources = new HashSet(); @@ -761,22 +765,24 @@ public void AddDeferredFrags() public void AddJavascriptSource(string jsSrc, string urlBuildNumber, bool userDefined, bool isInlined) { if (!string.IsNullOrWhiteSpace(jsSrc) && !JavascriptSourceAdded(jsSrc)) - { + { javascriptSources.Add(jsSrc); - string queryString = urlBuildNumber; + string queryString = GetURLBuildNumber(jsSrc, urlBuildNumber); string attributes = ""; if (userDefined) { queryString = ""; attributes = "data-gx-external-script"; } - string fragment = ""; - if (isAjaxRequest() || isInlined || jsSrc == "jquery.js" || jsSrc == "gxcore.js") { - WriteHtmlText(fragment); - } - else { - deferredFragments.Add(fragment); - } + string fragment = ""; + if (isAjaxRequest() || isInlined || jsSrc == "jquery.js" || jsSrc == "gxcore.js") + { + WriteHtmlText(fragment); + } + else + { + deferredFragments.Add(fragment); + } // After including jQuery, include all the deferred Javascript files if (jsSrc == "jquery.js") @@ -815,6 +821,35 @@ public void AddStyleSheetFile(string styleSheet) styleSheets.Add(styleSheet); } + public string GetURLBuildNumber(string styleSheet, string urlBuildNumber) + { + if (string.IsNullOrEmpty(urlBuildNumber) && !PathUtil.IsAbsoluteUrl(styleSheet)) + { + return "?" + GetCacheInvalidationToken(); + } + else + { + return urlBuildNumber; + } + } + + public string GetCacheInvalidationToken() + { + if (String.IsNullOrEmpty(CACHE_INVALIDATION_TOKEN)) + { + string token; + if (Config.GetValueOf("CACHE_INVALIDATION_TOKEN", out token)) + { + CACHE_INVALIDATION_TOKEN = token; + } + else + { + CACHE_INVALIDATION_TOKEN = Math.Truncate(NumberUtil.Random() * 1000000).ToString(); + } + } + return CACHE_INVALIDATION_TOKEN; + } + public bool StyleSheetAdded(string styleSheet) { return styleSheets.Contains(styleSheet); @@ -851,7 +886,7 @@ public void StatusMessage(string message) #if NETCORE ILog statusLog = log4net.LogManager.GetLogger(frame.GetMethod().DeclaringType); #else - ILog statusLog = log4net.LogManager.GetLogger(frame.GetMethod().DeclaringType.FullName); + ILog statusLog = log4net.LogManager.GetLogger(frame.GetMethod().DeclaringType.FullName); #endif GXLogging.Info(statusLog, message); Console.WriteLine(message); @@ -882,7 +917,7 @@ public void SendComponentObjects() httpAjaxContext.HiddenValues.Put("GX_CMP_OBJS", httpAjaxContext.ComponentObjects); } - public void SendServerCommands() + public void SendServerCommands() { if (!isAjaxRequest() && httpAjaxContext.Commands.Count > 0) { @@ -903,7 +938,7 @@ public string GetCssProperty(string propName, string propValue) { int browserType = GetBrowserType(); -#region Align + #region Align if (string.Compare(propName, "align", true) == 0) { if (browserType == BROWSER_FIREFOX) @@ -915,7 +950,7 @@ public string GetCssProperty(string propName, string propValue) return "-khtml-" + propValue; } } -#endregion + #endregion return propValue; } @@ -961,12 +996,12 @@ private void LocalInitialize() _handle = GxUserInfo.NewHandle(); } #if !NETCORE - if (Preferences.Instrumented) - { - GxUserInfo.setProperty(_handle, GxDefaultProps.USER_NAME, Environment.UserName); - GxUserInfo.setProperty(_handle, GxDefaultProps.PGM_NAME, AppDomain.CurrentDomain.FriendlyName); - GxUserInfo.setProperty(_handle, GxDefaultProps.START_TIME, DateTime.Now.ToString()); - } + if (Preferences.Instrumented) + { + GxUserInfo.setProperty(_handle, GxDefaultProps.USER_NAME, Environment.UserName); + GxUserInfo.setProperty(_handle, GxDefaultProps.PGM_NAME, AppDomain.CurrentDomain.FriendlyName); + GxUserInfo.setProperty(_handle, GxDefaultProps.START_TIME, DateTime.Now.ToString()); + } #endif GX_msglist = new msglist(); Config.LoadConfiguration(); @@ -984,7 +1019,7 @@ public bool IsMultipartRequest #if NETCORE return MultipartRequestHelper.IsMultipartContentType(this.HttpContext.Request.ContentType); #else - return this.HttpContext.Request.Files.Count > 0; + return this.HttpContext.Request.Files.Count > 0; #endif else @@ -1011,10 +1046,10 @@ public HttpContext HttpContext get { #if !NETCORE - if (_HttpContext == null && HttpContext.Current != null) - { - HttpContext = HttpContext.Current; - } + if (_HttpContext == null && HttpContext.Current != null) + { + HttpContext = HttpContext.Current; + } #endif return _HttpContext; } @@ -1370,12 +1405,12 @@ public string ServerVersion(string dataSource) IGxDataStore dstore = GetDataStore(dataSource); return (dstore.Version); } - public string DataBaseName(string dataSource) - { - IGxDataStore dstore = GetDataStore(dataSource); - return dstore.Connection.DatabaseName; - } - public bool isRemoteGXDB() + public string DataBaseName(string dataSource) + { + IGxDataStore dstore = GetDataStore(dataSource); + return dstore.Connection.DatabaseName; + } + public bool isRemoteGXDB() { return Preferences.Remote ? !Preferences.RemoteLocation.Equals(_currentLocation) : false; } @@ -1426,7 +1461,7 @@ static public string StdClassesVersion() } return Assembly.GetAssembly(typeof(GxContext)).GetName().Version.ToString(); } - + public MessageQueueTransaction MQTransaction { get { return _mqTransaction; } @@ -1501,7 +1536,7 @@ internal static string RemoveInternalSuffixes(string query) idx = query.IndexOf("gx-no-cache="); if (idx >= 0) { - idx = (idx > 0) ? idx - 1 : idx; + idx = (idx > 0) ? idx - 1 : idx; query = query.Substring(0, idx); } return query; @@ -1552,15 +1587,16 @@ public GXNavigationHelper GetNavigationHelper() return helper; } } - public T ReadSessionKey(string key) where T:class + public T ReadSessionKey(string key) where T : class { - try - { - if (httpAjaxContext != null && httpAjaxContext.SessionType == SessionType.NO_SESSION) - return default(T); - else if (_HttpContext != null && _HttpContext.Session != null) { + try + { + if (httpAjaxContext != null && httpAjaxContext.SessionType == SessionType.NO_SESSION) + return default(T); + else if (_HttpContext != null && _HttpContext.Session != null) + { #if !NETCORE - return (T)_HttpContext.Session[key]; + return (T)_HttpContext.Session[key]; #else string value = _HttpContext.Session.GetString(key); if (value != null) @@ -1570,41 +1606,41 @@ public T ReadSessionKey(string key) where T:class #endif } return default(T); - } - catch (InvalidOperationException) //Session has not been configured for this application or request. IE 11 - { - return default(T); - } - } - public bool WriteSessionKey(string key, T value) where T:class + } + catch (InvalidOperationException) //Session has not been configured for this application or request. IE 11 + { + return default(T); + } + } + public bool WriteSessionKey(string key, T value) where T : class { - try - { - if (HttpContext != null && _HttpContext.Session != null && httpAjaxContext != null && httpAjaxContext.SessionType != SessionType.NO_SESSION) - { + try + { + if (HttpContext != null && _HttpContext.Session != null && httpAjaxContext != null && httpAjaxContext.SessionType != SessionType.NO_SESSION) + { #if !NETCORE - HttpContext.Session[key] = value; + HttpContext.Session[key] = value; #else if (!_HttpContext.Response.HasStarted) { HttpContext.Session.SetString(key, (value != null ? JSONHelper.Serialize(value) : string.Empty)); } #endif - return true; - } - else - { - return false; - } - } - catch (InvalidOperationException) //Session has not been configured for this application or request. IE 11 - { - return false; - } - } + return true; + } + else + { + return false; + } + } + catch (InvalidOperationException) //Session has not been configured for this application or request. IE 11 + { + return false; + } + } - internal string GetRequestNavUrl() + internal string GetRequestNavUrl() { string sUrl = string.Empty; if (isAjaxRequest() && _HttpContext != null) @@ -1864,7 +1900,7 @@ public int GetBrowserType() { return BROWSER_UP; } - + else if (userAgent.ToUpper().IndexOf("SAFARI") != -1) { return BROWSER_SAFARI; @@ -1880,7 +1916,7 @@ public int GetBrowserType() else if (Regex.IsMatch(userAgent, "Googlebot|AhrefsBot|bingbot|MJ12bot", RegexOptions.IgnoreCase)) { return BROWSER_INDEXBOT; - } + } } return BROWSER_OTHER; } @@ -2001,7 +2037,8 @@ public void WriteHtmlText(string Content) httpAjaxContext.writeAjaxContent(Content); } - else { + else + { OutputWriter.Write(Content); } } @@ -2147,12 +2184,12 @@ public string GetCookie(string name) if (cookie != null && cookie.Value != null) { #if NETCORE - if (name==GxHttpCookie.GX_SESSION_ID && cookie.Value.Contains('+')) //Cookie compatibility with java, cookie value is already decoded - cookieVal = cookie.Value; - else - cookieVal = HttpUtility.UrlDecode(cookie.Value); + if (name == GxHttpCookie.GX_SESSION_ID && cookie.Value.Contains('+')) //Cookie compatibility with java, cookie value is already decoded + cookieVal = cookie.Value; + else + cookieVal = HttpUtility.UrlDecode(cookie.Value); #else - cookieVal = HttpUtility.UrlDecode(cookie.Value); + cookieVal = HttpUtility.UrlDecode(cookie.Value); #endif } return cookieVal; @@ -2166,7 +2203,7 @@ private HttpCookie TryGetCookie(HttpCookieCollection cookieColl, string name) } return null; } - public short SetCookie(string name, string cookieValue, string path, DateTime expires, string domain, int secure) + public short SetCookie(string name, string cookieValue, string path, DateTime expires, string domain, int secure) { return SetCookie(name, cookieValue, path, expires, domain, secure, GeneXus.Http.Server.GxHttpCookie.HttpOnlyDefault()); @@ -2201,33 +2238,33 @@ public short SetCookie(string name, string cookieValue, string path, DateTime ex if (!expires.Equals(DateTimeUtil.NullDate())) cookieOptions.Expires = DateTime.SpecifyKind(cookie.Expires, DateTimeKind.Utc); - _HttpContext.Response.Cookies.Append(name, cookie.Value, cookieOptions); + _HttpContext.Response.Cookies.Append(name, cookie.Value, cookieOptions); localCookies[name] = cookie; #else - if (_HttpContext.Response.Cookies.Get(name) != null) - { + if (_HttpContext.Response.Cookies.Get(name) != null) + { - try - { - _HttpContext.Response.Cookies.Set(cookie); + try + { + _HttpContext.Response.Cookies.Set(cookie); } - catch (HttpException) { } - localCookies.Set(cookie); - } - else - { + catch (HttpException) { } + localCookies.Set(cookie); + } + else + { - try - { - _HttpContext.Response.Cookies.Add(cookie); - } - catch (HttpException) { } - localCookies.Add(cookie); - } + try + { + _HttpContext.Response.Cookies.Add(cookie); + } + catch (HttpException) { } + localCookies.Add(cookie); + } #endif return 0; } - public byte ResponseContentType(String sContentType) + public byte ResponseContentType(String sContentType) { if (_HttpContext == null || this.GetWrapped()) return 0; @@ -2266,33 +2303,33 @@ private void SetCustomHttpHeader(string name, string value) _HttpContext.Response.AppendHeader(name, value); #if !NETCORE - switch (name.ToUpper()) - { - case "CACHE-CONTROL": - var Cache = _HttpContext.Response.Cache; - string[] values = value.Split(','); - foreach (var v in values) - { - switch (v.Trim().ToUpper()) - { - case "PUBLIC": - Cache.SetCacheability(HttpCacheability.Public); - break; - case "PRIVATE": - Cache.SetCacheability(HttpCacheability.Private); - break; - case "NO-CACHE": - Cache.SetCacheability(HttpCacheability.NoCache); - break; + switch (name.ToUpper()) + { + case "CACHE-CONTROL": + var Cache = _HttpContext.Response.Cache; + string[] values = value.Split(','); + foreach (var v in values) + { + switch (v.Trim().ToUpper()) + { + case "PUBLIC": + Cache.SetCacheability(HttpCacheability.Public); + break; + case "PRIVATE": + Cache.SetCacheability(HttpCacheability.Private); + break; + case "NO-CACHE": + Cache.SetCacheability(HttpCacheability.NoCache); + break; case "NO-STORE": Cache.AppendCacheExtension("no-store, must-revalidate"); break; default: - break; - } - } - break; - } + break; + } + } + break; + } #else switch (name.ToUpper()) { @@ -2345,10 +2382,10 @@ private void DoRedirect(string jumpUrl) private void DoForward(string jumpUrl) { #if !NETCORE - _HttpContext.Items["gx_webcall_method"] = "forward"; - _HttpContext.RewritePath(jumpUrl); - IHttpHandler handler = new GeneXus.HttpHandlerFactory.HandlerFactory().GetHandler(_HttpContext, "GET", jumpUrl, jumpUrl); - handler.ProcessRequest(_HttpContext); + _HttpContext.Items["gx_webcall_method"] = "forward"; + _HttpContext.RewritePath(jumpUrl); + IHttpHandler handler = new GeneXus.HttpHandlerFactory.HandlerFactory().GetHandler(_HttpContext, "GET", jumpUrl, jumpUrl); + handler.ProcessRequest(_HttpContext); #endif } protected void httpRedirect(String jumpUrl) @@ -2366,7 +2403,7 @@ protected void httpRedirect(String jumpUrl) } catch (Exception) { - + DoRedirect(jumpUrl); } } @@ -2521,14 +2558,14 @@ public void DoAjaxRefreshCmp(String sPrefix) httpAjaxContext.appendAjaxCommand("cmp_refresh", sPrefix); } #if !NETCORE - public void DoAjaxLoad(int SId, GXWebRow row) - { - JObject JSONRow = new JObject(); - JSONRow.Put("grid", SId); - JSONRow.Put("props", row.parentGrid.GetJSONObject()); - JSONRow.Put("values", row.parentGrid.GetValues()); - httpAjaxContext.appendLoadData(SId, JSONRow); - } + public void DoAjaxLoad(int SId, GXWebRow row) + { + JObject JSONRow = new JObject(); + JSONRow.Put("grid", SId); + JSONRow.Put("props", row.parentGrid.GetJSONObject()); + JSONRow.Put("values", row.parentGrid.GetValues()); + httpAjaxContext.appendLoadData(SId, JSONRow); + } #endif public void DoAjaxAddLines(int SId, int lines) { @@ -2571,7 +2608,7 @@ public void SendFinalJSONResponse(string json) _HttpContext.Response.Write(json); if (isMultipartResponse) _HttpContext.Response.Write("'/>"); - } + } public string BuildHTMLColor(int lColor) { @@ -2581,10 +2618,10 @@ public string BuildHTMLColor(int lColor) float getHTMLVersion() { #if !NETCORE - if (_HttpContext.Request.Browser.MajorVersion >= 4 && - (_HttpContext.Request.Browser.Type.ToUpper().IndexOf("IE") > -1 || - _HttpContext.Request.Browser.Type.ToUpper().IndexOf("NS") > -1)) - return 4.0f; + if (_HttpContext.Request.Browser.MajorVersion >= 4 && + (_HttpContext.Request.Browser.Type.ToUpper().IndexOf("IE") > -1 || + _HttpContext.Request.Browser.Type.ToUpper().IndexOf("NS") > -1)) + return 4.0f; #endif return 1.0f; } @@ -2608,12 +2645,12 @@ public string GetRemoteAddress() #if NETCORE return _HttpContext.Request.Host.Host; #else - return _HttpContext.Request.UserHostAddress; + return _HttpContext.Request.UserHostAddress; #endif } catch - { - return ""; + { + return ""; } } @@ -2626,7 +2663,7 @@ public virtual string GetServerName() if (Config.GetValueOf("SERVER_NAME", out serverName)) return serverName; #if !NETCORE - serverName = _HttpContext.Request.ServerVariables["http_host"]; + serverName = _HttpContext.Request.ServerVariables["http_host"]; #endif if (String.IsNullOrEmpty(serverName)) { @@ -2680,11 +2717,11 @@ private bool RequestDefaultPort get { #if !NETCORE - try - { - return _HttpContext.Request.Url.IsDefaultPort; - } - catch + try + { + return _HttpContext.Request.Url.IsDefaultPort; + } + catch #endif { return false; @@ -2694,12 +2731,12 @@ private bool RequestDefaultPort public virtual string GetServerSchema() { try - { + { if (FrontEndHttps()) { return GXUri.UriSchemeHttps; } - return _HttpContext.Request.GetScheme(); + return _HttpContext.Request.GetScheme(); } catch { @@ -2724,7 +2761,7 @@ private bool CheckHeaderValue(String headerName, String headerValue) { string httpsHeader = _HttpContext.Request.Headers[headerName]; if (!string.IsNullOrEmpty(httpsHeader) && httpsHeader.Equals(headerValue, StringComparison.OrdinalIgnoreCase)) - { + { return true; } return false; @@ -2758,7 +2795,7 @@ public string GetPhysicalPath() { if (HttpContext != null) { - string phPath = HttpHelper.RequestPhysicalApplicationPath(_HttpContext); + string phPath = HttpHelper.RequestPhysicalApplicationPath(_HttpContext); if (phPath.EndsWith("\\") || phPath.EndsWith("/")) _physicalPath = phPath; else @@ -2769,7 +2806,7 @@ public string GetPhysicalPath() _physicalPath = ""; } } - catch(Exception ex) + catch (Exception ex) { GXLogging.Debug(log, "GetPhysicalPath error", ex); _physicalPath = ""; @@ -2782,7 +2819,7 @@ public static bool IsRestService get { #if !NETCORE - return WebOperationContext.Current != null; + return WebOperationContext.Current != null; #else return false; #endif @@ -2796,7 +2833,7 @@ public static bool IsHttpContext get { #if !NETCORE - return HttpContext.Current != null; + return HttpContext.Current != null; #else return _isHttpContext; #endif @@ -2829,7 +2866,7 @@ public static string StaticPhysicalPath() { return _physicalPath; } - + else { return Directory.GetCurrentDirectory(); @@ -2911,7 +2948,7 @@ public string ExtensionForContentType(string contentType) new string[] {"tif" , "image/tiff"}, new string[] {"tiff", "image/tiff"}, new string[] {"png" , "image/png"}, - new string[] {"png" , "image/x-png"}, + new string[] {"png" , "image/x-png"}, new string[] {"mpg" , "video/mpeg"}, new string[] {"mpeg", "video/mpeg"}, new string[] {"mov" , "video/quicktime"}, @@ -2927,12 +2964,12 @@ public string ExtensionForContentType(string contentType) new string[] {"pdf" , "application/pdf"}, new string[] {"tgz" , "application/x-compressed"}, new string[] {"zip" , "application/zip"}, - new string[] {"zip" , "application/x-zip-compressed"}, + new string[] {"zip" , "application/x-zip-compressed"}, new string[] {"tar" , "application/x-tar"}, new string[] {"rar" , "application/x-rar-compressed"}, new string[] {"gz" , "application/x-gzip"} }; - + public int GetSoapErr() { return _nSOAPErr; @@ -3075,12 +3112,12 @@ public bool ExecuteAfterConnect(String datastoreName) } public void SetProperty(string key, string value) { - if (HttpContext != null && HttpContext.Session != null) + if (HttpContext != null && HttpContext.Session != null) { GXLogging.Debug(log, "HttpContext.Session.setProperty(", key, ")=", value); - WriteSessionKey(key, value); + WriteSessionKey(key, value); } - else + else { if (_properties == null) { @@ -3093,11 +3130,11 @@ public void SetProperty(string key, string value) public string GetProperty(string key) { string property = null; - if (HttpContext != null && HttpContext.Session != null) + if (HttpContext != null && HttpContext.Session != null) { property = ReadSessionKey(key); } - else + else { if (_properties != null && _properties.Contains(key)) { @@ -3392,7 +3429,7 @@ public String GetTimeZone() public Boolean SetTimeZone(String sTZ) { - sTZ = StringUtil.RTrim(sTZ); + sTZ = StringUtil.RTrim(sTZ); Boolean ret = false; try { @@ -3434,7 +3471,7 @@ Hashtable Images string imgDir = ""; if (String.IsNullOrEmpty(dir) && _HttpContext == null) { - + int srchIx = 0; string[] paths = new string[] { ".\\", "..\\" }; bool found = false; @@ -3533,7 +3570,7 @@ public string GetImagePath(string id, string KBId, string theme) return ret; else { - GXLogging.Debug(log, "Image not found at Images.txt. Image id:", () => KBId + id + " language:" + lang + " theme:" + theme); + GXLogging.Debug(log, "Image not found at Images.txt. Image id:", () => KBId + id + " language:" + lang + " theme:" + theme); return id; } } @@ -3643,11 +3680,11 @@ static public DateTime StartupDate if (startupDate == DateTime.MinValue) { DateTime dt = DateTime.Now.ToUniversalTime(); - startupDate = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, DateTimeKind.Utc); + startupDate = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, DateTimeKind.Utc); } return startupDate; } - } + } public void SetSubmitInitialConfig(IGxContext context) { @@ -3678,7 +3715,7 @@ public bool WillRedirect() { return !String.IsNullOrEmpty(StringUtil.RTrim(wjLoc)); } -#region IGxContext Members + #region IGxContext Members private const string CLIENT_ID_HEADER = "GX_CLIENT_ID"; public string ClientID @@ -3692,7 +3729,7 @@ public string ClientID { _clientId = Guid.NewGuid().ToString(); this.SetCookie(CLIENT_ID_HEADER, _clientId, string.Empty, DateTime.MaxValue, string.Empty, 0); - } + } } return _clientId; } @@ -3707,7 +3744,7 @@ public string ClientID public GXSOAPContext SoapContext { get; set; } -#endregion + #endregion } public class GxXmlContext { diff --git a/dotnet/src/dotnetframework/GxClasses/Middleware/GXHttp.cs b/dotnet/src/dotnetframework/GxClasses/Middleware/GXHttp.cs index 9e30ebf22..2cd798925 100644 --- a/dotnet/src/dotnetframework/GxClasses/Middleware/GXHttp.cs +++ b/dotnet/src/dotnetframework/GxClasses/Middleware/GXHttp.cs @@ -67,7 +67,6 @@ public abstract class GXHttpHandler : WebControl, IHttpHandler [System.Diagnostics.CodeAnalysis.SuppressMessage("GxFxCopRules", "CR1000:EnforceThreadSafeType")] private Dictionary callTargetsByObject = new Dictionary(); #endif - private static string CACHE_INVALIDATION_TOKEN; public GXHttpHandler() { initpars(); @@ -162,7 +161,7 @@ protected object convertparm(ParameterInfo[] pars, int i, object value) ((IGxJSONSerializable)parmObj).FromJSonString(valueS); return parmObj; } - + if (parmtype.Equals(typeof(int)) && value != null) { if (string.Compare(valueS, "true", StringComparison.OrdinalIgnoreCase) == 0) @@ -211,17 +210,17 @@ private static bool IsNumericType(Type t) #if !NETCORE protected IGxContext _Context; #endif - bool _isMain; + bool _isMain; bool _isStatic; string staticContentBase; ConcurrentDictionary _namedParms = new ConcurrentDictionary(); bool useOldQueryStringFormat; - public List _params = new List(); + public List _params = new List(); private string _strParms; - int _currParameter; + int _currParameter; #if NETCORE - private GXWebRow _currentGridRow; + private GXWebRow _currentGridRow; #endif private Hashtable EventsMetadata = new Hashtable(); @@ -243,7 +242,7 @@ public void webExecuteEx(HttpContext httpContext) private bool IsFullAjaxRequest(HttpContext httpContext) { #if NETCORE - String contentType = (localHttpContext != null && localHttpContext.Request.ContentType != null) ? localHttpContext.Request.ContentType : string.Empty; + String contentType = (localHttpContext != null && localHttpContext.Request.ContentType != null) ? localHttpContext.Request.ContentType : string.Empty; #else String contentType = httpContext != null ? httpContext.Request.ContentType : string.Empty; #endif @@ -262,25 +261,25 @@ public virtual void cleanup() { } public virtual String AjaxOnSessionTimeout() { return "Ignore"; } #if NETCORE - public void DoAjaxLoad(int SId, GXWebRow row) - { - JObject JSONRow = new JObject(); - JSONRow.Put("grid", SId); - JSONRow.Put("props", row.parentGrid.GetJSONObject()); - JSONRow.Put("values", row.parentGrid.GetValues()); - context.httpAjaxContext.appendLoadData(SId, JSONRow); - } - public void ajax_sending_grid_row(GXWebRow row) - { - if (context.isAjaxCallMode()) - { - _currentGridRow = row; - } - else - { - _currentGridRow = null; - } - } + public void DoAjaxLoad(int SId, GXWebRow row) + { + JObject JSONRow = new JObject(); + JSONRow.Put("grid", SId); + JSONRow.Put("props", row.parentGrid.GetJSONObject()); + JSONRow.Put("values", row.parentGrid.GetValues()); + context.httpAjaxContext.appendLoadData(SId, JSONRow); + } + public void ajax_sending_grid_row(GXWebRow row) + { + if (context.isAjaxCallMode()) + { + _currentGridRow = row; + } + else + { + _currentGridRow = null; + } + } #endif public void ajax_rsp_clear() { @@ -301,16 +300,16 @@ public class DynAjaxEvent JArray events; GXHttpHandler targetObj; string[] eventHandlers; - bool[] eventUseInternalParms; - string cmpContext = string.Empty; - int grid; - string row; - JArray inParmsMetadata; - private HashSet inParmsMetadataHash; - bool anyError; - - private void ParseInputJSonMessage(JObject objMessage, GXHttpHandler targetObj) - { + bool[] eventUseInternalParms; + string cmpContext = string.Empty; + int grid; + string row; + JArray inParmsMetadata; + private HashSet inParmsMetadataHash; + bool anyError; + + private void ParseInputJSonMessage(JObject objMessage, GXHttpHandler targetObj) + { inParmsValues = (JArray)objMessage["parms"]; inHashValues = (JArray)objMessage["hsh"]; if (inHashValues == null) @@ -348,19 +347,19 @@ private void ParseInputJSonMessage(JObject objMessage, GXHttpHandler targetObj) if (objMessage.Contains("grids")) ParseGridsDataParms((JObject)objMessage["grids"]); if (objMessage.Contains("grid")) - grid = Convert.ToInt32(objMessage["grid"]); - else - grid = 0; - if (objMessage.Contains("row")) - row = (string)objMessage["row"]; - else - row = ""; - if (objMessage.Contains("gxstate")) - { - ParseGXStateParms((JObject)objMessage["gxstate"]); - } - if (objMessage.Contains("fullPost")) - { + grid = Convert.ToInt32(objMessage["grid"]); + else + grid = 0; + if (objMessage.Contains("row")) + row = (string)objMessage["row"]; + else + row = ""; + if (objMessage.Contains("gxstate")) + { + ParseGXStateParms((JObject)objMessage["gxstate"]); + } + if (objMessage.Contains("fullPost")) + { this.targetObj._Context.httpAjaxContext.ParseGXState((JObject)objMessage["fullPost"]); } } @@ -545,7 +544,7 @@ private void SetCollectionFieldValue(FieldInfo fieldInfo, JArray values) MethodInfo mth = fieldInfo.FieldType.GetMethod("FromJSONObject"); if (mth != null) - mth.Invoke(fieldInfo.GetValue(targetObj), new Object[] { values }); + mth.Invoke(fieldInfo.GetValue(targetObj), new Object[] { values }); } } @@ -623,7 +622,7 @@ private void SetFieldValue(FieldInfo fieldInfo, object value) else { #if NETCORE - IFormatProvider provider = CultureInfo.InvariantCulture; + IFormatProvider provider = CultureInfo.InvariantCulture; #else IFormatProvider provider = CultureInfo.CreateSpecificCulture("en-US"); #endif @@ -719,7 +718,7 @@ private object[] BeforeInvoke() foreach (object columnVal in columnValues) { string varName = $"{cmpContext}{(string)parm["fld"]}_{rowIdx.ToString(CultureInfo.InvariantCulture).PadLeft(4, '0')}{parentRow}"; - + ReadColumnVarValue(columnVal, targetObj, varName); rowIdx++; } @@ -805,7 +804,7 @@ private object[] BeforeInvoke() hash_i++; } } - if (value != null && value!= JNull.Value) + if (value != null && value != JNull.Value) { SetNullableScalarOrCollectionValue(parm, value, columnValues); } @@ -824,9 +823,9 @@ private object[] BeforeInvoke() { parm_i++; } - } + } - } + } if (grid != 0 && !String.IsNullOrEmpty(row)) { @@ -899,7 +898,7 @@ private void DoInvoke(object[] MethodParms) _ = targetObj.GetType().InvokeMember(handler, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, Type.DefaultBinder, - targetObj, (eventUseInternalParms[i] ? MethodParms : null)); + targetObj, (eventUseInternalParms[i] ? MethodParms : null)); } } } @@ -1030,7 +1029,7 @@ public bool IsSameComponent(string oldName, string newName) } else if (newName.Trim().ToLower().StartsWith(oldName.Trim().ToLower() + ".aspx")) { - + return true; } return false; @@ -1089,8 +1088,10 @@ public void AddStyleSheetFile(string styleSheet) public void AddStyleSheetFile(string styleSheet, string urlBuildNumber, bool isDeferred = false) { + urlBuildNumber = context.GetURLBuildNumber(styleSheet, urlBuildNumber); AddStyleSheetFile(styleSheet, urlBuildNumber, false, isDeferred); } + //isGxThemeHidden: true if it is the theme to be sent in GX_THEME, in that case it is not added to the GX_STYLE_FILES list, only in the hidden GX_THEME private void AddStyleSheetFile(string styleSheet, string urlBuildNumber, bool isGxThemeHidden, bool isDeferred = false) { @@ -1150,13 +1151,13 @@ public void AddThemeStyleSheetFile(String kbPrefix, String styleSheet, string ur string cssContent = ""; Boolean bHasCustomContent = FetchCustomCSS(ref cssContent); - if (bHasCustomContent && !context.StyleSheetAdded(GetPgmname())) - { + if (bHasCustomContent && !context.StyleSheetAdded(GetPgmname())) + { context.WriteHtmlTextNl(""); - context.AddStyleSheetFile(GetPgmname()); - } + context.AddStyleSheetFile(GetPgmname()); + } - string[] referencedFiles = ThemeHelper.GetThemeCssReferencedFiles(Path.GetFileNameWithoutExtension(styleSheet)); + string[] referencedFiles = ThemeHelper.GetThemeCssReferencedFiles(Path.GetFileNameWithoutExtension(styleSheet)); foreach (string file in referencedFiles) { string extension = Path.GetExtension(file); @@ -1172,19 +1173,7 @@ public void AddThemeStyleSheetFile(String kbPrefix, String styleSheet, string ur public string GetCacheInvalidationToken() { - if (String.IsNullOrEmpty(CACHE_INVALIDATION_TOKEN)) - { - string token; - if (Config.GetValueOf("CACHE_INVALIDATION_TOKEN", out token)) - { - CACHE_INVALIDATION_TOKEN = token; - } - else - { - CACHE_INVALIDATION_TOKEN = Math.Truncate(NumberUtil.Random() * 1000000).ToString(); - } - } - return CACHE_INVALIDATION_TOKEN; + return context.GetCacheInvalidationToken(); } public void AddComponentObject(string cmpCtx, string objName, bool justCreated) @@ -1289,7 +1278,7 @@ public HtmlTextWriter ControlOutputWriter get { return _Context.OutputWriter; - + } set { @@ -1343,7 +1332,7 @@ protected void exitApplication() } catch (Exception) {; } } - + } private bool IsGxAjaxRequest() @@ -1881,7 +1870,7 @@ private bool ValidSession() private bool ValidWebSession() { #if NETCORE - bool isExpired = IsFullAjaxRequest(localHttpContext) && this.AjaxOnSessionTimeout() == "Warn" && GxWebSession.IsSessionExpired(localHttpContext); + bool isExpired = IsFullAjaxRequest(localHttpContext) && this.AjaxOnSessionTimeout() == "Warn" && GxWebSession.IsSessionExpired(localHttpContext); #else bool isExpired = IsFullAjaxRequest(HttpContext.Current) && this.AjaxOnSessionTimeout() == "Warn" && GxWebSession.IsSessionExpired(localHttpContext); #endif @@ -1913,7 +1902,7 @@ private bool ValidGAMSession(bool bRedirectIfNotAuth) if (!isOK) { #if NETCORE - localHttpContext.Response.Headers[HttpHeader.AUTHENTICATE_HEADER]= HttpHelper.OatuhUnauthorizedHeader(context.GetServerName(), string.Empty, string.Empty); + localHttpContext.Response.Headers[HttpHeader.AUTHENTICATE_HEADER] = HttpHelper.OatuhUnauthorizedHeader(context.GetServerName(), string.Empty, string.Empty); #else HttpContext.Current.Response.AddHeader(HttpHeader.AUTHENTICATE_HEADER, HttpHelper.OatuhUnauthorizedHeader(context.GetServerName(), string.Empty, string.Empty)); #endif @@ -1940,7 +1929,7 @@ private bool ValidGAMSession(bool bRedirectIfNotAuth) public bool IsAuthorized(String permissionPrefix) { - + bool isOK = false; bool isPermissionOK; @@ -2153,7 +2142,7 @@ protected void LoadParameters(string value) _params.Clear(); _namedParms.Clear(); string parmValue; - + if (!string.IsNullOrEmpty(value)) { value = GxContext.RemoveInternalSuffixes(value).TrimStart('?'); @@ -2213,7 +2202,7 @@ protected void TryLoadAjaxCallParms() } } } - + public virtual string getresponse(string sGXDynURL) { return ""; @@ -2361,7 +2350,7 @@ public void gxhtml_etr() } public void flushBuffer() { - + } #if !NETCORE public string formatLink(string jumpURL) @@ -2405,17 +2394,17 @@ static public GXWebComponent getWebComponent(Object caller, string nameSpace, st String objName = CleanObjectFromUrl(name.ToLower()); GXWebComponent objComponent = null; - if (!isUrlName(objName)) + if (!isUrlName(objName)) { try { - + objComponent = (GXWebComponent)ClassLoader.GetInstance(objName, nameSpace + "." + objName, ctorParms); } catch { } try { - + if (objComponent == null) #if NETCORE objComponent = (GXWebComponent)ClassLoader.CreateInstance(Assembly.GetEntryAssembly(), nameSpace + "." + objName, ctorParms); @@ -2427,7 +2416,7 @@ static public GXWebComponent getWebComponent(Object caller, string nameSpace, st } if (objComponent == null) { - + string url = name; Object[] actualParms = null; name = ObjectSignatureFromUrl(url, ctorParms, ref actualParms); From da7a68db379f9333cc2ee3e996a8711bf71a213b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=A1s=20Cardelino?= Date: Mon, 9 Nov 2020 18:53:53 -0300 Subject: [PATCH 2/2] Improve var name --- dotnet/src/dotnetframework/GxClasses/Core/GXApplication.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dotnet/src/dotnetframework/GxClasses/Core/GXApplication.cs b/dotnet/src/dotnetframework/GxClasses/Core/GXApplication.cs index 45947e802..4e87ec418 100644 --- a/dotnet/src/dotnetframework/GxClasses/Core/GXApplication.cs +++ b/dotnet/src/dotnetframework/GxClasses/Core/GXApplication.cs @@ -268,7 +268,7 @@ public interface IGxContext void UpdateSessionCookieContainer(); #endif string GetCacheInvalidationToken(); - string GetURLBuildNumber(string styleSheet, string urlBuildNumber); + string GetURLBuildNumber(string resourcePath, string urlBuildNumber); } [Serializable] public class GxContext : IGxContext @@ -821,9 +821,9 @@ public void AddStyleSheetFile(string styleSheet) styleSheets.Add(styleSheet); } - public string GetURLBuildNumber(string styleSheet, string urlBuildNumber) + public string GetURLBuildNumber(string resourcePath, string urlBuildNumber) { - if (string.IsNullOrEmpty(urlBuildNumber) && !PathUtil.IsAbsoluteUrl(styleSheet)) + if (string.IsNullOrEmpty(urlBuildNumber) && !PathUtil.IsAbsoluteUrl(resourcePath)) { return "?" + GetCacheInvalidationToken(); }