public object GetObject <T>(string key) { return(_cacheStorageProvider.Get <T>(BuildFullKey(key))); }
private bool TryValidateKey(string token, string akiv, bool clearText, string channel = "TheDefaultChannel") { string cacheKey; _request = HttpContext.Current.Request; try { byte[] mykey; mykey = _apiKeySettingService.EncryptionKeys(channel).ToByteArray(); byte[] myiv = Convert.FromBase64String(akiv); if (String.IsNullOrWhiteSpace(token)) { Logger.Error("Empty Token"); return(false); } string key = token; if (!clearText) { var encryptedAES = Convert.FromBase64String(token); key = DecryptStringFromBytes_Aes(encryptedAES, mykey, myiv); //key = aes.Decrypt(token, mykey, myiv); } else { var encryptedAES = EncryptStringToBytes_Aes(token, mykey, myiv); var base64EncryptedAES = Convert.ToBase64String(encryptedAES, Base64FormattingOptions.None); //var encrypted = aes.Crypt(token, mykey, myiv); if (_request.QueryString["unmask"] == "true") { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Write("Encoded: " + HttpContext.Current.Server.UrlEncode(base64EncryptedAES) + "<br/>"); HttpContext.Current.Response.Write("Clear: " + base64EncryptedAES); HttpContext.Current.Response.End(); } } // test if key has a time stamp var tokens = key.Split(':'); var pureKey = tokens[0]; int unixTimeStamp, unixTimeStampNow; unixTimeStamp = 0; unixTimeStampNow = ((Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds); if (tokens.Length >= 2) { unixTimeStamp = Convert.ToInt32(tokens[1]); } var item = CurrentSettings.ExternalApplicationList.ExternalApplications.FirstOrDefault(x => x.ApiKey.Equals(pureKey)); if (item == null) { item = DefaultApplication.ApiKey.Equals(pureKey) ? DefaultApplication : item; //this may be a test request } if (item == null) { Logger.Error("Decrypted key not found: key = " + key); return(false); } var floorLimit = Math.Abs(unixTimeStampNow - unixTimeStamp); if (item.EnableTimeStampVerification) { cacheKey = String.Concat(_shellSettings.Name, token); if (_cacheStorage.Get <object>(cacheKey) != null) { Logger.Error("cachekey duplicated: key = " + key); return(false); } if (floorLimit > ((item.Validity > 0 ? item.Validity : 5) /*minutes*/ * 60)) { Logger.Error("Timestamp validity expired: key = " + key); return(false); } else { _cacheStorage.Put(cacheKey, "", new TimeSpan(0, item.Validity > 0 ? item.Validity : 5, 0)); } } return(true); } catch (Exception ex) { Logger.Error("Exception: " + ex.Message); return(false); } }
public dynamic GetContentfromField(Dictionary <string, object> contesto, string externalUrl, string nomexlst, FieldExternalSetting settings, string contentType = "", HttpVerbOptions httpMethod = HttpVerbOptions.GET, HttpDataTypeOptions httpDataType = HttpDataTypeOptions.JSON, string tokenizedAdditionalHeadersText = "", string bodyRequest = "") { dynamic ci = null; string UrlToGet = ""; string additionalHeadersText = ""; string prefix = _shellSetting.Name + "_"; try { UrlToGet = GetUrl(contesto, externalUrl); additionalHeadersText = GetHeadersText(contesto, tokenizedAdditionalHeadersText); string chiavecache = UrlToGet; chiavecache = Path.GetInvalidFileNameChars().Aggregate(chiavecache, (current, c) => current.Replace(c.ToString(), string.Empty)); chiavecache = chiavecache.Replace('&', '_'); string chiavedate = prefix + "Date_" + chiavecache; chiavecache = prefix + chiavecache; dynamic ciDate = _cacheStorageProvider.Get <object>(chiavedate); if (settings.CacheMinute > 0) { ci = _cacheStorageProvider.Get <object>(chiavecache); } if (ci == null || ciDate == null) { string certPath; string webpagecontent; if (settings.CertificateRequired && !String.IsNullOrWhiteSpace(settings.CerticateFileName)) { certPath = String.Format(HostingEnvironment.MapPath("~/") + @"App_Data\Sites\" + _shellSetting.Name + @"\ExternalFields\{0}", settings.CerticateFileName); if (File.Exists(certPath)) { webpagecontent = GetHttpPage(UrlToGet, httpMethod, httpDataType, additionalHeadersText, bodyRequest, certPath, settings.CertificatePrivateKey.DecryptString(_shellSetting.EncryptionKey)).Trim(); } else { throw new Exception(String.Format("File \"{0}\" not found! Upload certificate via FTP.", certPath)); } } else { if (settings.DataType == OriginData.Executable) { string filename = HostingEnvironment.MapPath("~/") + @"App_Code\" + externalUrl.Substring(0, externalUrl.IndexOf(".exe") + 4); if (!File.Exists(filename)) { throw new Exception(String.Format("File \"{0}\" not found!", filename)); } var tmptokenizedzedUrl = _tokenizer.Replace(externalUrl, contesto); var StartInfo = new ProcessStartInfo { FileName = filename, Arguments = tmptokenizedzedUrl.Substring(tmptokenizedzedUrl.IndexOf(".exe") + 5), UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true, StandardOutputEncoding = Encoding.UTF8 }; var versionInfo = FileVersionInfo.GetVersionInfo(filename); if (versionInfo.CompanyName != "Laser Group") { throw new Exception(string.Format("ExternalExe {0} has not correct CompanyName", filename)); } else { using (var proc = Process.Start(StartInfo)) { webpagecontent = proc.StandardOutput.ReadToEnd(); string err = proc.StandardError.ReadToEnd(); if (!string.IsNullOrEmpty(err)) { Logger.Error(string.Format("ExternalExe {0} : {1}", externalUrl, err)); } proc.WaitForExit(); }; } } else { webpagecontent = GetHttpPage(UrlToGet, httpMethod, httpDataType, additionalHeadersText, bodyRequest).Trim(); } } if (!webpagecontent.StartsWith("<")) { if (webpagecontent.StartsWith("[")) { webpagecontent = String.Concat("{\"", nomexlst, "List", "\":", webpagecontent, "}"); } if (webpagecontent.Trim() == "") { // fix json vuoto webpagecontent = "{}"; } JObject jsonObject = JObject.Parse(webpagecontent); JObject newJsonObject = new JObject(); newJsonObject = jsonflusher(jsonObject); webpagecontent = newJsonObject.ToString(); XmlDocument newdoc = new XmlDocument(); newdoc = JsonConvert.DeserializeXmlNode(webpagecontent, "root"); correggiXML(newdoc); webpagecontent = newdoc.InnerXml; } // fix json vuoto if (webpagecontent == "<root />") { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(webpagecontent); XmlNode xmlNode = xmlDoc.DocumentElement; xmlNode = XmlWithJsonArrayTag(xmlNode, xmlDoc); string JsonVuoto = JsonConvert.SerializeXmlNode(xmlNode); JavaScriptSerializer ser = new JavaScriptSerializer() { MaxJsonLength = Int32.MaxValue }; dynamic dynamiccontent_tmp = ser.Deserialize(JsonVuoto, typeof(object)); ci = new DynamicJsonObject(dynamiccontent_tmp as IDictionary <string, object>); } else { dynamic mycache = null; Dictionary <string, object> dvb = new Dictionary <string, object>(); if (!string.IsNullOrEmpty(settings.CacheInput)) { string inputcache = _tokenizer.Replace(settings.CacheInput, contesto); mycache = _cacheStorageProvider.Get <object>(inputcache); if (mycache == null) { if (File.Exists(String.Format(HostingEnvironment.MapPath("~/") + "App_Data/Cache/" + inputcache))) { string filecontent = File.ReadAllText(String.Format(HostingEnvironment.MapPath("~/") + "App_Data/Cache/" + inputcache)); mycache = JsonConvert.DeserializeObject(filecontent); _cacheStorageProvider.Put(inputcache, mycache); } } } if (mycache != null) { XmlDocument xml = JsonConvert.DeserializeXmlNode(JsonConvert.SerializeObject(mycache)); dvb.Add("CachedData", xml); } else { dvb.Add("CachedData", new XmlDocument()); } dvb.Add("externalUrl", UrlToGet); dvb.Add("OrchardServices", _orchardServices); ci = RazorTransform(webpagecontent.Replace(" xmlns=\"\"", ""), nomexlst, contentType, dvb); _cacheStorageProvider.Remove(chiavecache); _cacheStorageProvider.Remove(chiavedate); if (settings.CacheMinute > 0) { _cacheStorageProvider.Put(chiavecache, (object)ci); // Use TimeSpan constructor to specify: // ... Days, hours, minutes, seconds, milliseconds. _cacheStorageProvider.Put(chiavedate, new { When = DateTime.UtcNow }, new TimeSpan(0, 0, settings.CacheMinute, 0, 0)); } if (settings.CacheToFileSystem) { if (!Directory.Exists(HostingEnvironment.MapPath("~/") + "App_Data/Cache")) { Directory.CreateDirectory(HostingEnvironment.MapPath("~/") + "App_Data/Cache"); } using (StreamWriter sw = File.CreateText(String.Format(HostingEnvironment.MapPath("~/") + "App_Data/Cache/" + chiavecache))) { sw.WriteLine(JsonConvert.SerializeObject(ci));//, Jsettings));// new JsonSerializerSettings { EmptyArrayHandling = EmptyArrayHandling.Set })); } } } } } catch (Exception ex) { Logger.Error(ex, UrlToGet); throw new ExternalFieldRemoteException(); } return(ci); }
public static T Get <T>(this ICacheStorageProvider provider, string key) { return((T)provider.Get <T>(key)); }