示例#1
0
        public override void ExecuteCommand(ClientManager clientManager, Alachisoft.NCache.Common.Protobuf.Command command)
        {
            int       overload;
            string    exception = null;
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();
            try
            {
                overload = command.MethodOverload;
                cmdInfo  = ParseCommand(command, clientManager);
            }
            catch (Exception exc)
            {
                _removeQueryResult = OperationResult.Failure;
                if (!base.immatureId.Equals("-2"))
                {
                    _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID, command.commandID));
                }
                return;
            }

            byte[] data = null;

            try
            {
                NCache nCache = clientManager.CmdExecuter as NCache;

                OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                operationContext.Add(OperationContextFieldName.RaiseCQNotification, true);
                operationContext.Add(OperationContextFieldName.ClientLastViewId, cmdInfo.ClientLastViewId);
                operationContext.Add(OperationContextFieldName.RemoveQueryOperation, true);

                removeRes = nCache.Cache.RemoveQuery(cmdInfo.Query, cmdInfo.Values, operationContext);
                stopWatch.Stop();
                RemoveQueryResponseBuilder.BuildResponse(removeRes, cmdInfo.CommandVersion, cmdInfo.RequestId, _serializedResponsePackets, command.commandID, nCache.Cache);
            }
            catch (Exception exc)
            {
                _removeQueryResult = OperationResult.Failure;
                exception          = exc.ToString();
                //PROTOBUF:RESPONSE
                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID, command.commandID));
            }
            finally
            {
                TimeSpan executionTime = stopWatch.Elapsed;
                try
                {
                    if (Alachisoft.NCache.Management.APILogging.APILogManager.APILogManger != null && Alachisoft.NCache.Management.APILogging.APILogManager.EnableLogging)
                    {
                        APILogItemBuilder log = new APILogItemBuilder(MethodsName.ExecuteNonQuery.ToLower());
                        log.GenerateDeleteQueryAPILogItem(cmdInfo.Query, cmdInfo.Values, 1, exception, executionTime, clientManager.ClientID.ToLower(), clientManager.ClientSocketId.ToString());
                    }
                }
                catch
                {
                }
            }
        }
示例#2
0
        public override void ExecuteCommand(ClientManager clientManager, Alachisoft.NCache.Common.Protobuf.Command command)
        {
            CommandInfo cmdInfo;

            ClientId = clientManager.ClientID;

            NCache nCache = clientManager.CmdExecuter as NCache;

            try
            {
                serailizationContext = nCache.CacheId;
                cmdInfo = base.ParseCommand(command, clientManager, serailizationContext);
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("BulkInsCmd.Exec", "cmd parsed");
                }
            }
            catch (Exception exc)
            {
                _insertBulkResult = OperationResult.Failure;
                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID));
                return;
            }

            byte[] dataPackage = null;

            try
            {
                OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                operationContext.Add(OperationContextFieldName.ClientLastViewId, cmdInfo.ClientLastViewId);
                if (!string.IsNullOrEmpty(cmdInfo.IntendedRecipient))
                {
                    operationContext.Add(OperationContextFieldName.IntendedRecipient, cmdInfo.IntendedRecipient);
                }

                Hashtable insertResult = (Hashtable)nCache.Cache.Insert(cmdInfo.Keys, cmdInfo.Entries, operationContext);
                Alachisoft.NCache.Common.Protobuf.Response           response           = new Alachisoft.NCache.Common.Protobuf.Response();
                Alachisoft.NCache.Common.Protobuf.BulkInsertResponse bulkInsertResponse = new Alachisoft.NCache.Common.Protobuf.BulkInsertResponse();
                response.requestId                     = Convert.ToInt64(cmdInfo.RequestId);
                response.intendedRecipient             = cmdInfo.IntendedRecipient;
                bulkInsertResponse.keyExceptionPackage = new Alachisoft.NCache.Common.Protobuf.KeyExceptionPackageResponse();

                //TODO : Package Key Value
                Alachisoft.NCache.SocketServer.Util.KeyPackageBuilder.PackageKeysExceptions(insertResult, bulkInsertResponse.keyExceptionPackage);

                response.responseType = Alachisoft.NCache.Common.Protobuf.Response.Type.INSERT_BULK;
                response.bulkInsert   = bulkInsertResponse;
                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response));
            }
            catch (Exception exc)
            {
                _insertBulkResult = OperationResult.Failure;
                //PROTOBUF:RESPONSE
                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID));
            }
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("BulkInsCmd.Exec", "cmd executed on cache");
            }
        }
示例#3
0
        public override void ExecuteCommand(ClientManager clientManager, Common.Protobuf.Command command)
        {
            System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
            stopWatch.Start();
            int    overload         = 1;
            string exceptionMessage = null;
            bool   result           = false;

            try
            {
                NCache nCache           = clientManager.CmdExecuter as NCache;
                var    operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                if (command.commandVersion < 1)
                {
                    operationContext.Add(OperationContextFieldName.ClientLastViewId, forcedViewId);
                }
                else
                {
                    operationContext.Add(OperationContextFieldName.ClientLastViewId, command.clientLastViewId.ToString(CultureInfo.InvariantCulture));
                }
                if (nCache != null)
                {
                    _command = command.removeTopicCommand;
                    TopicOperation topicOperation = new TopicOperation(_command.topicName, TopicOperationType.Remove);

                    result = nCache.Cache.TopicOpertion(topicOperation, operationContext);

                    Common.Protobuf.Response            response            = new Common.Protobuf.Response();
                    Common.Protobuf.RemoveTopicResponse removeTopicResponse = new Common.Protobuf.RemoveTopicResponse();
                    response.requestId           = _command.requestId;
                    response.commandID           = command.commandID;
                    removeTopicResponse.success  = result;
                    response.responseType        = Common.Protobuf.Response.Type.REMOVE_TOPIC;
                    response.removeTopicResponse = removeTopicResponse;
                    _serializedResponsePackets.Add(ResponseHelper.SerializeResponse(response));
                }
            }
            catch (Exception exc)
            {
                exceptionMessage = exc.ToString();
                _serializedResponsePackets.Add(ResponseHelper.SerializeExceptionResponse(exc, command.requestID, command.commandID));
            }
            finally
            {
                TimeSpan executionTime = stopWatch.Elapsed;
                try
                {
                    if (Alachisoft.NCache.Management.APILogging.APILogManager.APILogManger != null && Alachisoft.NCache.Management.APILogging.APILogManager.EnableLogging)
                    {
                        APILogItemBuilder log = new APILogItemBuilder(MethodsName.DeleteTopic);
                        log.GenerateGetCreateOrDeleteTopicAPILogItem(_command.topicName, executionTime, clientManager.ClientID, clientManager.ClientIP, overload, result, exceptionMessage);
                    }
                }
                catch
                {
                }
            }
        }
示例#4
0
        public override void ExecuteCommand(ClientManager clientManager, Common.Protobuf.Command command)
        {
            System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
            stopWatch.Start();
            int    overload         = 1;
            string exceptionMessage = null;

            try
            {
                NCache nCache = clientManager.CmdExecuter as NCache;
                if (nCache != null)
                {
                    _command = command.getMessageCommand;
                    var operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                    if (command.commandVersion < 1)
                    {
                        operationContext.Add(OperationContextFieldName.ClientLastViewId, forcedViewId);
                    }
                    else // NCache 4.1 SP1 or later
                    {
                        operationContext.Add(OperationContextFieldName.ClientLastViewId, command.clientLastViewId.ToString(CultureInfo.InvariantCulture));
                    }
                    _clientId = clientManager.ClientID;
                    SubscriptionInfo subInfo = new SubscriptionInfo()
                    {
                        ClientId = clientManager.ClientID
                    };
                    _result = nCache.Cache.GetAssignedMessages(subInfo, operationContext);
                    GetMessageResponseBuilder.BuildResponse(_result, command.commandVersion, _command.requestId.ToString(CultureInfo.InvariantCulture), _serializedResponsePackets, command.commandID, nCache.Cache);
                }
            }
            catch (System.Exception exc)
            {
                exceptionMessage = exc.ToString();
                _serializedResponsePackets.Add(ResponseHelper.SerializeExceptionResponse(exc, command.requestID, command.commandID));
            }
            finally
            {
                TimeSpan executionTime = stopWatch.Elapsed;
                try
                {
                    if (Alachisoft.NCache.Management.APILogging.APILogManager.APILogManger != null && Alachisoft.NCache.Management.APILogging.APILogManager.EnableLogging)
                    {
                        APILogItemBuilder log = new APILogItemBuilder(MethodsName.GetTopicMessages);
                        log.GenerateGetTopicMessagesAPILogItem(executionTime, clientManager.ClientID, clientManager.ClientIP, overload, _result, exceptionMessage);
                    }
                }
                catch
                {
                }
            }
        }
示例#5
0
        public override void ExecuteCommand(ClientManager clientManager, Alachisoft.NCache.Common.Protobuf.Command command)
        {
            CommandInfo cmdInfo;

            try
            {
                cmdInfo = ParseCommand(command, clientManager);
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("BulkGetCmd.Exec", "cmd parsed");
                }
            }
            catch (Exception exc)
            {
                _getBulkResult = OperationResult.Failure;
                if (!base.immatureId.Equals("-2"))
                {
                    //PROTOBUF:RESPONSE
                    _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID));
                }
                return;
            }

            byte[] data = null;

            NCache nCache = clientManager.CmdExecuter as NCache;

            try
            {
                OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                operationContext.Add(OperationContextFieldName.ClientLastViewId, cmdInfo.ClientLastViewId);
                if (!string.IsNullOrEmpty(cmdInfo.IntendedRecipient))
                {
                    operationContext.Add(OperationContextFieldName.IntendedRecipient, cmdInfo.IntendedRecipient);
                }

                Hashtable getResult = (Hashtable)nCache.Cache.GetBulk(cmdInfo.Keys, cmdInfo.FlagMap, operationContext);

                BulkGetResponseBuilder.BuildResponse(getResult, cmdInfo.CommandVersion, cmdInfo.RequestId, _serializedResponsePackets, cmdInfo.IntendedRecipient);
            }
            catch (Exception exc)
            {
                _getBulkResult = OperationResult.Failure;
                //PROTOBUF:RESPONSE
                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID));
            }
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("BulkGetCmd.Exec", "cmd executed on cache");
            }
        }
