Example #1
0
 /// <summary>
 /// Lê o item associado com a chave informada.
 /// </summary>
 /// <param name="key">Chave do item.</param>
 /// <param name="item">Instancia do item que será recuperado.</param>
 /// <param name="providerName">Nome do provedor de leitura que será utilizado.</param>
 public void ReadThru(string key, out ProviderCacheItem item, string providerName)
 {
     item = null;
     if (_readerProivder != null)
     {
         ReadThruProviderManager mgr = null;
         if (string.IsNullOrEmpty(providerName))
         {
             providerName = this.DefaultReadThruProvider;
         }
         if (_readerProivder.ContainsKey(providerName.ToLower()))
         {
             _readerProivder.TryGetValue(providerName.ToLower(), out mgr);
             try
             {
                 if (mgr != null)
                 {
                     mgr.ReadThru(key, out item);
                 }
             }
             catch (Exception)
             {
                 throw;
             }
         }
     }
 }
        public ProviderCacheItem LoadFromSource(string key)
        {
            var query = $"SELECT customerid, address, country, city FROM customers WHERE customerid = '{key}'";
            // Define a query returning a single row result set
            NpgsqlCommand     command           = new NpgsqlCommand(query, _connection as NpgsqlConnection);
            var               reader            = command.ExecuteReader();
            ProviderCacheItem providerCacheItem = null;

            while (reader.Read())
            {
                if (providerCacheItem == null)
                {
                    var customer = new Customer()
                    {
                        customerid = reader[0] as string,
                        address    = reader[1] as string,
                        country    = reader[2] as string,
                        city       = reader[3] as string,
                    };
                    providerCacheItem = new ProviderCacheItem(customer)
                    {
                        Dependency    = new PostGreSQLDependency(_connectionString, customer.customerid, "public", "customers", "customer_channel"),
                        ResyncOptions = new ResyncOptions(true)
                    };
                }
            }
            reader.Close();

            return(providerCacheItem);
        }
Example #3
0
 public WriteOperation(string key, ProviderCacheItem cacheItem, WriteOperationType opType, int retryCount)
 {
     this._key        = key;
     this._cacheItem  = cacheItem;
     this._opType     = opType;
     this._retryCount = retryCount;
 }
Example #4
0
        /// <summary>
        /// Ressincroniza a entrada do cache.
        /// </summary>
        /// <param name="key">Chave do item.</param>
        /// <param name="entry">Instancia da entrada.</param>
        /// <param name="flag">Conjunto associado.</param>
        /// <param name="group">Grupo onde a entrada está inserida.</param>
        /// <param name="subGroup">Subgrupo da entrada.</param>
        /// <param name="providerName">Nome do provedor.</param>
        /// <param name="operationContext">Contexto da operação.</param>
        /// <returns></returns>
        public object ResyncCacheItem(string key, out CacheEntry entry, ref BitSet flag, string group, string subGroup, string providerName, OperationContext operationContext)
        {
            ProviderCacheItem item = null;

            this.ReadThru(key, out item, providerName);
            UserBinaryObject obj2 = null;

            try
            {
                obj2 = this.GetCacheEntry(key, item, ref flag, group, subGroup, out entry);
                if (obj2 == null)
                {
                    return(obj2);
                }
                CacheInsResultWithEntry entry2 = _context.CacheImpl.Insert(key, entry, false, null, 0, LockAccessType.IGNORE_LOCK, operationContext);
                if (entry2.Result == CacheInsResult.Failure)
                {
                    throw new OperationFailedException("Operation failed to synchronize with data source");
                }
                if (entry2.Result == CacheInsResult.NeedsEviction)
                {
                    throw new OperationFailedException("The cache is full and not enough items could be evicted.");
                }
            }
            catch (Exception exception)
            {
                throw new OperationFailedException("Error occurred while synchronization with data source. Error: " + exception.Message, exception);
            }
            return(obj2);
        }
