private static void SimpleCachingDemo() { ICache cache = new InMemoryCache(); CachingPolicy cachingPolicy = CachingPolicy.CacheAll; // log SQL from all connections to the console EFTracingProviderConfiguration.LogToConsole = true; for (int i = 0; i < 3; ++i) { Console.WriteLine(); Console.WriteLine("*** Pass #{0}...", i); Console.WriteLine(); using (var context = new ExtendedDataBase()) { // set up caching context.Cache = cache; context.CachingPolicy = cachingPolicy; //cust.Orders.Load(); //context.SaveChanges(); } } Console.WriteLine(); //Console.WriteLine("*** Cache statistics: Hits:{0} Misses:{1} Hit ratio:{2}% Adds:{3} Invalidations:{4}", // cache.CacheHits, // cache.CacheMisses, // 100.0 * cache.CacheHits / (cache.CacheHits + cache.CacheMisses), // cache.CacheItemAdds, // cache.CacheItemInvalidations); }
private void DoSetCachingPolicy(CachingPolicy value) { switch (value) { case CachingPolicy.None: if (_subscribed) { RemoteUnsubscribe(); } ClearCache(); break; case CachingPolicy.Demanded: // cached elements and validity remains if (!_subscribed) { RemoteSubscribe(); } break; case CachingPolicy.Dictionary: if (!_subscribed) { RemoteSubscribe(); } RefreshCacheIfNeed(); break; default: throw new Exception( string.Format("LocalBaseCachingService: Unknown value of type {0}", typeof(CachingPolicy).FullName)); } _cachingPolicy = (int)value; }
public Configuration() { var transactionHandler = new CacheTransactionHandler(Cache); AddInterceptor(transactionHandler); var cachingPolicy = new CachingPolicy(); Loaded += (sender, args) => args.ReplaceService <DbProviderServices>( (s, _) => new CachingProviderServices(s, transactionHandler, cachingPolicy)); }
public CachingConfiguration() { //SetExecutionStrategy("System.Data.SqlClient", () => new SqlAzureExecutionStrategy()); var transactionHandler = new CacheTransactionHandler(new InMemoryCache()); AddInterceptor(transactionHandler); var cachingPolicy = new CachingPolicy(); Loaded += (sender, args) => args.ReplaceService <DbProviderServices>( (s, _) => new CachingProviderServices(s, transactionHandler, cachingPolicy)); }
private static ReportResponse ExecuteQuery(Guid segmentId, DateTime startDate, DateTime endDate) { var parameters = new Dictionary <string, object>() { { "@SegmentId", segmentId }, { "@StartDate", startDate }, { "@EndDate", endDate } }; var query = new ReportDataQuery(REPORT_QUERY, parameters); var cachingPolicy = new CachingPolicy { ExpirationPeriod = TimeSpan.Zero }; return(ReportDataService.ExecuteQuery(query, cachingPolicy)); }
public Configuration() { SetDatabaseInitializer <WindAuth.Data.DataContext>(new MigrateDatabaseToLatestVersion <WindAuth.Data.DataContext, WindAuth.Migrations.Configuration>()); var transactionHandler = new CacheTransactionHandler(new InMemoryCache()); AddInterceptor(transactionHandler); var cachingPolicy = new CachingPolicy(); Loaded += (sender, args) => args.ReplaceService <DbProviderServices>( (s, _) => new CachingProviderServices(s, transactionHandler, cachingPolicy)); }
private static OptionalSupportFlags GetCachingSupportFlags(CachingPolicy cachingPolicy) { switch (cachingPolicy) { case CachingPolicy.ManualCaching: return(OptionalSupportFlags.SMB_CSC_CACHE_MANUAL_REINT); case CachingPolicy.AutoCaching: return(OptionalSupportFlags.SMB_CSC_CACHE_AUTO_REINT); case CachingPolicy.VideoCaching: return(OptionalSupportFlags.SMB_CSC_CACHE_VDO); default: return(OptionalSupportFlags.SMB_CSC_NO_CACHING); } }
private static ShareFlags GetShareCachingFlags(CachingPolicy cachingPolicy) { switch (cachingPolicy) { case CachingPolicy.ManualCaching: return(ShareFlags.ManualCaching); case CachingPolicy.AutoCaching: return(ShareFlags.AutoCaching); case CachingPolicy.VideoCaching: return(ShareFlags.VdoCaching); default: return(ShareFlags.NoCaching); } }
public IHttpActionResult Get() { // Use ReportDataProvider ReportDataProviderBase reportingDataProvider = ApiContainer.Configuration.GetReportingDataProvider(); var cachingPolicy = new CachingPolicy { ExpirationPeriod = Config.CacheExpiration }; // Load data from a Custom template in core containing a SQL query field. This gets the SQL we need to query the Fact table Item dataSourceItem = Database.GetDatabase("core").GetItem(new ID("{97502B91-E580-4DAD-A2F5-8E06F4D0554A}")); var reportSqlQuery = dataSourceItem.Fields["SQL"].Value; // Use ReportDataQuery to load data from reporting database Fact table var query = new ReportDataQuery(reportSqlQuery); var table = reportingDataProvider.GetData("reporting", query, cachingPolicy).GetDataTable(); // Create two dictionaries to store data Dictionary<string, string> returnVisitData = new Dictionary<string, string>(); Dictionary<string, string> newVisitData = new Dictionary<string, string>(); // Add two values to each dictionary returnVisitData.Add("VisitType", "Return Visitors"); returnVisitData.Add("Visits", table.Rows[0]["VisitData"].ToString()); newVisitData.Add("VisitType", "New Visitors"); newVisitData.Add("Visits", table.Rows[1]["VisitData"].ToString()); // Data must conform to format: //{"data":{"dataset":[{"data":[ // So using Report Data class to aid with serialization to correct format var reportdata = new ReportData(); reportdata.AddRow(returnVisitData); reportdata.AddRow(newVisitData); var response = new ReportResponse(); response.Data.Dataset.Add(reportdata); //output to Json return new JsonResult<ReportResponse>(response, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }, Encoding.UTF8, this); }
public override int GetHashCode() { unchecked { var hashCode = Scope.GetHashCode(); hashCode = (hashCode * 397) ^ RequestTimeout.GetHashCode(); hashCode = (hashCode * 397) ^ FirstAttemptDelaySeconds.GetHashCode(); hashCode = (hashCode * 397) ^ MaxAttemptDelaySeconds.GetHashCode(); hashCode = (hashCode * 397) ^ DelayMultiplier.GetHashCode(); hashCode = (hashCode * 397) ^ Source.GetHashCode(); hashCode = (hashCode * 397) ^ (Hosts != null ? Hosts.GetHashCode() : 0); hashCode = (hashCode * 397) ^ DefaultPort.GetHashCode(); hashCode = (hashCode * 397) ^ DefaultSlotNumber.GetHashCode(); hashCode = (hashCode * 397) ^ UseHttpsOverride.GetHashCode(); hashCode = (hashCode * 397) ^ (SecurityRole != null ? SecurityRole.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (CachingPolicy != null ? CachingPolicy.GetHashCode() : 0); hashCode = (hashCode * 397) ^ SuppressHealthCheckAfterServiceUnused.GetHashCode(); return(hashCode); } }
public BlogDBContextConfiguration() { try { SetProviderServices("System.Data.SqlClient", SqlProviderServices.Instance); CacheTransactionHandler transactionHandler = new CacheTransactionHandler(new InMemoryCache()); AddInterceptor(transactionHandler); CachingPolicy cachingPolicy = new CachingPolicy(); Loaded += (sender, args) => args.ReplaceService <DbProviderServices>((s, _) => new CachingProviderServices(s, transactionHandler, cachingPolicy)); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("+++++ ERROR - Hiba! Hiba a kontextus felépítése közben! " + "Hiba az Adatbázis Modell létrehozása közben! " + $"\tContext Name: {nameof(BlogDbContext)}.\n\n" + $"Exception Message: {ex.Message}"); } }
public YintaiHangzhouContext(string nameOrConnectionString, ICache cacheProvider, CachingPolicy cachingPolicy) : base(Architecture.Common.Data.EF.EFTracingUtil.GetConnection(nameOrConnectionString), true) { var ctx = ((IObjectContextAdapter)this).ObjectContext; this.ObjectContext = ctx; EFTracingConnection tracingConnection; if (ObjectContext.TryUnwrapConnection(out tracingConnection)) { ctx.GetTracingConnection().CommandExecuting += (s, e) => _log.Debug(e.ToTraceString()); } EFCachingConnection cachingConnection; if (ObjectContext.TryUnwrapConnection(out cachingConnection)) { Cache = cacheProvider; CachingPolicy = cachingPolicy; } }
public IHttpActionResult Get(string keys = null, string dateFrom = null, string dateTo = null) { DateTime startDate; if (!DateTime.TryParseExact(dateFrom, "dd-MM-yyyy", new CultureInfo("en-US"), DateTimeStyles.None, out startDate)) { startDate = DateTime.MinValue; } DateTime endDate; if (!DateTime.TryParseExact(dateTo, "dd-MM-yyyy", new CultureInfo("en-US"), DateTimeStyles.None, out endDate)) { endDate = DateTime.MaxValue; } else { endDate = endDate.Date + new TimeSpan(23, 59, 59); } var parameters = new Dictionary <string, object>() { { "@DimensionKeyId", keys }, { "@StartDate", startDate }, { "@EndDate", endDate } }; var query = new ReportDataQuery(REPORT_QUERY, parameters); var cachingPolicy = new CachingPolicy { ExpirationPeriod = TimeSpan.Zero }; var response = ReportDataService.ExecuteQuery(query, cachingPolicy, "[Url]"); var serializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; return(new JsonResult <ReportResponse>(response, serializerSettings, Encoding.UTF8, this)); }
/// <summary> /// In this demo we are running a set of queries 3 times and logging SQL commands to the console. /// Note that queries are actually executed only in the first pass, while in second and third they are fulfilled /// completely from the cache. /// </summary> private static void SimpleCachingDemo() { ICache cache = new InMemoryCache(); CachingPolicy cachingPolicy = CachingPolicy.CacheAll; // log SQL from all connections to the console EFTracingProviderConfiguration.LogToConsole = true; for (int i = 0; i < 3; ++i) { Console.WriteLine(); Console.WriteLine("*** Pass #{0}...", i); Console.WriteLine(); using (var context = new ExtendedNorthwindEntities()) { // set up caching context.Cache = cache; context.CachingPolicy = cachingPolicy; Console.WriteLine("Loading customer..."); var cust = context.Customers.First(c => c.CustomerID == "ALFKI"); Console.WriteLine("Customer name: {0}", cust.ContactName); Console.WriteLine("Loading orders..."); cust.Orders.Load(); Console.WriteLine("Order count: {0}", cust.Orders.Count); } } Console.WriteLine(); //Console.WriteLine("*** Cache statistics: Hits:{0} Misses:{1} Hit ratio:{2}% Adds:{3} Invalidations:{4}", // cache.CacheHits, // cache.CacheMisses, // 100.0 * cache.CacheHits / (cache.CacheHits + cache.CacheMisses), // cache.CacheItemAdds, // cache.CacheItemInvalidations); }
public IHttpActionResult Get(string datasource, string siteName) { ReportDataProviderBase reportingDataProvider = ApiContainer.Configuration.GetReportingDataProvider(); var cachingPolicy = new CachingPolicy { ExpirationPeriod = TimeSpan.FromHours(1) //must find cache expiration node }; Item dataSourceItem = Database.GetDatabase("core").GetItem(new ID(datasource)); var reportSQLQuery = dataSourceItem.Fields["{0AA8B742-BBDF-4405-AB8D-6FAC7E79433B}"].Value; NameValueCollection parameters = HttpUtility.ParseQueryString(this.Request.RequestUri.Query); var from = DateTime.ParseExact(parameters["dateFrom"], "dd-MM-yyyy", new DateTimeFormatInfo()); var to = DateTime.ParseExact(parameters["dateTo"], "dd-MM-yyyy", new DateTimeFormatInfo()); string dateFrom = from.ToString("yyyy-MM-dd"); string dateTo = to.ToString("yyyy-MM-dd"); if (from.Equals(to) && parameters["dateTo"].Length <= 10) { dateFrom = from.ToString("yyyy-MM-dd 00:00:00"); dateTo = to.ToString("yyyy-MM-dd 23:59:59"); } reportSQLQuery = reportSQLQuery.Replace("@StartDate", "'" + dateFrom + "'"); reportSQLQuery = reportSQLQuery.Replace("@EndDate", "'" + dateTo + "'"); string hashedSiteName = "0"; if (siteName != "all") { var encoder = new Hash32Encoder(); hashedSiteName = encoder.Encode(siteName); reportSQLQuery = reportSQLQuery.Replace("@SiteNameIdOperator", "="); } else { reportSQLQuery = reportSQLQuery.Replace("@SiteNameIdOperator", "!="); } reportSQLQuery = reportSQLQuery.Replace("@SiteNameId", hashedSiteName); var query = new ReportDataQuery(reportSQLQuery); DataTableReader reader = reportingDataProvider.GetData("reporting", query, cachingPolicy).GetDataTable().CreateDataReader(); var data = new ReportData(); int counter = 0; while (reader.Read()) { var row = new Dictionary <string, string>(); for (int i = 0; i < reader.FieldCount; i++) { row.Add(reader.GetName(i), reader[i].ToString()); } data.AddRow(row); counter++; } var responce = new ReportResponse { data = data, TotalRecordCount = counter }; return(new JsonResult <ReportResponse>(responce, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }, Encoding.UTF8, this)); }
public void Add(string shareName, IFileSystem fileSystem, CachingPolicy cachingPolicy) { FileSystemShare share = new FileSystemShare(shareName, fileSystem, cachingPolicy); this.Add(share); }
public FileSystemShare(string shareName, INTFileStore fileSystem, CachingPolicy cachingPolicy) { m_name = shareName; m_fileSystem = fileSystem; m_cachingPolicy = cachingPolicy; }
internal override void OnResponding(Request request) { if (request.Response == null) { request.Response = new ResponseComponent(request); } base.OnResponding(request); foreach (string mime in Codes.MimeTypes.Keys) { if (request.Route.EndsWith(mime)) { request.Response.ContentMimeType = Codes.MimeTypes[mime]; } } FileCache cache = null; if (filecachelist.Keys.Contains(request.Route)) { cache = filecachelist[request.Route]; } bool partial = false; int seek = 0; long?fsPosition = null; long?fsLength = null; if (cache == null || cache.Content == null) { string file = $"{this.rootpath}{this.virtualpath}{request.Route}"; if (request.RangeStart.HasValue) { seek = request.RangeStart.Value; } using (var fs = new System.IO.FileStream(file, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { // TODO check for accept ranges in request header, otherwise streamout the entire content request.Response.Content = new byte[4 * 1024 * 1024]; if (seek > 0) { fs.Seek(seek, System.IO.SeekOrigin.Begin); } request.Response.ContentLength = fs.Read(request.Response.Content, 0, request.Response.Content.Length); if (fs.Position < fs.Length || seek > 0) { partial = true; } // TODO not to store the entire buffer if (!partial) { byte[] t = new byte[request.Response.ContentLength]; Buffer.BlockCopy(request.Response.Content, 0, t, 0, (int)request.Response.ContentLength); filecachelist.Add(this.virtualpath + request.Route, cache = new FileCache() { ContentLength = request.Response.ContentLength, Content = t, ContentRoute = request.Route, ContentMimeType = request.Response.ContentMimeType }); Debug.WriteLine("\t\t[Servic] cached miss with {0} bytes", cache.ContentLength, null); } fsPosition = fs.Position; fsLength = fs.Length; } } else if (cache != null && cache.Content != null) { Debug.WriteLine("\t\t[servic] cached hit with {0} bytes", cache.ContentLength, null); request.Response.Content = cache.Content; request.Response.ContentLength = cache.ContentLength; request.Response.ContentMimeType = cache.ContentMimeType; } if (partial) { request.Socket.Send(Encoding.ASCII.GetBytes(Codes.HttpReposnes[206])); } else { request.Socket.Send(Encoding.ASCII.GetBytes(Codes.HttpReposnes[200])); } if (partial) { request.Socket.Send(Encoding.ASCII.GetBytes("Accept-Ranges: bytes\r\n")); } request.Socket.Send(Encoding.ASCII.GetBytes($"Content-Length: {request.Response.ContentLength}\r\n")); request.Socket.Send(Encoding.ASCII.GetBytes($"Content-Type: {request.Response.ContentMimeType}\r\n")); foreach (var header in request.Session.AdditionalHeaders) { request.Socket.Send(Encoding.ASCII.GetBytes($"{header}\r\n")); } if (partial) { request.Socket.Send(Encoding.ASCII.GetBytes(string.Format("Content-Range: bytes {0}-{1}/{2}\r\n", seek, fsPosition.Value - 1, fsLength.Value))); } request.Socket.Send(Encoding.ASCII.GetBytes("\r\n")); request.Socket.Send(request.Response.Content, (int)request.Response.ContentLength, System.Net.Sockets.SocketFlags.None); }
public static ReportResponse ExecuteQuery(ReportDataQuery queryData, CachingPolicy cachingPolicy, string keyTranslationField = null, string keyTranslationDefault = null) { var reportResponse = new ReportResponse(); var totalRecordCount = 0; var translations = new Dictionary <string, string>(); var reportingDataProvider = ApiContainer.Configuration.GetReportingDataProvider(); var reportRows = new List <ReportRow>(); var dataTable = reportingDataProvider.GetData("reporting", queryData, cachingPolicy).GetDataTable(); foreach (DataRow dataRow in dataTable.Rows) { var key = GetStringValue(dataRow, "[Key]"); var dimensionKeyId = GetInt64Value(dataRow, "[DimensionKeyId]"); var bounces = GetIntValue(dataRow, "[Bounces]"); var conversions = GetIntValue(dataRow, "[Conversions]"); var timeOnSite = GetInt64Value(dataRow, "[TimeOnSite]"); var value = GetIntValue(dataRow, "[Value]"); var pageViews = GetIntValue(dataRow, "[PageViews]"); var visits = GetIntValue(dataRow, "[Visits]"); var date = GetDateValue(dataRow, "[Date]"); var count = GetIntValue(dataRow, "[Count]"); var reportRow = new ReportRow { Key = key, DimensionKeyId = dimensionKeyId, Bounces = bounces, Conversions = conversions, TimeOnSite = timeOnSite, PageViews = pageViews, Visits = visits, Value = value, Date = date, Count = count, ValuePerVisit = Math.Round((double)value / visits, 2), BounceRate = Math.Round((double)bounces / visits, 4), AvgVisitDuration = Math.Round((double)timeOnSite / visits, 2), ConversionRate = Math.Round((double)conversions / visits, 2), AvgVisitPageViews = Math.Round((double)pageViews / visits, 2), AvgVisitCount = Math.Round((double)count / visits, 2), AvgPageCount = Math.Round((double)count / pageViews, 2), AvgCountValue = (count == 0) ? 0 : Math.Round((double)value / count, 2) }; reportResponse.Data.AddRow(reportRow); if (keyTranslationField != null) { var translation = GetStringValue(dataRow, keyTranslationField) ?? keyTranslationDefault; translations.Add(reportRow.Key, translation); } totalRecordCount++; } if (keyTranslationField != null) { reportResponse.Data.Localization.AddField("key", translations); } reportResponse.TotalRecordCount = totalRecordCount; reportResponse.TimeResolution = "c"; // w return(reportResponse); }
public FileSystemShare(string shareName, IFileSystem fileSystem, CachingPolicy cachingPolicy) { m_name = shareName; m_fileSystem = new NTFileSystemAdapter(fileSystem); m_cachingPolicy = cachingPolicy; }