示例#6
0
        public override void ExecuteCommand(ClientManager clientManager, Alachisoft.NCache.Common.Protobuf.Command command)
        {
            CommandInfo cmdInfo;

            try
            {
                cmdInfo = ParseCommand(command, clientManager);
            }
            catch (Exception exc)
            {
                _removeBulkResult = OperationResult.Failure;
                if (!base.immatureId.Equals("-2"))
                {
                    //PROTOBUF:RESPONSE
                    _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID));
                }
                return;
            }

            //TODO
            byte[] data = null;

            try
            {
                NCache           nCache           = clientManager.CmdExecuter as NCache;
                CallbackEntry    cbEnrty          = null;
                OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                operationContext.Add(OperationContextFieldName.ClientLastViewId, cmdInfo.ClientLastViewId);
                if (!string.IsNullOrEmpty(cmdInfo.IntendedRecipient))
                {
                    operationContext.Add(OperationContextFieldName.IntendedRecipient, cmdInfo.IntendedRecipient);
                }

                nCache.Cache.Delete(cmdInfo.Keys, cmdInfo.FlagMap, cbEnrty, operationContext);

                Alachisoft.NCache.Common.Protobuf.Response           response           = new Alachisoft.NCache.Common.Protobuf.Response();
                Alachisoft.NCache.Common.Protobuf.BulkDeleteResponse bulkDeleteResponse = new Alachisoft.NCache.Common.Protobuf.BulkDeleteResponse();
                response.requestId         = Convert.ToInt64(cmdInfo.RequestId);
                response.intendedRecipient = cmdInfo.IntendedRecipient;

                response.responseType       = Alachisoft.NCache.Common.Protobuf.Response.Type.DELETE_BULK;
                response.bulkDeleteResponse = bulkDeleteResponse;
                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response));
            }
            catch (Exception exc)
            {
                _removeBulkResult = OperationResult.Failure;
                //PROTOBUF:RESPONSE
                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID));
            }
        }
示例#7
0
        /// <summary>
        /// Implementation of message sending.
        /// </summary>
        void AsyncProcessor.IAsyncTask.Process()
        {
            object result = null;

            try
            {
                _operationContext.Add(OperationContextFieldName.NoGracefulBlock, true);
                _cache.Insert(_key, _value, _expiryHint, _evictionHint, _group, _subGroup, _queryInfo, _flag, _operationContext, null, _cbEntry, _type);
                result = NCache.Caching.AsyncOpResult.Success;
            }
            catch (Exception e)
            {
                if (NCacheLog != null)
                {
                    NCacheLog.Error("AsyncInsert.Process()", e.Message);
                }
                result = e;
            }
            finally
            {
                if (_cbEntry != null && _cbEntry.AsyncOperationCompleteCallback != null)
                {
                    _cache.OnAsyncOperationCompleted(AsyncOpCode.Update, new object[] { _key, _cbEntry.AsyncOperationCompleteCallback, result });
                }
            }
        }
示例#8
0
        /// <summary>
        /// Implementation of message sending.
        /// </summary>
        ///
        void AsyncProcessor.IAsyncTask.Process()
        {
            object result = null;

            try
            {
                _operationContext.Add(OperationContextFieldName.NoGracefulBlock, true);
                _cache.Clear(_flagMap, _cbEntry, _operationContext);
                result = AsyncOpResult.Success;
            }
            catch (Exception e)
            {
                if (NCacheLog != null)
                {
                    NCacheLog.Error("AsyncClear.Process()", e.Message);
                }
                result = e;
            }
            finally
            {
                if (_cbEntry != null && _cbEntry.AsyncOperationCompleteCallback != null)
                {
                    _cache.OnAsyncOperationCompleted(AsyncOpCode.Clear, new object[] { null, _cbEntry.AsyncOperationCompleteCallback, result });
                }
            }
        }
示例#9
0
        /// <summary>
        /// Implementation of message sending.
        /// </summary>
        void AsyncProcessor.IAsyncTask.Process()
        {
            object result = null;

            try
            {
                _operationContext.Add(OperationContextFieldName.NoGracefulBlock, true);
                _cache.Add(_key, _value, _expiryHint, _syncDependency, _evictionHint, _group, _subGroup, _queryInfo, _flag, _provider, null, _operationContext, null);
                result = AsyncOpResult.Success;
            }
            catch (Exception e)
            {
                if (NCacheLog != null)
                {
                    NCacheLog.Error("AsyncAdd.Process()", e.Message);
                }
                result = e;
            }
            finally
            {
                CallbackEntry cbEntry = _value as CallbackEntry;
                if (cbEntry != null && cbEntry.AsyncOperationCompleteCallback != null)
                {
                    _cache.OnAsyncOperationCompleted(AsyncOpCode.Add, new object[] { _key, cbEntry.AsyncOperationCompleteCallback, result });
                }
            }
        }
示例#10
0
        private void AddInsertLoggedOperations(ArrayList updatedKeys, ArrayList loggedOperations)
        {
            CacheEntry entry = null;

            if (updatedKeys != null && updatedKeys.Count > 0)
            {
                for (int i = 0; i < updatedKeys.Count; i++)
                {
                    string           key = updatedKeys[i] as string;
                    OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                    operationContext.Add(OperationContextFieldName.GenerateQueryInfo, true);
                    operationContext.UseObjectPool = false;
                    try
                    {
                        entry = _parent.InternalCache.Get(key, false, operationContext);
                        if (entry != null)
                        {
                            entry.MarkInUse(NCModulesConstants.StateTransfer);
                        }
                        loggedOperations.Add(new InsertLoggedOperation(key, entry));
                    }
                    finally
                    {
                        if (entry != null)
                        {
                            entry.MarkFree(NCModulesConstants.Replication);
                        }
                    }
                }
            }
        }
示例#11
0
        public async Task <IActionResult> Create([Bind("Ailments,Clothes,DateOfBirth,EyesColour,FurtherInformation,Gender,HairColor,KnownPlaces,Medications,MissingSince,Name,OperationId,Size,SkinType,SpecialCharacteristics,Weight")] MissingPerson missingPerson)
        {
            if (ModelState.IsValid)
            {
                _context.Add(missingPerson);
                await _context.SaveChangesAsync();

                OperationActionsController operationActionsController = new OperationActionsController(_context);
                await operationActionsController.Create(missingPerson.OperationId,
                                                        "Vermisstendaten erfasst",
                                                        string.Empty,
                                                        $"{missingPerson.Name}, vermisst seit {missingPerson.MissingSince}"); // TODO: I18n

                return(RedirectToAction(nameof(Index), new { id = missingPerson.OperationId }));
            }
            return(View(missingPerson));
        }
示例#12
0
        public async Task <IActionResult> Create([Bind("Dog,Id,Name,Type")] Person person)
        {
            if (ModelState.IsValid)
            {
                _context.Add(person);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(person));
        }
示例#13
0
        private void AddNamedTag(object key, Hashtable value, CacheEntry entry, OperationContext operationContext)
        {
            string    type     = value["type"] as string;
            Hashtable tagsList = ((Hashtable)value["named-tags-list"]).Clone() as Hashtable;

            if (tagsList != null && type != null)
            {
                Hashtable   metaInfoAttribs = (Hashtable)tagsList.Clone();
                IQueryIndex index;

                lock (_indexMap.SyncRoot)
                {
                    if (!_indexMap.Contains(type))
                    {
                        if (_sharedAttributeIndex != null && _sharedAttributeIndex.ContainsKey(type))
                        {
                            AttributeIndex tempAttrib = _sharedAttributeIndex[type];
                            tempAttrib.Initialize(new ArrayList());
                            _indexMap.Add(type, tempAttrib);
                        }
                        else
                        {
                            _indexMap[type] = new AttributeIndex(null, _cacheName, type, true);
                        }
                    }

                    index = _indexMap[type] as IQueryIndex;

                    if (index != null)
                    {
                        long prevSize = index.IndexInMemorySize;

                        index.AddToIndex(key, new QueryItemContainer(entry, tagsList));

                        _queryIndexMemorySize += index.IndexInMemorySize - prevSize;
                    }
                }

                if (operationContext.Contains(OperationContextFieldName.IndexMetaInfo))
                {
                    MetaInformation metaInformation =
                        (MetaInformation)operationContext.GetValueByField(OperationContextFieldName.IndexMetaInfo);
                    metaInformation.Add(metaInfoAttribs);
                }
                else
                {
                    MetaInformation metaInformation = new MetaInformation(metaInfoAttribs);
                    metaInformation.CacheKey = key as string;
                    metaInformation.Type     = value["type"] as string;
                    operationContext.Add(OperationContextFieldName.IndexMetaInfo, metaInformation);
                    entry.ObjectType = value["type"] as string;
                }
            }
        }