Example #5
0
        /// <summary>
        /// Load the Orders from the database based on condition from the database.
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="userContext"></param>
        /// <returns></returns>
        private LoaderResult LoadOrders(string condition, object userContext)
        {
            LoaderResult result = new LoaderResult();

            result.UserContext = userContext;
            if (_connection != null)
            {
                SqlCommand  command = new SqlCommand(_query + condition, _connection);
                IDataReader reader  = command.ExecuteReader();
                while (reader.Read())
                {
                    // Read and construct Order
                    Order order = new Order();
                    order.OrderID     = int.Parse(reader[0].ToString());
                    order.OrderDate   = Convert.ToDateTime(reader[1].ToString());
                    order.ShipName    = reader[2] as string;
                    order.ShipAddress = reader[3] as string;
                    order.ShipCity    = reader[4] as string;
                    order.ShipCountry = reader[5] as string;
                    // Create a Cache item
                    // You must create ProviderCacheItem before adding to the resultant data...
                    ProviderCacheItem cacheItem = new ProviderCacheItem(order);

                    // Add to Loader data...
                    result.Data.Add(new System.Collections.Generic.KeyValuePair <string, ProviderItemBase>(order.OrderID.ToString(), cacheItem));
                }
            }
            result.HasMoreData = false;
            return(result);
        }
Example #6
0
 public WriteOperations(string key, ProviderCacheItem cacheItem, WriteOperationType opType, bool updateInCache)
 {
     this._key           = key;
     this._cacheItem     = cacheItem;
     this._opType        = opType;
     this._updateInCache = updateInCache;
 }
Example #7
0
        public WriteOperation GetWriteOperation(LanguageContext languageContext, OperationContext operationContext)
        {
            object            value;
            ProviderCacheItem providerCacheItem = null;

            if (_writeOperation != null)
            {
                return(new WriteOperation(_writeOperation.Key, _writeOperation.ProviderCacheItem, _writeOperation.OperationType, this._retryCount));
            }
            if (_entry != null)
            {
                if (_entry.Value is CallbackEntry)
                {
                    value = ((CallbackEntry)_entry.Value).Value;
                }
                else
                {
                    value = _entry.Value;
                }

                if (value != null)
                {
                    if (_opCode != OpCode.Remove) // Don't need data for remove operation
                    {
                        value = _context.CacheWriteThruDataService.GetCacheData(value, _entry.Flag);
                    }
                }


                providerCacheItem = GetProviderCacheItemFromCacheEntry(_entry, value, operationContext);
            }

            //WriteOperations
            return(new WriteOperation(_key.ToString(), providerCacheItem, SetWriteOperationType(_opCode), _retryCount));
        }
        /// <summary>
        /// Responsible for loading an object from the external data source.
        /// Key is passed as parameter.
        /// <param name="key">item identifier; probably a primary key</param>
        /// <returns>data contained in ProviderCacheItem</returns>
        public ProviderCacheItem LoadFromSource(string key)
        {
            ProviderCacheItem cacheItem = new ProviderCacheItem(sqlDatasource.LoadCustomer(key));

            cacheItem.ResyncOptions.ResyncOnExpiration = true;
            cacheItem.ResyncOptions.ProviderName       = sqlDatasource.ConnString;
            return(cacheItem);
        }
Example #9
0
        /// <summary>
        /// Responsible for loading an object from the external data source.
        /// Key is passed as parameter.
        /// <param name="key">item identifier; probably a primary key</param>
        /// <returns>data contained in ProviderCacheItem</returns>
        public ProviderCacheItem LoadFromSource(string key)
        {
            ProviderCacheItem cacheItem = new ProviderCacheItem(sqlDatasource.LoadCustomer(key));

            cacheItem.ResyncOptions.ResyncOnExpiration = true;
            // Resync provider name will be picked from default provider.
            return(cacheItem);
        }
Example #10
0
        public ProviderCacheItem LoadFromSource(string key)
        {
            Customer value     = LoadFromDataSource(key);
            var      cacheItem = new ProviderCacheItem(value);

            cacheItem.ResyncOptions.ResyncOnExpiration = true;
            return(cacheItem);
        }
Example #11
0
        public static StoreItem ToSerializedStoreItem(this StoreItem storeItem, ProviderItemBase providerItem, ISerializer serializer)
        {
            ProviderCacheItem providerCacheItem = providerItem as ProviderCacheItem;

            if (providerCacheItem == null)
            {
                throw new Exception("providerItembase is not cache item");
            }
            storeItem.UserObject = serializer.Serialize(providerCacheItem.GetValue <object>());
            return(storeItem);
        }
Example #12
0
 /// <summary>
 /// Lê um item com base na chave informada.
 /// </summary>
 /// <param name="key"></param>
 /// <param name="item"></param>
 public void ReadThru(string key, out ProviderCacheItem item)
 {
     item = null;
     try
     {
         _provider.LoadFromSource(key, out item);
     }
     catch (Exception exception)
     {
         throw new OperationFailedException(ResourceMessageFormatter.Create(() => Properties.Resources.OperationFailedException_IReadThruProviderLoadFromSourceFailed).Format(), exception);
     }
 }
