示例#1
0
文件: CacheBase.cs 项目: Zedfa/Core
        public static T Cache <T>(this ICacheDataProvider <T> cacheExecution, CacheInfo cacheInfo, int expireCacheSecondTime, string cacheKey, bool canUseCache)
        {
            T   result       = default(T);
            var fakeResult   = string.Empty;
            var cacheKeyFake = cacheKey + "_Fake";


            if (CacheService.TryGetCache <T>(cacheKey, out result))
            {
                if (!CacheService.TryGetCache <string>(cacheKeyFake, out fakeResult))
                {
                    if (cacheInfo.CacheRefreshingKind == CacheRefreshingKind.Slide)
                    {
                        CacheService.SetCache <string>(cacheKeyFake, "Fake value", expireCacheSecondTime * 10);
                    }
                    else
                    {
                        CacheService.SetCache <string>(cacheKeyFake, "Fake value", expireCacheSecondTime);
                    }

                    if (cacheInfo.CountOfWaitingThreads < 3)
                    {
                        var task = new Task(() =>
                        {
                            var resultFunc = default(T);
                            TryRefreshCache <T>(cacheExecution, cacheInfo, out resultFunc);
                        });

                        task.Start();
                    }
                }
                else
                {
                    cacheInfo.FrequencyOfUsing += 1;
                    cacheInfo.LastUseDateTime   = DateTime.Now;
                }
            }
            else
            {
                result = cacheExecution.GetFreshData();
                if (cacheInfo.EnableToFetchOnlyChangedDataFromDB)
                {
                    List <ObjectBase> nlst = (result as IList).Cast <ObjectBase>().ToList();
                    QueryableCacheDataProvider <object> .CalcAllTimeStampAndSet(result as IList, cacheInfo, true);

                    if (nlst.Count > 0)
                    {
                        foreach (var en in nlst.Cast <ObjectBase>())
                        {
                            (en as ObjectBase).EnableFillNavigationProperyByCache();
                        }
                    }
                }
                CacheService.SetCache <T>(cacheKey, result, expireCacheSecondTime * (double)100000);
                CacheService.SetCache <string>(cacheKeyFake, "Fake value", expireCacheSecondTime);
            }
            return(result);
        }
示例#2
0
        private object GetDataFromCacheServerViaWCF()
        {
            EndpointAddress endpointAddress = new EndpointAddress(ConfigHelper.GetConfigValue <string>("CacheClientWebServiceUrl"));
            NetTcpBinding   binding         = new NetTcpBinding();

            binding.MaxBufferPoolSize      = int.MaxValue;
            binding.MaxReceivedMessageSize = int.MaxValue;
            binding.MaxBufferSize          = int.MaxValue;
            // binding.TransferMode = TransferMode.Streamed;
            binding.ReaderQuotas.MaxArrayLength         = int.MaxValue;
            binding.ReaderQuotas.MaxBytesPerRead        = int.MaxValue;
            binding.ReaderQuotas.MaxDepth               = int.MaxValue;
            binding.ReaderQuotas.MaxNameTableCharCount  = int.MaxValue;
            binding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
            binding.Security.Mode  = SecurityMode.None;
            binding.CloseTimeout   = new TimeSpan(0, 2, 0);
            binding.OpenTimeout    = new TimeSpan(0, 2, 0);
            binding.ReceiveTimeout = new TimeSpan(0, 2, 0);
            binding.SendTimeout    = new TimeSpan(0, 2, 0);
            binding.Security.Message.ClientCredentialType   = MessageCredentialType.None;
            binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
            using (ServiceClient proxy = new ServiceClient(binding, endpointAddress))
            {
                var logerService = AppBase.LogService;
                try
                {
                    var result = proxy.GetCacheDataViaWcf(this);
                    if (CacheInfo.EnableCoreSerialization)
                    {
                        result = DeserializeCacheData((byte[])result);
                    }

                    proxy.Close();
                    if (CacheInfo.EnableToFetchOnlyChangedDataFromDB)
                    {
                        QueryableCacheDataProvider <ObjectBase> .CalcAllTimeStampAndSet(result as IEnumerable, CacheInfo, false);
                    }
                    return(result);
                }
                catch (FaultException exc)
                {
                    if (exc is System.ServiceModel.FaultException <System.ServiceModel.ExceptionDetail> )
                    {
                        var customEx = new CustomCacheFaultedException((exc as FaultException <ExceptionDetail>).Detail);
                        //var eLog = logerService.GetEventLogObj();
                        //eLog.OccuredException = customEx;
                        //eLog.UserId = "Cache";
                        //eLog.CustomMessage = "cache server error report in client side!";
                        //logerService.Handle(eLog);

                        proxy.Abort();
                        throw logerService.Handle(customEx, "cache server error report in client side!", true, "Cache");

                        //throw customEx;
                    }
                    else
                    {
                        //var eLog = logerService.GetEventLogObj();
                        //eLog.OccuredException = exc;
                        //eLog.UserId = "Cache";
                        //eLog.CustomMessage = "cache server error report in client side!";
                        //logerService.Handle(eLog);
                        proxy.Abort();
                        throw logerService.Handle(exc, "cache server error report in client side!", true, "Cache");

                        //throw exc;
                    }
                }
                catch (Exception ex)
                {
                    //var eLog = logerService.GetEventLogObj();
                    //eLog.OccuredException = ex;
                    //eLog.UserId = "Cache";
                    //eLog.CustomMessage = "cache server error report in client side!";
                    //logerService.Handle(eLog);
                    proxy.Abort();
                    //throw ex;
                    throw logerService.Handle(ex, "cache server error report in client side!", true, "Cache");
                }
            }
        }