示例#14
0
        public async Task <IActionResult> Create([Bind("Id,Name,AlertDate,AlertTime")] Operation operation)
        {
            if (ModelState.IsValid)
            {
                _context.Add(operation);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Details), new { Id = operation.Id }));
            }

            return(View(operation));
        }
示例#15
0
        private EPCacheEntry GetEPCacheEntry(Object key, Boolean ignoreLock, OperationContext operationContext)
        {
            Object   lockId   = null;
            ulong    version  = 0;
            DateTime time     = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            DateTime lockDate = time.Date;
            BitSet   flagMap  = new BitSet();

            operationContext.Add(OperationContextFieldName.ReaderBitsetEnum, flagMap);
            operationContext.Add(OperationContextFieldName.DataFormat, DataFormat.Object);
            operationContext.Add(OperationContextFieldName.GenerateQueryInfo, true);

            LockAccessType lockAccessType = LockAccessType.IGNORE_LOCK;

            if (!ignoreLock)
            {
                lockAccessType = LockAccessType.ACQUIRE;
            }

            CacheEntry entry = (CacheEntry)_cacheRoot.GetCacheEntry(key, null, null, ref lockId, ref lockDate, EntryProcessorManager.DefaultLockTimeOut, lockAccessType, operationContext, ref version);

            LockHandle handle = null;

            if (lockId != null)
            {
                handle = new LockHandle(lockId.ToString(), lockDate);
            }

            if (entry != null)
            {
                CallbackEntry callbackEntry = entry.Value as CallbackEntry;
                object        value         = callbackEntry != null ? callbackEntry.Value : entry.Value;
                if (value != null)
                {
                    entry.Value = _context.CachingSubSystemDataService.GetCacheData(value, entry.Flag);
                }
            }

            return(new EPCacheEntry(entry, handle));
        }
示例#16
0
        //PROTOBUF

        public override void ExecuteCommand(ClientManager clientManager, Alachisoft.NCache.Common.Protobuf.Command command)
        {
            CommandInfo cmdInfo;

            try
            {
                cmdInfo = ParseCommand(command, clientManager);
            }
            catch (Exception exc)
            {
                if (!base.immatureId.Equals("-2"))
                {
                    _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID));
                }
                return;
            }

            NCache nCache = clientManager.CmdExecuter as NCache;

            try
            {
                object           lockId           = cmdInfo.LockId;
                DateTime         lockDate         = new DateTime();
                OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                operationContext.Add(OperationContextFieldName.GenerateQueryInfo, true);
                CacheEntry entry = (CacheEntry)nCache.Cache.GetCacheEntry(cmdInfo.Key, ref lockId, ref lockDate, cmdInfo.LockTimeout, cmdInfo.LockAccessType, operationContext);

                Alachisoft.NCache.Common.Protobuf.GetCacheItemResponse getCacheItemResponse = new Alachisoft.NCache.Common.Protobuf.GetCacheItemResponse();
                Alachisoft.NCache.Common.Protobuf.Response             response             = new Alachisoft.NCache.Common.Protobuf.Response();
                response.requestId    = Convert.ToInt64(cmdInfo.RequestId);
                response.responseType = Alachisoft.NCache.Common.Protobuf.Response.Type.GET_CACHE_ITEM;

                if (entry == null)
                {
                    getCacheItemResponse.lockId    = lockId == null ? string.Empty : lockId.ToString();
                    getCacheItemResponse.lockTicks = lockDate.Ticks;
                    response.getItem = getCacheItemResponse;
                    _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response));
                    return;
                }

                getCacheItemResponse = PopulateResponse(entry, getCacheItemResponse, clientManager);
                response.getItem     = getCacheItemResponse;

                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response));
            }
            catch (Exception exc)
            {
                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID));
            }
        }
示例#17
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);
                }
            }
        }
示例#18
0
        public async Task <IActionResult> Create([Bind("Name,GroupLeader,PagerNumber,OperationId,AreaSeeker,DebrisSearcher,WaterLocators,Mantrailer,Helpers")] Unit unit)
        {
            if (ModelState.IsValid)
            {
                _context.Add(unit);
                await _context.SaveChangesAsync();

                OperationActionsController operationActionsController = new OperationActionsController(_context);
                await operationActionsController.Create(unit.OperationId, "Einheit eingetroffen / erfasst", unit.Name); // TODO: I18n

                return(RedirectToAction(nameof(Index), new { id = unit.OperationId }));
            }
            return(View(unit));
        }
        private StateTxfrInfo GetMessages(int bucketId)
        {
            long sizeToSend = 0;

            if (_parent.Context.NCacheLog.IsInfoEnabled)
            {
                _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "bucket size :" + _keyList.Count);
            }

            foreach (DictionaryEntry topicWiseMessage in _topicWiseMessageList)
            {
                ClusteredArrayList messageList = topicWiseMessage.Value as ClusteredArrayList;

                foreach (string messageId in messageList)
                {
                    OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                    operationContext.Add(OperationContextFieldName.GenerateQueryInfo, true);
                    TransferrableMessage message = _parent.InternalCache.GetTransferrableMessage(topicWiseMessage.Key as string, messageId);
                    if (message != null)
                    {
                        if (sizeToSend > _threshold)
                        {
                            break;
                        }

                        ClusteredArrayList transferrableMessageList = _result[topicWiseMessage.Key] as ClusteredArrayList;
                        if (transferrableMessageList == null)
                        {
                            transferrableMessageList = new ClusteredArrayList();
                            _result.Add(topicWiseMessage.Key, transferrableMessageList);
                        }
                        _messageCount++;
                        transferrableMessageList.Add(message);
                        sizeToSend += message.Message.Size;
                    }
                }
            }
            if (_parent.Context.NCacheLog.IsInfoEnabled)
            {
                _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "items sent :" + _keyCount);
            }

            if (_parent.Context.NCacheLog.IsInfoEnabled)
            {
                _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "BalanceDataLoad = " + _isBalanceDataLoad.ToString());
            }
            _parent.Context.PerfStatsColl.IncrementStateTxfrPerSecStatsBy(_result.Count);

            return(new StateTxfrInfo(_result, false, sizeToSend, this.stream, true));
        }
示例#20
0
        public override void ExecuteCommand(ClientManager clientManager, Common.Protobuf.Command command)
        {
            CommandInfo cmdInfo;

            try
            {
                cmdInfo = ParseCommand(command, clientManager);
            }
            catch (Exception exc)
            {
                if (!base.immatureId.Equals("-2"))
                {
                    //_commandBytes = clientManager.ReplyPacket(base.ExceptionPacket(exc, base.immatureId), base.ParsingExceptionMessage(exc));
                    //PROTOBUF:RESPONSE
                    _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponseWithType(exc, command.requestID, command.commandID, clientManager.ClientVersion));
                }
                return;
            }

            try
            {
                NCache           nCache  = clientManager.CmdExecuter as NCache;
                OperationContext context = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                context.Add(OperationContextFieldName.ClientId, clientManager.ClientID);

                nCache.Cache.RegisterPollingNotification(cmdInfo.PollingCallbackId, context);

                //PROTOBUF:RESPONSE
                Alachisoft.NCache.Common.Protobuf.RegisterPollNotifResponse registerNotifResponse = new Alachisoft.NCache.Common.Protobuf.RegisterPollNotifResponse();

                if (clientManager.ClientVersion >= 5000)
                {
                    Common.Util.ResponseHelper.SetResponse(registerNotifResponse, command.requestID, command.commandID);
                    _serializedResponsePackets.Add(Common.Util.ResponseHelper.SerializeResponse(registerNotifResponse, Common.Protobuf.Response.Type.REGISTER_POLL_NOTIF));
                }
                else
                {
                    Common.Protobuf.Response response = new Common.Protobuf.Response();
                    response.registerPollNotifResponse = registerNotifResponse;
                    Common.Util.ResponseHelper.SetResponse(response, command.requestID, command.commandID, Common.Protobuf.Response.Type.REGISTER_POLL_NOTIF);
                    _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response));
                }
            }
            catch (Exception exc)
            {
                //PROTOBUF:RESPONSE
                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponseWithType(exc, command.requestID, command.commandID, clientManager.ClientVersion));
            }
        }
示例#21
0
        /// <summary>
        /// Implementation of message sending.
        /// </summary>
        void AsyncProcessor.IAsyncTask.Process()
        {
            object result = null;

            BitSet        flagMap      = null;
            Notifications notification = null;
            string        providerName = null;

            try
            {
                flagMap = BitSet.CreateAndMarkInUse(_cache.Context.FakeObjectPool, NCModulesConstants.AsyncCrud);
                if (_key is object[])
                {
                    object[] package = (object[])_key;
                    _key    = package[0];
                    flagMap = package[1] as BitSet;
                    if (package.Length > 2)
                    {
                        notification = package[2] as Notifications;
                    }
                    if (package.Length == 4)
                    {
                        providerName = package[3] as string;
                    }
                }
                _operationContext.Add(OperationContextFieldName.NoGracefulBlock, true);
                _cache.Remove(_key as string, flagMap, notification, null, 0, LockAccessType.IGNORE_LOCK, providerName, _operationContext);
                result = AsyncOpResult.Success;
            }
            catch (Exception e)
            {
                if (NCacheLog != null)
                {
                    NCacheLog.Error("AsyncRemove.Process()", e.Message);
                }
                result = e;
            }
            finally
            {
                flagMap?.MarkFree(NCModulesConstants.AsyncCrud);
                if (notification != null && notification.AsyncOperationCompleteCallback != null)
                {
                    _cache.OnAsyncOperationCompleted(AsyncOpCode.Remove, new object[] { _key, notification.AsyncOperationCompleteCallback, result });
                }
            }
        }