Example #13
0
        /// <summary> Do write-thru now. </summary>
        public void Process()
        {
            lock (this)
            {
                try
                {
                    if (_val == null)
                    {
                        ProviderCacheItem item              = null;
                        LanguageContext   languageContext   = LanguageContext.NONE;
                        OperationContext  operationContext  = new OperationContext();
                        CacheEntry        entry             = null;
                        object            userBrinaryObject = null;
                        try
                        {
                            _parent.ReadThru(_key, out item, _resyncProviderName, out languageContext, operationContext);
                            userBrinaryObject = _parent.GetCacheEntry(_key, item, ref this._flag, _groupInfo != null ? _groupInfo.Group : null, _groupInfo != null ? _groupInfo.SubGroup : null, out entry, languageContext);
                        }
                        catch (Exception ex)
                        {
                            _val = ex;
                            _parent.Context.NCacheLog.Error("DatasourceMgr.ResyncCacheItem", ex.Message + " " + ex.StackTrace);
                        }
                        if (!(_val is Exception) && userBrinaryObject != null)
                        {
                            operationContext.Add(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);

                            CacheInsResultWithEntry result = _parent.Context.CacheImpl.Insert(_key, entry, true, null, 0, LockAccessType.IGNORE_LOCK, operationContext);
                            if (result != null && result.Result == CacheInsResult.IncompatibleGroup)
                            {
                                _parent.Context.CacheImpl.Remove(_key, ItemRemoveReason.Removed, true, null, 0, LockAccessType.IGNORE_LOCK, new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation));
                            }
                        }
                        else
                        {
                            _parent.Context.CacheImpl.Remove(_key, ItemRemoveReason.Removed, true, null, 0, LockAccessType.IGNORE_LOCK, new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation));
                        }
                    }
                }
                catch (Exception e)
                {
                    _val = e;
                    _parent.Context.NCacheLog.Error("DatasourceMgr.ResyncCacheItem", e.Message + " " + e.StackTrace);
                }
                finally
                {
                    _parent.Context.PerfStatsColl.IncrementCountStats(_parent.Context.CacheInternal.Count);
                    _parent.Queue.Remove(_key);
                }
            }
        }
 public void MakeStoreItem(string key, ProviderCacheItem providerItem)
 {
     try
     {
         Key            = key;
         ExpirationType = providerItem.Expiration.Type;
         TimeToLive     = providerItem.Expiration.ExpireAfter;
         ItemPriority   = providerItem.ItemPriority;
         Group          = providerItem.Group;
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Example #15
0
        /// <summary>
        /// Convert StoreItem to ProviderItemBase based on the serializer provided
        /// </summary>
        /// <param name="storeItem"></param>
        /// <param name="serializer"></param>
        /// <returns></returns>
        public static ProviderItemBase ToProviderItemBase(this StoreItem storeItem, ISerializer serializer)
        {
            ProviderItemBase providerItem = null;

            switch (storeItem.ItemType)
            {
            case ItemType.CacheItem:
                providerItem = new ProviderCacheItem(storeItem.UserObject);
                SetProviderItemBaseProperties(storeItem, providerItem);

                providerItem.ToProviderCacheItem().SetValue(storeItem.UserObject);
                return(providerItem);
            }
            return(providerItem);
        }
Example #16
0
 /// <summary>
 /// Carrega o próximo item do cache.
 /// </summary>
 /// <param name="data">Lista ordenada com os dados a serem inseridos</param>
 /// <param name="index">Objeto de indexeção para saber em que estágio da geração do cache estamos</param>
 /// <returns>Retorna true enquanto falta objetos para se carregar para o cache</returns>
 public bool LoadNext(ref OrderedDictionary data, ref object index)
 {
     try
     {
         if (!_started)
         {
             Start(null);
         }
         if (_itemsLoader == null)
         {
             return(false);
         }
         Record record = null;
         IRecordKeyGenerator generator = null;
         while (true)
         {
             if (!_itemsLoader.MoveNext())
             {
                 _itemsLoader.Dispose();
                 _itemsLoader = null;
                 OnLoadFinish();
                 return(false);
             }
             record    = _itemsLoader.Current;
             generator = _itemsLoader.CurrentGenerator;
             if (generator == null)
             {
                 continue;
             }
             break;
         }
         var key    = generator.GetKey(record);
         var values = new object[record.FieldCount];
         for (var i = 0; i < record.FieldCount; i++)
         {
             values[i] = record.GetValue(i);
         }
         var cacheItem = new ProviderCacheItem(new CacheItemRecord(_itemsLoader.CurrentTypeName, values, record.Descriptor));
         cacheItem.AbsoluteExpiration = DateTime.MaxValue;
         data.Add(key, cacheItem);
         return(true);
     }
     catch
     {
         throw;
     }
 }
Example #17
0
        public LoaderResult LoadNext(object userContext)
        {
            LoaderResult loaderResult = new LoaderResult();
            string       queryString  = "SELECT * FROM Customers";

            try
            {
                using (SqlConnection sqlConnection = new SqlConnection(_connectionString))
                {
                    if (sqlConnection.State == ConnectionState.Closed)
                    {
                        sqlConnection.Open();
                    }
                    SqlCommand cmd = new SqlCommand(queryString, sqlConnection);
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            Customer customerObject = new Customer
                            {
                                CompanyName  = reader["CompanyName"].ToString(),
                                ContactName  = reader["ContactName"].ToString(),
                                ContactTitle = reader["ContactTitle"].ToString(),
                                Address      = reader["Address"].ToString(),
                                CustomerId   = reader["CustomerID"].ToString()
                            };

                            ProviderCacheItem cacheItem = new ProviderCacheItem(customerObject);
                            var key          = $"Customer:{customerObject.CustomerId}";
                            var keyValuePair = new KeyValuePair <string, ProviderItemBase>(key, cacheItem);
                            loaderResult.Data.Add(keyValuePair);
                        }
                    }
                    sqlConnection.Close();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            loaderResult.HasMoreData = false;
            return(loaderResult);
        }
Example #18
0
 /// <summary>
 /// Método do processo da tarefa.
 /// </summary>
 public void Process()
 {
     lock (this)
     {
         try
         {
             if (_val == null)
             {
                 ProviderCacheItem item       = null;
                 CacheEntry        cacheEntry = null;
                 UserBinaryObject  obj2       = null;
                 try
                 {
                     _parent.ReadThru(_key, out item, _resyncProviderName);
                     obj2 = _parent.GetCacheEntry(_key, item, ref _flag, (_groupInfo != null) ? _groupInfo.Group : null, (_groupInfo != null) ? _groupInfo.SubGroup : null, out cacheEntry);
                 }
                 catch (Exception exception)
                 {
                     _val = exception;
                     _parent._context.Logger.Error(("DatasourceMgr.ResyncCacheItem: " + exception.StackTrace).GetFormatter());
                 }
                 if (!(_val is Exception) && (obj2 != null))
                 {
                     _parent._context.CacheImpl.Insert(_key, cacheEntry, true, null, 0, LockAccessType.IGNORE_LOCK, new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation));
                 }
                 else
                 {
                     _parent._context.CacheImpl.Remove(_key, ItemRemoveReason.Expired, true, null, 0, LockAccessType.IGNORE_LOCK, new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation));
                 }
             }
         }
         catch (Exception exception2)
         {
             _val = exception2;
             _parent._context.Logger.Error((exception2.Message + exception2.StackTrace).GetFormatter());
         }
         finally
         {
             _parent._queue.Remove(_key);
         }
     }
 }