示例#3
0
文件: CacheBase.cs 项目: Zedfa/Core
        public static T MergeFreshDataByOldCache <T>(T oldData, T newData, CacheInfo cacheInfo, bool isQueryableCache, out List <ObjectBase> entitiesForDeletion, out List <ObjectBase> entitiesForAddition, out List <ObjectBase> entitiesForUpdates)
        {
            entitiesForDeletion = null;
            entitiesForAddition = null;
            entitiesForUpdates  = null;
            var nlst       = (newData as IList);
            T   resultList = oldData;

            if (oldData == null)
            {
                resultList = newData;
            }
            else
            {
                if (!cacheInfo.DisableToSyncDeletedRecord_JustIfEnableToFetchOnlyChangedDataFromDB && !cacheInfo.IsFunctionalCache)
                {
                    var deletedRecords = CacheConfig.CacheManagementRepository.
                                         GetDeletedRecordsByTable(cacheInfo.Repository.Schema + "." + cacheInfo.Repository.TableName,
                                                                  cacheInfo.MaxTimeStampForDeletedRecord, cacheInfo.CacheRefreshingKind != CacheRefreshingKind.SqlDependency);

                    if (deletedRecords.Count > 0)
                    {
                        var maxDeletedRecordItem       = (ObjectBase)deletedRecords.OrderByDescending(item => ((ObjectBase)item).TimeStampUnit).First();
                        var maxTimeStampDeletedRecords = ((ObjectBase)maxDeletedRecordItem).TimeStampUnit;
                        var oldEntityBaseLst           = (oldData as IList).Cast <ObjectBase>().ToList();
                        var oldLst = oldData as IList;
                        entitiesForDeletion = new List <ObjectBase>();
                        foreach (var record in deletedRecords)
                        {
                            if (nlst != null && nlst.Count > 0)
                            {
                                var newItemToRemove = nlst.Cast <ObjectBase>().FirstOrDefault(item => item.CacheId == record.DeletedEntityId);
                                if (newItemToRemove != null)
                                {
                                    nlst.Remove(newItemToRemove);
                                    newItemToRemove.IsDeletedForCache = true;
                                }
                            }

                            var itemToRemove = oldEntityBaseLst.FirstOrDefault(item => item.CacheId == record.DeletedEntityId);
                            if (itemToRemove != null)
                            {
                                entitiesForDeletion.Add(itemToRemove);
                                oldLst.Remove(itemToRemove);
                                itemToRemove.IsDeletedForCache = true;

                                foreach (var inf in cacheInfo.InfoAndEntityListForFillingNavigationPropertyDic.ToList())
                                {
                                    List <ObjectBase> entities;
                                    /// attention: Added Tolist Here
                                    //lock (inf.Value)
                                    //{
                                    entities = inf.Value.Where(en =>
                                    {
                                        var thisPropertyValue = en[inf.Key.ThisEntityRefrencePropertyName];
                                        return(thisPropertyValue != null && thisPropertyValue.Equals(itemToRemove[inf.Key.OtherEntityRefrencePropertyName]));
                                    }).ToList();
                                    //}
                                    //Where(en => en[inf.Key.ThisEntityRefrencePropertyName].Equals(itemToRemove[inf.Key.OtherEntityRefrencePropertyName])).ToList()
                                    entities.ForEach((Action <ObjectBase>)((ObjectBase parentEntity) =>
                                    {
                                        object navContainer;
                                        if (parentEntity.NavigationPropertyDataDic.TryGetValue(inf.Key.PropertyInfo.Name, out navContainer))
                                        {
                                            if (inf.Key.IsEnumerable)
                                            {
                                                // var navContainer = parentEntity.NavigationPropertyDataDic[inf.Key.PropertyInfo.Name];
                                                var navPropList = navContainer as IList;
                                                if (navPropList.Count > 0)
                                                {
                                                    IList newNavProp = Activator.CreateInstance(navContainer.GetType()) as IList;
                                                    navPropList.Cast <ObjectBase>().ToList().ForEach((ObjectBase entity) =>
                                                    {
                                                        if (!entity.Equals(itemToRemove))
                                                        {
                                                            newNavProp.Add(entity);
                                                        }
                                                    });

                                                    parentEntity.NavigationPropertyDataDic.TryUpdate(inf.Key.PropertyInfo.Name, newNavProp, navContainer);
                                                    parentEntity.CallNavigationPropertyChangedByCache(parentEntity, inf.Key.PropertyInfo.Name);
                                                }
                                                // (en.NavigationPropertyDataDic[inf.Key.PropertyInfo.Name] as IList).Remove(itemToRemove);
                                            }
                                            else
                                            {
                                                //en[inf.Key.PropertyInfo.Name] = null;
                                                object tmp;
                                                parentEntity.NavigationPropertyDataDic.TryRemove(inf.Key.PropertyInfo.Name, out tmp);
                                                parentEntity.CallNavigationPropertyChangedByCache(parentEntity, inf.Key.PropertyInfo.Name);
                                            }
                                        }
                                        else
                                        {
                                            parentEntity.CallNavigationPropertyChangedByCache(parentEntity, inf.Key.PropertyInfo.Name);
                                        }
                                    }));
                                }
                            }
                        }



                        cacheInfo.MaxTimeStampUintForDeletedRecord  = cacheInfo.MaxTimeStampUintForDeletedRecord2;
                        cacheInfo.MaxTimeStampUintForDeletedRecord2 = maxTimeStampDeletedRecords;
                        cacheInfo.MaxTimeStampForDeletedRecord      = cacheInfo.MaxTimeStampForDeletedRecord2;
                        cacheInfo.MaxTimeStampForDeletedRecord2     = maxDeletedRecordItem.TimeStamp;
                    }
                }


                if (nlst.Count > 0)
                {
                    entitiesForAddition = new List <ObjectBase>();
                    entitiesForUpdates  = new List <ObjectBase>();
                    var newLst           = nlst.Cast <ObjectBase>().ToList();
                    var oldLst           = (oldData as IList);
                    var oldEntityBaseLst = (oldData as IList).Cast <ObjectBase>().ToList();
                    var result           = Activator.CreateInstance <T>() as IList;
                    foreach (var item in oldEntityBaseLst)
                    {
                        result.Add(item);
                    }

                    foreach (var newItem in newLst)
                    {
                        var oldItem = oldEntityBaseLst.FirstOrDefault(item => item.Equals(newItem));
                        if (oldItem != null)
                        {
                            UpdateNavigationProperties(cacheInfo, newItem, oldItem);
                            oldItem.UpdateAllProps(newItem);
                            entitiesForUpdates.Add(oldItem);
                        }
                        else
                        {
                            entitiesForAddition.Add(newItem);
                            result.Add(newItem);
                            UpdateNavigationProperties(cacheInfo, newItem, null);

                            // newItem.EnableFillNavigationProperyByCache = true;
                        }
                    }

                    resultList = (T)result;
                }
            }

            if (entitiesForUpdates != null && entitiesForUpdates.Count > 0)
            {
                cacheInfo.CallOnUpdateEntities(entitiesForUpdates);
            }

            if (entitiesForAddition != null && entitiesForAddition.Count > 0)
            {
                cacheInfo.CallOnAddEntities(entitiesForAddition);
            }

            if (entitiesForDeletion != null && entitiesForDeletion.Count > 0)
            {
                cacheInfo.CallOnDeleteEntities(entitiesForDeletion);
            }

            if ((cacheInfo.EnableUseCacheServer && ConfigHelper.GetConfigValue <bool>("IsCacheServer")) || !cacheInfo.EnableUseCacheServer)
            {
                if (!string.IsNullOrEmpty(cacheInfo.NameOfNavigationPropsForFetchingOnlyChangedDataFromDB) || (cacheInfo.EnableSaveCacheOnHDD && cacheInfo.NotYetGetCacheData))
                {
                    QueryableCacheDataProvider <object> .CalcAllTimeStampAndSet(newData as IList, cacheInfo, isQueryableCache);
                }
                else
                {
                    cacheInfo.MaxTimeStamp     = cacheInfo.MaxTimeStampCopy;
                    cacheInfo.MaxTimeStampUint = cacheInfo.MaxTimeStampUintCopy;
                }
            }

            if (nlst.Count > 0)
            {
                foreach (var en in nlst.Cast <ObjectBase>())
                {
                    (en as ObjectBase).EnableFillNavigationProperyByCache();
                }
            }

            // System.Diagnostics.Debug.WriteLine("after merg:" + (oldData as IList).Count);
            return(resultList);
        }