示例#22
0
        private void RemoveEPCacheEntry(string key, EPCacheEntry epCacheEntry, BitSet flag, String writethruProvider)
        {
            CacheEntry     entry      = epCacheEntry.CacheEntry;
            object         lockID     = null;
            LockAccessType lockAccess = LockAccessType.IGNORE_LOCK;

            if (epCacheEntry.LockHandle != null)
            {
                lockAccess = LockAccessType.DEFAULT;
                lockID     = epCacheEntry.LockHandle.LockId;
            }

            OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);

            operationContext.Add(OperationContextFieldName.RaiseCQNotification, true);

            _cacheRoot.Remove(key, flag, null, lockID, 0, lockAccess, writethruProvider, operationContext);
        }
示例#23
0
        public async Task <IActionResult> Create(string operationId, string oAction, string unitName = "", string message = "")
        {
            if (ParameterCombinationIsValid(oAction, unitName, message))
            {
                var operationAction = new OperationAction
                {
                    Created     = DateTime.Now,
                    OperationId = operationId,
                    Action      = oAction,
                    UnitName    = unitName,
                    Message     = message
                };

                _context.Add(operationAction);
                await _context.SaveChangesAsync();
            }

            return(RedirectToAction("Details", "Operations", new { id = operationId }));
        }
示例#24
0
        /// <summary>
        /// Implementation of message sending.
        /// </summary>
        void AsyncProcessor.IAsyncTask.Process()
        {
            object        result       = null;
            BitSet        flagMap      = new BitSet();
            CallbackEntry cbEntry      = null;
            string        providerName = null;

            try
            {
                if (_key is object[])
                {
                    object[] package = (object[])_key;
                    _key    = package[0];
                    flagMap = package[1] as BitSet;
                    if (package.Length > 2)
                    {
                        cbEntry = package[2] as CallbackEntry;
                    }
                    if (package.Length == 4)
                    {
                        providerName = package[3] as string;
                    }
                }
                _operationContext.Add(OperationContextFieldName.NoGracefulBlock, true);
                _cache.Remove(_key as string, flagMap, cbEntry, null, 0, LockAccessType.IGNORE_LOCK, providerName, _operationContext);
                result = AsyncOpResult.Success;
            }
            catch (Exception e)
            {
                if (NCacheLog != null)
                {
                    NCacheLog.Error("AsyncRemove.Process()", e.Message);
                }
                result = e;
            }
            finally
            {
                if (cbEntry != null && cbEntry.AsyncOperationCompleteCallback != null)
                {
                    _cache.OnAsyncOperationCompleted(AsyncOpCode.Remove, new object[] { _key, cbEntry.AsyncOperationCompleteCallback, result });
                }
            }
        }
        private StateTxfrInfo GetCacheItems(int bucketId)
        {
            long sizeToSend = 0;

            if (_parent.Context.NCacheLog.IsInfoEnabled)
            {
                _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "bucket size :" + _keyList.Count);
            }

            for (_keyCount = 0; _keyCount < _keyList.Count; _keyCount++)
            {
                string key = _keyList[_keyCount] as string;

                OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                operationContext.Add(OperationContextFieldName.GenerateQueryInfo, true);
                CacheEntry entry = _parent.InternalCache.InternalCache.Get(key, false, operationContext);
                if (entry != null)
                {
                    long size = (entry.InMemorySize + Common.MemoryUtil.GetStringSize(key));//.DataSize;
                    if (sizeToSend > _threshold)
                    {
                        break;
                    }

                    _result[key] = entry;
                    sizeToSend  += size;
                }
            }
            if (_parent.Context.NCacheLog.IsInfoEnabled)
            {
                _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "items sent :" + _keyCount);
            }

            if (_parent.Context.NCacheLog.IsInfoEnabled)
            {
                _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "BalanceDataLoad = " + _isBalanceDataLoad.ToString());
            }

            _parent.Context.PerfStatsColl.IncrementStateTxfrPerSecStatsBy(_result.Count);

            return(new StateTxfrInfo(_result, false, sizeToSend, this.stream, false));
        }
示例#26
0
        public override void ExecuteCommand(ClientManager clientManager, Common.Protobuf.Command command)
        {
            long   requestId;
            string taskId;
            short  callbackId;
            long   clientLastViewId;

            Common.Protobuf.TaskEnumeratorCommand taskEnumeratorCommand = command.TaskEnumeratorCommand;
            taskId           = taskEnumeratorCommand.TaskId;
            requestId        = command.requestID;
            callbackId       = (short)taskEnumeratorCommand.CallbackId;
            clientLastViewId = command.clientLastViewId;
            try
            {
                ICommandExecuter tempVar = clientManager.CmdExecuter;
                NCache           nCache  = (NCache)((tempVar is NCache) ? tempVar : null);

                OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                operationContext.Add(OperationContextFieldName.ClientLastViewId, clientLastViewId);

                List <Common.MapReduce.TaskEnumeratorResult> enumerators =
                    nCache.Cache.GetTaskEnumerator(new Common.MapReduce.TaskEnumeratorPointer(
                                                       clientManager.ClientID, taskId, callbackId), operationContext);

                Common.Protobuf.Response reponse = new Common.Protobuf.Response();
                reponse.requestId = requestId;
                reponse.commandID = command.commandID;
                Common.Protobuf.TaskEnumeratorResponse taskEnumResponse = new Common.Protobuf.TaskEnumeratorResponse();
                foreach (Common.MapReduce.TaskEnumeratorResult rslt in enumerators)
                {
                    taskEnumResponse.TaskEnumeratorResult.Add(Serialization.Formatters.CompactBinaryFormatter.ToByteBuffer(rslt, nCache.Cache.Name));
                }

                reponse.responseType           = Alachisoft.NCache.Common.Protobuf.Response.Type.TASK_ENUMERATOR;
                reponse.TaskEnumeratorResponse = taskEnumResponse;
                _serializedResponsePackets.Add(ResponseHelper.SerializeResponse(reponse));
            }
            catch (Exception ex)
            {
                _serializedResponsePackets.Add(ResponseHelper.SerializeExceptionResponse(ex, command.requestID, command.commandID));
            }
        }
示例#27
0
        private void UpdateEPCacheEntry(Object key, EPCacheEntry epCacheEntry, BitSet writeOptionFlag, String writethruProvider)
        {
            CacheEntry       entry            = epCacheEntry.CacheEntry;
            OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);

            operationContext.Add(OperationContextFieldName.RaiseCQNotification, true);
            object value;

            if (entry.Value is CallbackEntry)
            {
                value = ((CallbackEntry)entry.Value).Value;
            }
            else
            {
                value = entry.Value;
            }
            object obj = _context.CachingSubSystemDataService.GetClientData(value, ref writeOptionFlag, Common.Util.LanguageContext.DOTNET);

            _cacheRoot.Insert(key, obj, entry.ExpirationHint, entry.SyncDependency, entry.EvictionHint, entry.GroupInfo != null ? entry.GroupInfo.Group : null, entry.GroupInfo != null ? entry.GroupInfo.SubGroup : null, entry.QueryInfo, writeOptionFlag, entry.LockId != null ? entry.LockId : null, entry.Version, entry.LockAccessType, writethruProvider, entry.ResyncProviderName != null ? entry.ResyncProviderName : null, operationContext);
        }
示例#28
0
        public override void ExecuteCommand(ClientManager clientManager, Alachisoft.NCache.Common.Protobuf.Command command)
        {
            CommandInfo cmdInfo;

            try
            {
                cmdInfo = ParseCommand(command, clientManager);
            }
            catch (Exception exc)
            {
                _removeBulkResult = OperationResult.Failure;
                if (!base.immatureId.Equals("-2"))
                {
                    //PROTOBUF:RESPONSE
                    _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID));
                }
                return;
            }

            //TODO
            byte[] data = null;

            try
            {
                NCache           nCache           = clientManager.CmdExecuter as NCache;
                CallbackEntry    cbEnrty          = null;
                OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                operationContext.Add(OperationContextFieldName.ClientLastViewId, cmdInfo.ClientLastViewId);

                Hashtable removeResult = (Hashtable)nCache.Cache.Remove(cmdInfo.Keys, cmdInfo.FlagMap, cbEnrty, operationContext);
                BulkRemoveResponseBuilder.BuildResponse(removeResult, cmdInfo.CommandVersion, cmdInfo.RequestId, _serializedResponsePackets);
            }
            catch (Exception exc)
            {
                _removeBulkResult = OperationResult.Failure;
                //PROTOBUF:RESPONSE
                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID));
                //_resultPacket = clientManager.ReplyPacket(base.ExceptionPacket(exc, cmdInfo.RequestId), base.ExceptionMessage(exc));
            }
        }
示例#29
0
        public override void ExecuteCommand(ClientManager clientManager, Common.Protobuf.Command command)
        {
            CommandInfo cmdInfo;

            try
            {
                cmdInfo = ParseCommand(command, clientManager);
            }
            catch (Exception exc)
            {
                if (!base.immatureId.Equals("-2"))
                {
                    //PROTOBUF:RESPONSE
                    _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID, command.commandID));
                }
                return;
            }

            try
            {
                NCache           nCache  = clientManager.CmdExecuter as NCache;
                OperationContext context = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                context.Add(OperationContextFieldName.ClientId, clientManager.ClientID);

                nCache.Cache.RegisterPollingNotification(cmdInfo.PollingCallbackId, context);

                Alachisoft.NCache.Common.Protobuf.Response response = new Alachisoft.NCache.Common.Protobuf.Response();
                Alachisoft.NCache.Common.Protobuf.RegisterPollNotifResponse registerKeyNotifResponse = new Alachisoft.NCache.Common.Protobuf.RegisterPollNotifResponse();
                response.responseType = Alachisoft.NCache.Common.Protobuf.Response.Type.REGISTER_POLL_NOTIF;
                response.registerPollNotifResponse = registerKeyNotifResponse;
                response.requestId = command.registerPollNotifCommand.requestId;
                response.commandID = command.commandID;
                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response));
            }
            catch (Exception exc)
            {
                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID, command.commandID));
            }
        }