Example #19
0
        public IDictionary <string, ProviderCacheItem> LoadFromSource(ICollection <string> keys)
        {
            var dictionary = new Dictionary <string, ProviderCacheItem>();

            try
            {
                foreach (string key in keys)
                {
                    ProviderCacheItem cacheItem = new ProviderCacheItem(LoadFromDataSource(key));
                    cacheItem.ResyncOptions.ResyncOnExpiration = true;
                    dictionary.Add(key, cacheItem);
                }
                return(dictionary);
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.Message);
            }
            return(dictionary);
        }
        public ProviderCacheItem LoadFromSource(
            string key)
        {
            if (key.StartsWith("Customer:CustomerID:"))
            {
                var customerId = key.Replace("Customer:CustomerID:", "").Trim();

                var commandDefinition = new CommandDefinition(
                    $@" SELECT * 
                                                        FROM dbo.Customers 
                                                        WHERE CustomerID = @cId",
                    new { cid = customerId },
                    flags: CommandFlags.NoCache);

                var customer = Connection.Query <Customer>(commandDefinition)
                               .FirstOrDefault();

                if (customer == null)
                {
                    return(null);
                }
                else
                {
                    var providerCacheItem = new ProviderCacheItem(customer)
                    {
                        Dependency    = GetCustomerSqlDependency(customerId),
                        ResyncOptions = new ResyncOptions(true)
                    };

                    return(providerCacheItem);
                }
            }
            else
            {
                return(null);
            }
        }
        /// <summary>
        /// Responsible for loading multiple objects from the external data source.
        /// </summary>
        /// <param name="keys">Collection of keys to be fetched from data source</param>
        /// <returns>Dictionary of keys with respective data contained in ProviderCacheItem</returns>
        public IDictionary <string, ProviderCacheItem> LoadFromSource(ICollection <string> keys)
        {
            // initialize dictionary to return to cache
            IDictionary <string, ProviderCacheItem> providerItems = new Dictionary <string, ProviderCacheItem>();

            // iterate through all the keys and fetch data
            foreach (string key in keys)
            {
                // get data from data source
                object data = sqlDatasource.LoadCustomer(key);
                // initialize ProviderCacheItem with the received data
                ProviderCacheItem item = new ProviderCacheItem(data);
                // you can change item properties before adding to cache. For example
                // adding expiration
                item.Expiration = new Expiration(ExpirationType.DefaultAbsolute);
                // assigning group to key
                item.Group = "customers";

                // add the provider item with the key to result
                providerItems.Add(key, item);
            }
            // return result to cache
            return(providerItems);
        }