示例#30
0
            /// <summary>
            /// Does the lazy loading of object. This method is virtual so containers can
            /// customize object fetching logic.
            /// </summary>
            /// <param name="key"></param>
            /// <returns></returns>
            protected override object FetchObject(object key, OperationContext operationContext)
            {
                ReplicatedCacheBase cache = _cache as ReplicatedCacheBase;

                object obj     = null;
                bool   doAgain = false;


                do
                {
                    doAgain = false;
                    Address targetNode = cache.Cluster.Coordinator;
                    if (targetNode == null)
                    {
                        return(null);
                    }

                    if (cache.Cluster.IsCoordinator)
                    {
                        //coordinator has left and i am the new coordinator so need not to do
                        //state transfer.
                        _bvalid = false;
                        return(obj);
                    }
                    try
                    {
                        operationContext.Add(OperationContextFieldName.GenerateQueryInfo, true);
                        obj = cache.Clustered_Get(targetNode, key, operationContext, _isUserOperation);
                    }
                    catch (Runtime.Exceptions.SuspectedException se)
                    {
                        //coordinator has left; so need to synchronize with the new coordinator.
                        doAgain = true;
                    }
                }while (doAgain);

                return(obj);
            }
示例#31
0
        /// <summary>
        /// Adds key and value pairs to the cache. If any of the specified keys 
        /// already exists in the cache; it is updated, otherwise a new item is 
        /// added to the cache.
        /// </summary>
        /// <param name="keys">keys of the entries.</param>
        /// <param name="cacheEntry">the cache entries.</param>
        /// <returns>returns keys that are added or updated successfully and their status.</returns>
        public sealed override Hashtable Insert(object[] keys, CacheEntry[] cacheEntries, bool notify, OperationContext operationContext)
        {
            Hashtable table = new Hashtable();
            EventContext eventContext = null;
            EventId eventId = null;
            OperationID opId = operationContext.OperatoinID;
            for (int i = 0; i < keys.Length; i++)
            {
                try
                {
                    operationContext.RemoveValueByField(OperationContextFieldName.EventContext);
                    if (notify)
                    {
                        //generate EventId
                        eventId = new EventId();
                        eventId.EventUniqueID = opId.OperationId;
                        eventId.OperationCounter = opId.OpCounter;
                        eventId.EventCounter = i;
                        eventContext = new EventContext();
                        eventContext.Add(EventContextFieldName.EventID, eventId);
                        operationContext.Add(OperationContextFieldName.EventContext, eventContext);
                    }
                    CacheInsResultWithEntry result = Insert(keys[i], cacheEntries[i], notify, null, LockAccessType.IGNORE_LOCK, operationContext);
                    table.Add(keys[i], result);
                }
                catch (Exception e)
                {
                    table[keys[i]] = e;
                }
                finally
                {
                    operationContext.RemoveValueByField(OperationContextFieldName.EventContext);
                }
            }

            if (_context.PerfStatsColl != null)
            {
                _context.PerfStatsColl.SetCacheSize(Size);
            }

            return table;
        }
示例#32
0
        /// <summary>
        /// Adds key and value pairs to the cache. Throws an exception or returns the
        /// list of keys that failed to add in the cache.
        /// </summary>
        /// <param name="keys">keys of the entries.</param>
        /// <param name="cacheEntries">the cache entries.</param>
        /// <returns>List of keys that are added or that alredy exists in the cache and their status.</returns>
        public sealed override Hashtable Add(object[] keys, CacheEntry[] cacheEntries, bool notify, OperationContext operationContext)
        {

            Hashtable table = new Hashtable();
            EventContext eventContext = null;
            EventId eventId = null;
            OperationID opId = operationContext.OperatoinID;
            for (int i = 0; i < keys.Length; i++)
            {
                try
                {

                    operationContext.RemoveValueByField(OperationContextFieldName.EventContext);
                    if (notify)
                    {
                        //generate EventId
                        eventId = new EventId();
                        eventId.EventUniqueID = opId.OperationId;
                        eventId.OperationCounter = opId.OpCounter;
                        eventId.EventCounter = i;
                        eventContext = new EventContext();
                        eventContext.Add(EventContextFieldName.EventID, eventId);
                        operationContext.Add(OperationContextFieldName.EventContext, eventContext);
                    }
                    CacheAddResult result = Add(keys[i], cacheEntries[i], notify, operationContext);
                    table[keys[i]] = result;
                }
                catch (Exceptions.StateTransferException se)
                {
                    table[keys[i]] = se;
                }
                catch (Exception inner)
                {
                    table[keys[i]] = new OperationFailedException(inner.Message, inner);
                }
                finally 
                {
                    operationContext.RemoveValueByField(OperationContextFieldName.EventContext);
                }
            }

            if (_context.PerfStatsColl != null)
            {
                _context.PerfStatsColl.SetCacheSize(Size);
            }
            return table;
        }
示例#33
0
        /// <summary>
        /// Retrieve the objects from the cache.
        /// An array of keys is passed as parameter.
        /// </summary>
        /// <param name="keys">keys of the entries.</param>
        /// <returns>key and entry pairs.</returns>
        public sealed override Hashtable Get(object[] keys, OperationContext operationContext)
        {
            Hashtable entries = new Hashtable();
            CacheEntry e = null;
            for (int i = 0; i < keys.Length; i++)
            {
                try
                {
                    
                    if(operationContext != null)
                    {
                        operationContext.RemoveValueByField(OperationContextFieldName.EventContext);
                        OperationID opId = operationContext.OperatoinID;
                        //generate EventId
                        EventId eventId = EventId.CreateEventId(opId);
                        eventId.EventUniqueID = opId.OperationId;
                        eventId.OperationCounter = opId.OpCounter;
                        eventId.EventCounter = i;
                        EventContext eventContext = new EventContext();
                        eventContext.Add(EventContextFieldName.EventID, eventId);
                        operationContext.Add(OperationContextFieldName.EventContext, eventContext);
                    }

                    e = Get(keys[i], operationContext);
                    if (e != null)
                    {
                        entries[keys[i]] = e;
                    }
                }
                catch (StateTransferException se)
                {
                    entries[keys[i]] = se;
                }
            }
            return entries;
        }
         protected StateTxfrInfo GetData(ArrayList bucketIds)
		 {
			 try
			 {
				 object[] keys = null;
				 Hashtable data = null;
				 Hashtable result = new Hashtable();
                 ArrayList payLoad = new ArrayList();
                 ArrayList payLoadCompilationInfo = new ArrayList();

				 if (!_sendLogData)
				 {
					 IEnumerator ie = bucketIds.GetEnumerator();
					 while (ie.MoveNext())
					 {
						 int bucketId = (int)ie.Current;
                         if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(1)", "transfering data for bucket : " + bucketId);
                         bool enableLogs = _transferType == StateTransferType.MOVE_DATA ? true : false;
                         ArrayList keyList = _parent.InternalCache.GetKeyList(bucketId, enableLogs);
						 _logableBuckets.Add(bucketId);

						 data = null;
						 if (keyList != null)
						 {
                             if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(1)", "bucket : " + bucketId + " [" + keyList.Count + " ]");

							 keys = keyList.ToArray();

                             OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                             operationContext.Add(OperationContextFieldName.GenerateQueryInfo, true);
							 data = _parent.InternalCache.Get(keys,operationContext);
						 }
                        
						 if (data != null && data.Count > 0)
						 {
							 if (result.Count == 0)
							 {
								 result = data.Clone() as Hashtable;
							 }
							 else
							 {
								 IDictionaryEnumerator ide = data.GetEnumerator();
								 while (ide.MoveNext())
								 {
                                     CacheEntry entry = ide.Value as CacheEntry;
                                     UserBinaryObject ubObject = null;
                                     if (entry.Value is CallbackEntry)
                                     {
                                         ubObject = ((CallbackEntry)entry.Value).Value as UserBinaryObject;
                                     }
                                     else
                                         ubObject = entry.Value as UserBinaryObject;

                                     payLoad.AddRange(ubObject.Data);
                                     long size = entry.DataSize;
                                     int index = payLoadCompilationInfo.Add(size);
                                     PayloadInfo payLoadInfo = new PayloadInfo(entry.CloneWithoutValue(), index);
                                     result[ide.Key] = payLoadInfo;
								 }

							 }
						 }
					 }
					 _sendLogData = true;
                     if (_parent.Context.NCacheLog.IsInfoEnabled)
                         _parent.Context.NCacheLog.Info("State Transfer Corresponder", "BalanceDataLoad = " + _isBalanceDataLoad.ToString());
                     if (_isBalanceDataLoad)
                     {
                         _parent.Context.PerfStatsColl.IncrementDataBalPerSecStatsBy(result.Count);
                     }
                     else
                     {
                         _parent.Context.PerfStatsColl.IncrementStateTxfrPerSecStatsBy(result.Count);
                     }

					 return new StateTxfrInfo(result,payLoad,payLoadCompilationInfo, false);
				 }
				 else
					 return GetLoggedData(bucketIds);
			 }
			 catch (Exception ex)
			 {
                 _parent.Context.NCacheLog.Error("StateTxfrCorresponder.GetData(1)", ex.ToString());
				 return null;
			 }
		 }
		 protected StateTxfrInfo GetData(int bucketId)
		 {
			 Hashtable result = new Hashtable();
             ArrayList payLoad = new ArrayList();
             ArrayList payLoadCompilationInfo = new ArrayList();

			 long sizeToSend = 0;

             lock (_parent._bucketStateTxfrStatus.SyncRoot)
             {
                 _parent._bucketStateTxfrStatus[bucketId] = true;
             }

             if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "state txfr request for :" + bucketId + " txfrid :" + _lastTxfrId);

			 if (_keyList != null && _keyList.Count > 0)
			 {
                 if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "bucket size :" + _keyList.Count);

				 for (_keyCount = 0; _keyCount < _keyList.Count; _keyCount++)
				 {
					 string key = _keyList[_keyCount] as string;

                     OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                      operationContext.Add(OperationContextFieldName.GenerateQueryInfo, true);
                     CacheEntry entry = _parent.InternalCache.InternalCache.Get(key, false,operationContext);
					 if (entry != null)
					 {
                         long size = (entry.InMemorySize + Common.MemoryUtil.GetStringSize(key));//.DataSize;                         
                         if (sizeToSend > _threshold) break;

                         UserBinaryObject ubObject = null;
                         if (entry.Value is CallbackEntry)
                         {
                             ubObject = ((CallbackEntry)entry.Value).Value as UserBinaryObject;
                         }
                         else
                             ubObject = entry.Value as UserBinaryObject;

                         payLoad.AddRange(ubObject.Data);
                         long entrySize = entry.DataSize;
                         int index = payLoadCompilationInfo.Add(entrySize);
                         PayloadInfo payLoadInfo = new PayloadInfo(entry.CloneWithoutValue(), index);

                         result[key] = payLoadInfo;
						 sizeToSend += size;
					 }
				 }
                 if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "items sent :" + _keyCount);
                 
                 if (_parent.Context.NCacheLog.IsInfoEnabled)
                     _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "BalanceDataLoad = " + _isBalanceDataLoad.ToString()); 

                 if (_isBalanceDataLoad)
                     _parent.Context.PerfStatsColl.IncrementDataBalPerSecStatsBy(result.Count);
                 else
                     _parent.Context.PerfStatsColl.IncrementStateTxfrPerSecStatsBy(result.Count);

				 return new StateTxfrInfo(result,payLoad,payLoadCompilationInfo, false,sizeToSend);
			 }
             else if (_transferType == StateTransferType.MOVE_DATA)
             {
                 //We need to transfer the logs.
                 if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "sending log data for bucket: " + bucketId);

                 ArrayList list = new ArrayList(1);
                 list.Add(bucketId);
                 return GetLoggedData(list);
             }
             else
             {
                 //As transfer mode is not MOVE_DATA, therefore no logs are maintained
                 //and hence are not transferred.
                 return new StateTxfrInfo(null,null,null, true);
             }
		 }