Example #22
0
 /// <summary>
 /// Responsible for loading the object from the external data source.
 /// Key is passed as parameter.
 /// </summary>
 /// <param name="key">item identifier; probably a primary key</param>
 /// <param name="cacheItem">It is used to provide CacheItem information like Cache policies, dependencies, expirations ...</param>
 public void LoadFromSource(string key, out ProviderCacheItem cacheItem)
 {
     cacheItem = new ProviderCacheItem(_source.LoadCustomer(key));
 }
Example #23
0
        ProviderCacheItem GetProviderCacheItemFromCacheEntry(CacheEntry cacheEntry, object value, OperationContext operationContext)
        {
            ProviderCacheItem providerCacheItem = new ProviderCacheItem(value);

            if (cacheEntry.EvictionHint != null && cacheEntry.EvictionHint._hintType == EvictionHintType.PriorityEvictionHint)
            {
                providerCacheItem.ItemPriority = ((PriorityEvictionHint)cacheEntry.EvictionHint).Priority;
            }
            else
            {
                providerCacheItem.ItemPriority = cacheEntry.Priority;
            }
            if (cacheEntry.GroupInfo != null)
            {
                providerCacheItem.Group    = cacheEntry.GroupInfo.Group;
                providerCacheItem.SubGroup = cacheEntry.GroupInfo.SubGroup;
            }

            DateTime absoluteExpiration = DateTime.MaxValue.ToUniversalTime();
            TimeSpan slidingExpiration  = TimeSpan.Zero;

            ExpirationHint hint = cacheEntry.ExpirationHint;

            if (hint != null)
            {
                providerCacheItem.ResyncItemOnExpiration = hint.NeedsReSync;
                AutoExpiration.DependencyHelper helper = new AutoExpiration.DependencyHelper();
                providerCacheItem.Dependency = helper.GetActualCacheDependency(hint, ref absoluteExpiration, ref slidingExpiration);
            }

            if (absoluteExpiration != DateTime.MaxValue.ToUniversalTime())
            {
                providerCacheItem.AbsoluteExpiration = absoluteExpiration.ToLocalTime();
            }
            providerCacheItem.SlidingExpiration = slidingExpiration;

            if (cacheEntry.QueryInfo != null)
            {
                if (cacheEntry.QueryInfo["tag-info"] != null)
                {
                    Hashtable tagInfo = cacheEntry.QueryInfo["tag-info"] as Hashtable;
                    if (tagInfo != null)
                    {
                        ArrayList tagsList = tagInfo["tags-list"] as ArrayList;
                        if (tagsList != null && tagsList.Count > 0)
                        {
                            Tag[] tags = new Tag[tagsList.Count];
                            int   i    = 0;
                            foreach (string tag in tagsList)
                            {
                                tags[i++] = new Tag(tag);
                            }

                            providerCacheItem.Tags = tags;
                        }
                    }
                }

                if (cacheEntry.QueryInfo["named-tag-info"] != null)
                {
                    Hashtable tagInfo = cacheEntry.QueryInfo["named-tag-info"] as Hashtable;
                    if (tagInfo != null)
                    {
                        Hashtable tagsList = tagInfo["named-tags-list"] as Hashtable;
                        if (tagsList != null)
                        {
                            NamedTagsDictionary namedTags = new NamedTagsDictionary();

                            foreach (DictionaryEntry tag in tagsList)
                            {
                                Type   tagType = tag.Value.GetType();
                                string tagKey  = tag.Key.ToString();

                                if (tagType == typeof(int))
                                {
                                    namedTags.Add(tagKey, (int)tag.Value);
                                }
                                else if (tagType == typeof(long))
                                {
                                    namedTags.Add(tagKey, (long)tag.Value);
                                }
                                else if (tagType == typeof(float))
                                {
                                    namedTags.Add(tagKey, (float)tag.Value);
                                }
                                else if (tagType == typeof(double))
                                {
                                    namedTags.Add(tagKey, (double)tag.Value);
                                }
                                else if (tagType == typeof(decimal))
                                {
                                    namedTags.Add(tagKey, (decimal)tag.Value);
                                }
                                else if (tagType == typeof(bool))
                                {
                                    namedTags.Add(tagKey, (bool)tag.Value);
                                }
                                else if (tagType == typeof(char))
                                {
                                    namedTags.Add(tagKey, (char)tag.Value);
                                }
                                else if (tagType == typeof(string))
                                {
                                    namedTags.Add(tagKey, (string)tag.Value);
                                }
                                else if (tagType == typeof(DateTime))
                                {
                                    namedTags.Add(tagKey, (DateTime)tag.Value);
                                }
                            }

                            if (namedTags.Count > 0)
                            {
                                providerCacheItem.NamedTags = namedTags;
                            }
                        }
                    }
                }
            }
            providerCacheItem.ResyncProviderName = cacheEntry.ResyncProviderName;
            return(providerCacheItem);
        }
        /// <summary>
        /// Processa os dados carregados do LoadNext.
        /// </summary>
        /// <param name="data"></param>
        private void ProcessDataFromLoadNext(OrderedDictionary data)
        {
            int num = 0;

            byte[] buffer = null;
            foreach (DictionaryEntry entry in data)
            {
                EvictionHint hint2;
                num = 0;
                object            key  = null;
                ProviderCacheItem item = null;
                Colosoft.Caching.Expiration.ExpirationHint expiryHint = null;
                string    resyncProviderName = null;
                Hashtable queryInfo          = null;
                try
                {
                    if ((!(entry.Key is string) || !(entry.Value is ProviderCacheItem)))
                    {
                        throw new InvalidOperationException("Invalid Key/Value type specified");
                    }
                    key  = entry.Key;
                    item = (ProviderCacheItem)entry.Value;
                    if (item == null)
                    {
                        continue;
                    }
                    CacheLoaderUtil.EvaluateExpirationParameters(item.AbsoluteExpiration, item.SlidingExpiration);
                    expiryHint = Expiration.DependencyHelper.GetExpirationHint(item.Dependency, item.AbsoluteExpiration, item.SlidingExpiration);
                    if ((expiryHint != null) && item.ResyncItemOnExpiration)
                    {
                        expiryHint.SetBit(2);
                    }
                    resyncProviderName = (item.ResyncProviderName == null) ? null : item.ResyncProviderName.ToLower();
                    queryInfo          = new Hashtable();
                    TypeInfoMap typeInfoMap = _cache.GetTypeInfoMap();
                    if (typeInfoMap != null)
                    {
                        queryInfo["query-info"] = CacheLoaderUtil.GetQueryInfo(item.Value, typeInfoMap);
                    }
                    if (item.Tags != null)
                    {
                        queryInfo["tag-info"] = CacheLoaderUtil.GetTagInfo(item.Value, item.Tags);
                    }
                    if (item.NamedTags != null)
                    {
                        Hashtable hashtable2 = CacheLoaderUtil.GetNamedTagsInfo(item.Value, item.NamedTags, typeInfoMap);
                        if (hashtable2 != null)
                        {
                            queryInfo["named-tag-info"] = hashtable2;
                        }
                    }
                }
                catch (Exception exception3)
                {
                    OnProcessEntryError(entry, exception3);
                    continue;
                }
                var    set          = new BitSet();
                object currentValue = item.Value;
                try
                {
                    hint2 = new PriorityEvictionHint(item.ItemPriority);
                    if (!(currentValue is ICacheItemRecord))
                    {
                        buffer = this.SafeSerialize(currentValue) as byte[];
                        if ((buffer != null) && _cache.CompressionEnabled)
                        {
                            buffer = IO.Compression.CompressionUtil.Compress(buffer, ref set, _cache.CompressThresholdSize);
                        }
                        if (buffer != null)
                        {
                            currentValue = UserBinaryObject.CreateUserBinaryObject(buffer);
                        }
                    }
                }
                catch (Exception ex)
                {
                    OnLoadProcessingError(ex);
                    continue;
                }
                while (num <= this.NoOfRetries)
                {
                    if (_cache.IsRunning)
                    {
                        if (!CanInsertEntry(key, currentValue))
                        {
                            break;
                        }
                        try
                        {
                            _cache.Insert(key, currentValue, expiryHint, null, hint2, item.Group, item.SubGroup, queryInfo, set, null, 0, LockAccessType.IGNORE_LOCK, null, resyncProviderName, new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation));
                        }
                        catch (Exception exception4)
                        {
                            num++;
                            System.Threading.Thread.Sleep(this.RetryInterval);
                            if (num > this.NoOfRetries)
                            {
                                OnInsertEntryError(key, currentValue, exception4);
                                if (exception4 is OperationFailedException)
                                {
                                    if (((OperationFailedException)exception4).IsTracable || !_logger.IsErrorEnabled)
                                    {
                                        continue;
                                    }
                                    _logger.Error("CacheStartupLoader.Load()".GetFormatter(), exception4);
                                    break;
                                }
                                if (_logger.IsErrorEnabled)
                                {
                                    _logger.Error("CacheStartupLoader.Load()".GetFormatter(), exception4);
                                    break;
                                }
                            }
                            continue;
                        }
                        OnInsertedEntry(key, currentValue);
                    }
                    break;
                }
            }
        }