示例#36
0
            /// <summary>
            /// Does the lazy loading of object. This method is virtual so containers can 
            /// customize object fetching logic.
            /// </summary>
            /// <param name="key"></param>
            /// <returns></returns>
            protected override object FetchObject(object key, OperationContext operationContext)
            {
                ReplicatedCacheBase cache = _cache as ReplicatedCacheBase;

                object obj = null;
                bool doAgain = false;


                do
                {
                    doAgain = false;
                    Address targetNode = cache.Cluster.Coordinator;
                    if (targetNode == null) return null;

                    if (cache.Cluster.IsCoordinator)
                    {
                        //coordinator has left and i am the new coordinator so need not to do
                        //state transfer.
                        _bvalid = false;
                        return obj;
                    }
                    try
                    {
                        operationContext.Add(OperationContextFieldName.GenerateQueryInfo , true);
                        obj = cache.Clustered_Get(targetNode, key, operationContext,_isUserOperation);

                    }
                    catch (Runtime.Exceptions.SuspectedException se)
                    {
                        //coordinator has left; so need to synchronize with the new coordinator.
                        doAgain = true;
                    }
                }
                while (doAgain);

                return obj;
            }
		 protected virtual StateTxfrInfo GetLoggedData(ArrayList bucketIds)
		 {
			 ArrayList updatedKeys = null;
			 ArrayList removedKeys = null;
			 Hashtable logTbl = null;
			 StateTxfrInfo info = null;
			 Hashtable result = new Hashtable();
             ArrayList payLoad = new ArrayList();
             ArrayList payLoadCompilationInfo = new ArrayList();


			 bool isLoggingStopped = false;

			 try
			 {

				 logTbl = _parent.InternalCache.GetLogTable(bucketIds, ref isLoggingStopped);

				 if (logTbl != null)
				 {

					 updatedKeys = logTbl["updated"] as ArrayList;
					 removedKeys = logTbl["removed"] as ArrayList;

					 if (updatedKeys != null && updatedKeys.Count > 0)
					 {
						 for (int i = 0; i < updatedKeys.Count; i++)
						 {
							 string key = updatedKeys[i] as string;
                             OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                             operationContext.Add(OperationContextFieldName.GenerateQueryInfo, true);
                             CacheEntry entry = _parent.InternalCache.Get(key, false, operationContext);
                             UserBinaryObject ubObject = null;
                             if (entry.Value is CallbackEntry)
                             {
                                 ubObject = ((CallbackEntry)entry.Value).Value as UserBinaryObject;
                             }
                             else
                                 ubObject = entry.Value as UserBinaryObject;

                             payLoad.AddRange(ubObject.Data);
                             long size = entry.DataSize;
                             int index = payLoadCompilationInfo.Add(size);
                             PayloadInfo payLoadInfo = new PayloadInfo(entry.CloneWithoutValue(), index);

							 result[key] = payLoadInfo;
						 }
					 }
					 if (removedKeys != null && removedKeys.Count > 0)
					 {
						 for (int i = 0; i < removedKeys.Count; i++)
						 {
							 string key = removedKeys[i] as string;
							 result[key] = null;
						 }
					 }

					 if (!isLoggingStopped)
						 info = new StateTxfrInfo(result,payLoad,payLoadCompilationInfo, false);
					 else
                         info = new StateTxfrInfo(result, payLoad, payLoadCompilationInfo, true);


                     _parent.Context.NCacheLog.Debug("StateTxfrCorresponder.GetLoggedData()", info == null ? "returning null state-txfr-info" : "returning " + info.data.Count.ToString() + " items in state-txfr-info");
					 return info;
				 }
				 else
                     if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresoponder.GetLoggedData", "no logged data found");
			 }
			 catch (Exception e)
			 {
                 _parent.Context.NCacheLog.Error("StateTxfrCorresoponder.GetLoggedData", e.ToString());
				 throw;
			 }
			 finally
			 {
                
			 }
		
			 //no operation has been logged during state transfer.
			 //so announce completion of state transfer for this bucket.
             return new StateTxfrInfo(result, payLoad, payLoadCompilationInfo, true);
		 }
示例#38
0
		 protected virtual StateTxfrInfo GetLoggedData(ArrayList bucketIds)
		 {
			 ArrayList updatedKeys = null;
			 ArrayList removedKeys = null;
			 Hashtable logTbl = null;
			 StateTxfrInfo info = null;

			 bool isLoggingStopped = false;

			 try
			 {

				 logTbl = _parent.InternalCache.GetLogTable(bucketIds, ref isLoggingStopped);

				 if (logTbl != null)
				 {

					 updatedKeys = logTbl["updated"] as ArrayList;
					 removedKeys = logTbl["removed"] as ArrayList;

					 if (updatedKeys != null && updatedKeys.Count > 0)
					 {
						 for (int i = 0; i < updatedKeys.Count; i++)
						 {
							 string key = updatedKeys[i] as string;
                             OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                             operationContext.Add(OperationContextFieldName.GenerateQueryInfo, true);
                             CacheEntry entry = _parent.InternalCache.Get(key, false, operationContext);
                             _result[key] = entry;
						 }
					 }
					 if (removedKeys != null && removedKeys.Count > 0)
					 {
						 for (int i = 0; i < removedKeys.Count; i++)
						 {
							 string key = removedKeys[i] as string;
							 _result[key] = null;
						 }
					 }

                     if (!isLoggingStopped)
                         info = new StateTxfrInfo(_result, false, 0, this.stream);
                     else
                         info = new StateTxfrInfo(_result, true, 0, this.stream);


                     _parent.Context.NCacheLog.Debug("StateTxfrCorresponder.GetLoggedData()", info == null ? "returning null state-txfr-info" : "returning " + info.data.Count.ToString() + " items in state-txfr-info");
					 return info;
				 }
				 else
                     if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresoponder.GetLoggedData", "no logged data found");
			 }
			 catch (Exception e)
			 {
                 _parent.Context.NCacheLog.Error("StateTxfrCorresoponder.GetLoggedData", e.ToString());
				 throw;
			 }
			 finally
			 {
                
			 }
		
			 //no operation has been logged during state transfer.
			 //so announce completion of state transfer for this bucket.
             return new StateTxfrInfo(_result, true, 0, this.stream);
		 }
        void IEvictionPolicy.Execute(CacheBase cache, CacheRuntimeContext context, long evictSize)
        {
          
            ILogger NCacheLog = cache.Context.NCacheLog;
            
            if (NCacheLog.IsInfoEnabled) NCacheLog.Info("LocalCache.Evict()", "Cache Size: {0}" + cache.Count.ToString());

             //if user has updated the values in configuration file then new values will be reloaded.
            _sleepInterval = Convert.ToInt32(ServiceConfiguration.EvictionBulkRemoveDelay);
            _removeThreshhold = Convert.ToInt32(ServiceConfiguration.EvictionBulkRemoveSize);
            DateTime startTime = DateTime.Now;
            ArrayList selectedKeys = this.GetSelectedKeys(cache, (long)Math.Ceiling(evictSize * _ratio));
            DateTime endTime = DateTime.Now;

            if (NCacheLog.IsInfoEnabled) NCacheLog.Info("LocalCache.Evict()", String.Format("Time Span for {0} Items: " + (endTime - startTime), selectedKeys.Count));

            startTime = DateTime.Now;

            Cache rootCache = context.CacheRoot;

            ArrayList keysTobeRemoved = new ArrayList();
            ArrayList dependentItems = new ArrayList();
            ArrayList removedItems = null;

            IEnumerator e = selectedKeys.GetEnumerator();

            int removedThreshhold = _removeThreshhold/300;
            int remIteration = 0;
            while (e.MoveNext())
            {
                object key = e.Current;
                if (key == null) continue;

                keysTobeRemoved.Add(key);

                if (keysTobeRemoved.Count % 300 == 0)
                {
                    try
                    {
                        OperationContext priorityEvictionOperationContext = new OperationContext();
                        priorityEvictionOperationContext.Add(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                        removedItems = cache.RemoveSync(keysTobeRemoved.ToArray(), ItemRemoveReason.Underused, false, priorityEvictionOperationContext) as ArrayList;

                        context.PerfStatsColl.IncrementEvictPerSecStatsBy(keysTobeRemoved.Count);
                    }
                    catch (Exception ex)
                    {
                        NCacheLog.Error("PriorityEvictionPolicy.Execute", "an error occured while removing items. Error " + ex.ToString());
                    }
                    keysTobeRemoved.Clear();
                    if (removedItems != null && removedItems.Count > 0)
                    {
                        dependentItems.AddRange(removedItems);
                    }
                    
                    remIteration++;
                    if (remIteration >= removedThreshhold)
                    {
                        //put some delay so that user operations are not affected.
                        System.Threading.Thread.Sleep(_sleepInterval*1000);
                        remIteration = 0;
                    }
                }
            }

            if (keysTobeRemoved.Count > 0)
            {
                try
                {
                    OperationContext priorityEvictionOperationContext = new OperationContext();
                    priorityEvictionOperationContext.Add(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                    removedItems = cache.RemoveSync(keysTobeRemoved.ToArray(), ItemRemoveReason.Underused, false, priorityEvictionOperationContext) as ArrayList;

                    context.PerfStatsColl.IncrementEvictPerSecStatsBy(keysTobeRemoved.Count);
                    if (removedItems != null && removedItems.Count > 0)
                    {
                        dependentItems.AddRange(removedItems);
                    }
                }
                catch (Exception ex)
                {
                    NCacheLog.Error("PriorityEvictionPolicy.Execute", "an error occured while removing items. Error " + ex.ToString());
                }
            }

            if (dependentItems.Count > 0)
            {
                ArrayList removableList = new ArrayList();
                if (rootCache != null)
                {
                    foreach (object depenentItme in dependentItems)
                    {
                        if (depenentItme == null) continue;
                        removableList.Add(depenentItme);
                        if (removableList.Count % 100 == 0)
                        {
                            try
                            {
                                OperationContext priorityEvictionOperationContext = new OperationContext();
                                priorityEvictionOperationContext.Add(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                                rootCache.CascadedRemove(removableList.ToArray(), ItemRemoveReason.Underused, true, priorityEvictionOperationContext);

                                context.PerfStatsColl.IncrementEvictPerSecStatsBy(removableList.Count);
                            }
                            catch (Exception exc)
                            {
                                NCacheLog.Error("PriorityEvictionPolicy.Execute", "an error occured while removing dependent items. Error " + exc.ToString());

                            }
                            removableList.Clear();
                        }

                    }
                    if (removableList.Count > 0)
                    {
                        try
                        {
                            OperationContext priorityEvictionOperationContext = new OperationContext();
                            priorityEvictionOperationContext.Add(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                            rootCache.CascadedRemove(removableList.ToArray(), ItemRemoveReason.Underused, true, priorityEvictionOperationContext);

                            context.PerfStatsColl.IncrementEvictPerSecStatsBy(removableList.Count);
                        }
                        catch (Exception exc)
                        {
                            NCacheLog.Error("PriorityEvictionPolicy.Execute", "an error occured while removing dependent items. Error " + exc.ToString());

                        }
                        removableList.Clear();
                    }
                }
            }
            return;

        }
示例#40
0
        /// <summary>
        /// Removes key and value pairs from the cache. The keys are specified as parameter.
        /// Moreover it take a removal reason and a boolean specifying if a notification should
        /// be raised.
        /// </summary>
        /// <param name="keys">keys of the entry.</param>
        /// <param name="removalReason">reason for the removal.</param>
        /// <param name="notify">boolean specifying to raise the event.</param>
        /// <returns>list of removed keys</returns>
        public override Hashtable Remove(object[] keys, ItemRemoveReason removalReason, bool notify, bool isUserOperation, OperationContext operationContext)
        {
            Hashtable table = new Hashtable();
            EventContext eventContext = null;
            EventId eventId = null;
            OperationID opId = operationContext.OperatoinID;
            for (int i = 0; i < keys.Length; i++)
            {
                try
                {
                    operationContext.RemoveValueByField(OperationContextFieldName.EventContext);
                    if (notify)
                    {
                        //generate EventId
                        eventId = new EventId();
                        eventId.EventUniqueID = opId.OperationId;
                        eventId.OperationCounter = opId.OpCounter;
                        eventId.EventCounter = i;
                        eventContext = new EventContext();
                        eventContext.Add(EventContextFieldName.EventID, eventId);
                        operationContext.Add(OperationContextFieldName.EventContext, eventContext);
                    }
                    CacheEntry e = Remove(keys[i], removalReason, notify, null, LockAccessType.IGNORE_LOCK, operationContext);
                    if (e != null)
                    {
                        table[keys[i]] = e;
                    }
                }              
                catch (StateTransferException e)
                {
                    table[keys[i]] = e;
                }
                finally
                {
                    operationContext.RemoveValueByField(OperationContextFieldName.EventContext);
                }
            }


            if (_context.PerfStatsColl != null)
            {
                _context.PerfStatsColl.SetCacheSize(Size);
            }

            return table;
        }
        private Hashtable ClusteredInsert(object[] keys, CacheEntry[] cacheEntries, bool notify, OperationContext operationContext)
        {
            Hashtable targetNodes = null;
            Hashtable result = new Hashtable();
            Hashtable tmpResult = null;

            ArrayList totalKeys = new ArrayList(keys);
            ArrayList totalEntries = new ArrayList(cacheEntries);
            ArrayList keysToInsert = new ArrayList(keys);

            Address targetNode = null;
            object[] currentKeys = null;
            CacheEntry[] currentValues = null;

            Dictionary<object, CacheEntry> fullEntrySet = new Dictionary<object, CacheEntry>();

            Hashtable totalAddedKeys = new Hashtable();
            Hashtable totalInsertedKeys = new Hashtable();
            Hashtable totalRemainingKeys = new Hashtable();

            if (_internalCache == null) throw new InvalidOperationException();

            do
            {
                targetNodes = GetTargetNodes(keysToInsert);

                if (targetNodes != null && targetNodes.Count == 0)
                {
                    foreach (object key in keysToInsert)
                    {
                        result[key] = new OperationFailedException("No target node available to accommodate the data.");
                    }
                    return result;
                }
                IDictionaryEnumerator ide = targetNodes.GetEnumerator();
                Hashtable keyList = null;

                //We select one node at a time for Add operation.
                while (ide.MoveNext())
                {
                    targetNode = ide.Key as Address;
                    keyList = (Hashtable) ide.Value;

                    if (targetNode != null && keyList != null)
                    {
                        currentKeys = new object[keyList.Count];
                        currentValues = new CacheEntry[keyList.Count];

                        int j = 0;
                        foreach (object key in keyList.Keys)
                        {
                            int index = totalKeys.IndexOf(key);
                            if (index != -1)
                            {
                                currentKeys[j] = totalKeys[index];
                                currentValues[j] = totalEntries[index] as CacheEntry;
                                if (!fullEntrySet.ContainsKey((string) totalKeys[index]))
                                    fullEntrySet.Add((string) totalKeys[index], (CacheEntry) totalEntries[index]);
                                j++;
                            }
                        }

                        try
                        {
                            if (targetNode.Equals(Cluster.LocalAddress))
                            {
                                tmpResult = Local_Insert(currentKeys, currentValues, Cluster.LocalAddress, notify, operationContext);
                            }
                            else
                            {
                                tmpResult = Clustered_Insert(targetNode, currentKeys, currentValues,
                                    operationContext);
                            }
                        }
                        catch (Runtime.Exceptions.SuspectedException se)
                        {
                            //we redo the operation
                            if (Context.NCacheLog.IsInfoEnabled)
                                Context.NCacheLog.Info("PartitionedServerCache.SafeAdd",
                                    targetNode + " left while addition");

                            tmpResult = new Hashtable();
                            for (int i = 0; i < currentKeys.Length; i++)
                            {
                                tmpResult[currentKeys[i]] = new GeneralFailureException(se.Message, se);
                            }
                        }
                        catch (Runtime.Exceptions.TimeoutException te)
                        {
                            if (Context.NCacheLog.IsInfoEnabled)
                                Context.NCacheLog.Info("PartitionedServerCache.SafeAdd",
                                    targetNode + " operation timed out");

                            tmpResult = new Hashtable();
                            for (int i = 0; i < currentKeys.Length; i++)
                            {
                                tmpResult[currentKeys[i]] = new GeneralFailureException(te.Message, te);
                            }
                        }
                        catch (BucketTransferredException ex)
                        {
                            tmpResult = new Hashtable();
                            for (int i = 0; i < currentKeys.Length; i++)
                            {
                                tmpResult[currentKeys[i]] = new OperationFailedException(ex.Message, ex);
                            }
                        }

                        if (tmpResult != null && tmpResult.Count > 0)
                        {
                            IDictionaryEnumerator ie = tmpResult.GetEnumerator();
                            while (ie.MoveNext())
                            {
                                if (ie.Value is StateTransferException)
                                {
                                    totalRemainingKeys[ie.Key] = null;
                                }
                                else
                                {
                                    if (ie.Value is Exception)
                                    {
                                        result[ie.Key] = ie.Value;
                                    }
                                    else if (ie.Value is CacheInsResultWithEntry)
                                    {
                                        CacheInsResultWithEntry res = ie.Value as CacheInsResultWithEntry;
                                        switch (res.Result)
                                        {
                                            case CacheInsResult.Failure:
                                                result[ie.Key] =
                                                    new OperationFailedException(
                                                        "Generic operation failure; not enough information is available.");
                                                break;
                                            case CacheInsResult.NeedsEviction:
                                                result[ie.Key] =
                                                    new OperationFailedException(
                                                        "The cache is full and not enough items could be evicted.");
                                                break;
                                            case CacheInsResult.Success:
                                                totalAddedKeys[ie.Key] = null;
                                                break;
                                            case CacheInsResult.SuccessOverwrite:
                                                totalInsertedKeys[ie.Key] = ie.Value;
                                                result[ie.Key] = ie.Value;
                                                break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                keysToInsert = new ArrayList(totalRemainingKeys.Keys);
                totalRemainingKeys.Clear();
            } while (keysToInsert.Count > 0);

            object generateQueryInfo = operationContext.GetValueByField(OperationContextFieldName.GenerateQueryInfo);
            if (generateQueryInfo == null)
            {
                operationContext.Add(OperationContextFieldName.GenerateQueryInfo, true);
            }

            if (totalInsertedKeys.Count > 0)
            {
                IDictionaryEnumerator ide = totalInsertedKeys.GetEnumerator();
                while (ide.MoveNext())
                {
                    object key = ide.Key;
                    CacheInsResultWithEntry insResult = ide.Value as CacheInsResultWithEntry;
                    if (notify)
                    {
                        CacheEntry currentEntry = fullEntrySet[(string) ide.Key];
                        object value = insResult.Entry.Value;
                        if (value is CallbackEntry)
                        {

                            RaiseCustomUpdateCalbackNotifier(ide.Key, currentEntry, insResult.Entry, operationContext);
                        }
                    }
                }

            }



            if (generateQueryInfo == null)
            {
                operationContext.RemoveValueByField(OperationContextFieldName.GenerateQueryInfo);
            }


            return result;
        }
示例#42
0
         //protected StateTxfrInfo GetData(ArrayList bucketIds)
         //{
         //    try
         //    {
         //        object[] keys = null;
         //        Hashtable data = null;
         //        Hashtable result = new Hashtable();
         //        ArrayList payLoad = new ArrayList();
         //        ArrayList payLoadCompilationInfo = new ArrayList();

         //        if (!_sendLogData)
         //        {
         //            IEnumerator ie = bucketIds.GetEnumerator();
         //            while (ie.MoveNext())
         //            {
         //                int bucketId = (int)ie.Current;
         //                if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(1)", "transfering data for bucket : " + bucketId);
         //                bool enableLogs = _transferType == StateTransferType.MOVE_DATA ? true : false;
         //                _parent.InternalCache.GetKeyList(bucketId, enableLogs, _keyList);
         //                _logableBuckets.Add(bucketId);

         //                data = null;
         //                if (keyList != null)
         //                {
         //                    if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(1)", "bucket : " + bucketId + " [" + keyList.Count + " ]");

         //                    keys = keyList.ToArray();

         //                    OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
         //                    operationContext.Add(OperationContextFieldName.GenerateQueryInfo, true);
         //                    data = _parent.InternalCache.Get(keys,operationContext);
         //                }
                        
         //                if (data != null && data.Count > 0)
         //                {
         //                    if (result.Count == 0)
         //                    {
         //                        result = data.Clone() as Hashtable;
         //                    }
         //                    else
         //                    {
         //                        IDictionaryEnumerator ide = data.GetEnumerator();
         //                        while (ide.MoveNext())
         //                        {
         //                            CacheEntry entry = ide.Value as CacheEntry;
         //                            UserBinaryObject ubObject = null;
         //                            if (entry.Value is CallbackEntry)
         //                            {
         //                                ubObject = ((CallbackEntry)entry.Value).Value as UserBinaryObject;
         //                            }
         //                            else
         //                                ubObject = entry.Value as UserBinaryObject;

         //                            payLoad.AddRange(ubObject.Data);
         //                            long size = entry.DataSize;
         //                            int index = payLoadCompilationInfo.Add(size);
         //                            PayloadInfo payLoadInfo = new PayloadInfo(entry.CloneWithoutValue(), index);
         //                            result[ide.Key] = payLoadInfo;
         //                        }

         //                    }
         //                }
         //            }
         //            _sendLogData = true;
         //            if (_parent.Context.NCacheLog.IsInfoEnabled)
         //                _parent.Context.NCacheLog.Info("State Transfer Corresponder", "BalanceDataLoad = " + _isBalanceDataLoad.ToString());
         //            if (_isBalanceDataLoad)
         //            {
         //                _parent.Context.PerfStatsColl.IncrementDataBalPerSecStatsBy(result.Count);
         //            }
         //            else
         //            {
         //                _parent.Context.PerfStatsColl.IncrementStateTxfrPerSecStatsBy(result.Count);
         //            }

         //            return new StateTxfrInfo(result,payLoad,payLoadCompilationInfo, false);
         //        }
         //        else
         //            return GetLoggedData(bucketIds);
         //    }
         //    catch (Exception ex)
         //    {
         //        _parent.Context.NCacheLog.Error("StateTxfrCorresponder.GetData(1)", ex.ToString());
         //        return null;
         //    }
         //}

		 protected StateTxfrInfo GetData(int bucketId)
		 {
             if (_result.Count > 0)
             {
                 _result.Clear();
             }

			 long sizeToSend = 0;

             lock (_parent._bucketStateTxfrStatus.SyncRoot)
             {
                 _parent._bucketStateTxfrStatus[bucketId] = true;
             }

             if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "state txfr request for :" + bucketId + " txfrid :" + _lastTxfrId);

			 if (_keyList != null && _keyList.Count > 0)
			 {
                 if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "bucket size :" + _keyList.Count);

				 for (_keyCount = 0; _keyCount < _keyList.Count; _keyCount++)
				 {
					 string key = _keyList[_keyCount] as string;

                     OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                      operationContext.Add(OperationContextFieldName.GenerateQueryInfo, true);
                     CacheEntry entry = _parent.InternalCache.InternalCache.Get(key, false,operationContext);
					 if (entry != null)
					 {
                         long size = (entry.InMemorySize + Common.MemoryUtil.GetStringSize(key));//.DataSize;                         
                         if (sizeToSend > _threshold) break;

                         _result[key] = entry;
						 sizeToSend += size;
					 }
				 }
                 if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "items sent :" + _keyCount);
                 
                 if (_parent.Context.NCacheLog.IsInfoEnabled)
                     _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "BalanceDataLoad = " + _isBalanceDataLoad.ToString()); 

                 if (_isBalanceDataLoad)
                     _parent.Context.PerfStatsColl.IncrementDataBalPerSecStatsBy(_result.Count);
                 else
                     _parent.Context.PerfStatsColl.IncrementStateTxfrPerSecStatsBy(_result.Count);

				 return new StateTxfrInfo(_result,false,sizeToSend, this.stream);
			 }
             else if (_transferType == StateTransferType.MOVE_DATA)
             {
                 //We need to transfer the logs.
                 if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "sending log data for bucket: " + bucketId);

                 ArrayList list = new ArrayList(1);
                 list.Add(bucketId);
                 return GetLoggedData(list);
             }
             else
             {
                 //As transfer mode is not MOVE_DATA, therefore no logs are maintained
                 //and hence are not transferred.
                 return new StateTxfrInfo(null, true, 0, null);
             }
		 }
示例#43
0
        private void RemoveFailedKeysOnReplica()
        {
            try
            {
                if (IsSyncReplica && failedKeysList != null && failedKeysList.Count > 0)
                {
                    OperationContext operationContext = new OperationContext(OperationContextFieldName.RemoveOnReplica, true);
                    operationContext.Add(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);

                    IEnumerator ieFailedKeys = failedKeysList.GetEnumerator();
                    while (ieFailedKeys.MoveNext())
                    {
                        string key = (string)ieFailedKeys.Current;
                        try
                        {
                            _parent.Context.CacheImpl.Remove(key, ItemRemoveReason.Removed, false, null, LockAccessType.IGNORE_LOCK, operationContext);
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
            }
            finally
            {
                failedKeysList = null;
            }
        }
示例#44
0
 /// <summary>
 /// Does the lazy loading of object. This method is virtual so containers can customize object 
 /// fetching logic.
 /// </summary>
 /// <param name="key"></param>
 /// <returns></returns>
 protected virtual object FetchObject(object key, OperationContext operationContext)
 {
     operationContext.Add(OperationContextFieldName.GenerateQueryInfo, true);
     return _cache.Get(key,operationContext);
 }