Example #25
0
        /// <summary>
        /// Responsible for loading the object from the external data source.
        /// Key is passed as parameter.
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        ///
        public void ReadThru(string key, out ProviderCacheItem item, OperationContext operationContext)
        {
            item = null;
            try
            {
                if (_dsReader is ICustomReadThru)
                {
                    if (operationContext.Contains(OperationContextFieldName.ReadThru))
                    {
                        ((ICustomReadThru)_dsReader).DoReadThru =
                            Convert.ToBoolean(operationContext.GetValueByField(OperationContextFieldName.ReadThru));
                    }
                    if (operationContext.Contains(OperationContextFieldName.ReadThru))
                    {
                        ((ICustomReadThru)_dsReader).ProviderName =
                            operationContext.GetValueByField(OperationContextFieldName.ReadThruProviderName) as string;
                    }

                    if (operationContext.Contains(OperationContextFieldName.GroupInfo))
                    {
                        GroupInfo gi = operationContext.GetValueByField(OperationContextFieldName.GroupInfo) as GroupInfo;
                        if (gi != null)
                        {
                            ((ICustomReadThru)_dsReader).Group    = gi.Group;
                            ((ICustomReadThru)_dsReader).SubGroup = gi.SubGroup;
                        }
                    }
                }

                Stopwatch readThruWatch = new Stopwatch();
                readThruWatch.Start();

                _dsReader.LoadFromSource(key, out item);
                readThruWatch.Stop();
                double elapsedByReadThru = readThruWatch.Elapsed.TotalSeconds;

                if (elapsedByReadThru > ServiceConfiguration.CommandExecutionThreshold &&
                    ServiceConfiguration.EnableCommandThresholdLogging)
                {
                    if (_context.NCacheLog != null)
                    {
                        _context.NCacheLog.Warn("ReadThruProviderMgr.ReadThru",
                                                "ReadThru took " + elapsedByReadThru +
                                                " seconds to complete. Which is longer than expected.");
                    }
                }

                this._context.PerfStatsColl.IncrementReadThruPerSec();
            }
            catch (Exception e)
            {
                //Client doesnt throw the inner exception
                //Client casts the thrown exception message into Operation failed Exception therefore the current inner exception will be casted
                //in Operation failed exception > Inner Exception > Inner Exception
                throw new OperationFailedException("IReadThruProvider.LoadFromSource failed. Error: " + e.ToString(), e);
            }
            finally
            {
                try
                {
                    // reset all here
                    ((ICustomReadThru)_dsReader).DoReadThru   = false;
                    ((ICustomReadThru)_dsReader).Group        = null;
                    ((ICustomReadThru)_dsReader).SubGroup     = null;
                    ((ICustomReadThru)_dsReader).ProviderName = null;
                }
                catch {}
            }
        }
Example #26
0
        /// <summary>
        /// Recupera uma entrada do cache.
        /// </summary>
        /// <param name="key"></param>
        /// <param name="item"></param>
        /// <param name="flag"></param>
        /// <param name="group"></param>
        /// <param name="subGroup"></param>
        /// <param name="cacheEntry"></param>
        /// <returns></returns>
        public UserBinaryObject GetCacheEntry(string key, ProviderCacheItem item, ref BitSet flag, string group, string subGroup, out CacheEntry cacheEntry)
        {
            UserBinaryObject val = null;

            cacheEntry = null;
            object serializableObject = null;

            if ((item != null) && (item.Value != null))
            {
                if ((item.Group == null) && (item.SubGroup != null))
                {
                    throw new OperationFailedException("Error occurred while synchronization with data source; group must be specified for sub group");
                }
                if ((group != null) && !CacheHelper.CheckDataGroupsCompatibility(new GroupInfo(item.Group, item.SubGroup), new GroupInfo(group, subGroup)))
                {
                    throw new OperationFailedException("Error occurred while synchronization with data source; groups are incompatible");
                }
                if (flag == null)
                {
                    flag = new BitSet();
                }
                serializableObject = item.Value;
                Hashtable   hashtable   = new Hashtable();
                TypeInfoMap typeInfoMap = _context.CacheRoot.GetTypeInfoMap();
                hashtable["query-info"] = CacheLoaderUtil.GetQueryInfo(item.Value, typeInfoMap);
                if (item.Tags != null)
                {
                    Hashtable tagInfo = CacheLoaderUtil.GetTagInfo(item.Value, item.Tags);
                    if (tagInfo != null)
                    {
                        hashtable.Add("tag-info", tagInfo);
                    }
                }
                if (item.NamedTags != null)
                {
                    try
                    {
                        Hashtable hashtable3 = CacheLoaderUtil.GetNamedTagsInfo(item.Value, item.NamedTags, typeInfoMap);
                        if (hashtable3 != null)
                        {
                            hashtable.Add("named-tag-info", hashtable3);
                        }
                    }
                    catch (Exception exception)
                    {
                        throw new OperationFailedException("Error occurred while synchronization with data source; " + exception.Message);
                    }
                }
                if (!item.Value.GetType().IsSerializable&& !_type.IsAssignableFrom(item.Value.GetType()))
                {
                    throw new OperationFailedException("Read through provider returned an object that is not serializable.");
                }
                serializableObject = SerializationUtil.SafeSerialize(serializableObject, _context.SerializationContext, ref flag);
                if (_context.CompressionEnabled)
                {
                    item.Value = CompressionUtil.Compress(item.Value as byte[], ref flag, _context.CompressionThreshold);
                }
                val = UserBinaryObject.CreateUserBinaryObject(serializableObject as byte[]);
                EvictionHint   evictionHint = new PriorityEvictionHint(item.ItemPriority);
                ExpirationHint expiryHint   = DependencyHelper.GetExpirationHint(item.Dependency, item.AbsoluteExpiration, item.SlidingExpiration);
                if (expiryHint != null)
                {
                    expiryHint.CacheKey = key;
                    if (item.ResyncItemOnExpiration)
                    {
                        expiryHint.SetBit(2);
                    }
                }
                cacheEntry                    = new CacheEntry(val, expiryHint, evictionHint);
                cacheEntry.Flag               = flag;
                cacheEntry.GroupInfo          = new GroupInfo(item.Group, item.SubGroup);
                cacheEntry.QueryInfo          = hashtable;
                cacheEntry.ResyncProviderName = (item.ResyncProviderName == null) ? null : item.ResyncProviderName.ToLower();
            }
            return(val);
        }
Example #27
0
 /// <summary>
 /// Responsible for loading the object from the external data source.
 /// Key is passed as parameter.
 /// <param name="key">item identifier; probably a primary key</param>
 /// <param name="exh">Current expiration hint; you can modify the value and attach a new hint</param>
 /// <param name="evh">Current eviction hint; you can modify the value and attach a new hint</param>
 /// <returns></returns>
 public void LoadFromSource(string key, out ProviderCacheItem cacheItem)
 {
     cacheItem = new ProviderCacheItem(sqlDatasource.LoadCustomer(key));
     cacheItem.ResyncItemOnExpiration = true;
     cacheItem.ResyncProviderName     = sqlDatasource.ConnString;
 }
Example #28
0
 public InternalWriteOperation(string key, ProviderCacheItem cacheItem, WriteOperationType opType, int retryCount) : base(key, cacheItem, opType, retryCount)
 {
 }