예제 #1
0
 public CachedData GetCellCache(ViewGroup parent)
 {
     if (!_cachedDataByView.ContainsKey (parent)) {
         _cachedDataByView [parent] = new CachedData ();
     }
     return _cachedDataByView [parent];
 }
 public void SetUp()
 {
     _cacheKey = new DefaultCacheKeyConverter().ConvertCacheKey<CachedData, string>("", _lookupKey);
     _contextCache = null;
     _response = null;
     _cachedItem = new CachedData();
     _previousMetrics = BlendedCacheMetricsStore.GetCachedItemMetrics<CachedData, string>(_lookupKey) ?? new Metrics();
 }
예제 #3
0
 private Release(HPMUniqueID uniqueID, HPMUniqueID uniqueTaskID)
     : base(uniqueID, uniqueTaskID)
 {
     if (cachedData.ContainsKey(uniqueTaskID.m_ID))
         cache = cachedData[uniqueTaskID.m_ID];
     else
     {
         cache = new CachedData();
         cachedData.Add(uniqueTaskID.m_ID, cache);
     }
 }
        public void SetUp()
        {
            _cachedItem = new CachedData();
            var existingCachedItem = new CachedData();

            _cacheKeyProvider = new DefaultCacheKeyConverter();
            _cacheKey = _cacheKeyProvider.ConvertCacheKey<CachedData, string>("", _lookupKey);
            _contextCache = new DictionaryContextCache(_cacheKey, existingCachedItem);
            _volatileCache = new DictionaryVolatileCache(_cacheKey, existingCachedItem);
            _longTermCache = new DictionaryLongTermCache(_cacheKey, existingCachedItem);

            _configuration = new BlendedCacheConfiguration();
        }
        public void SetUp()
        {
            _cacheKey = new DefaultCacheKeyConverter().ConvertCacheKey<CachedData, string>("", _lookupKey);
            _response = null;
            _contextCachedItem = new CachedData();
            _volatileCachedItem = new CachedData();
            _longTermCachedItem = new CachedData();

            _contextCache_Empty = new DictionaryContextCache();
            _contextCache_Full = new DictionaryContextCache(_cacheKey, _contextCachedItem);

            _volatileCache_Empty = new DictionaryVolatileCache();
            _volatileCache_Full = new DictionaryVolatileCache(_cacheKey, _volatileCachedItem);

            _longTermCache_Empty = new DictionaryLongTermCache();
            _longTermCache_Full = new DictionaryLongTermCache(_cacheKey, _longTermCachedItem);
        }
예제 #6
0
        /// <summary>
        /// RPGアツマールのサーバーストレージからすべてのデータをjsonで受け取ったときのイベントを処理します
        /// </summary>
        /// <param name="jsonData">受け取ったデータのjson文字列データ</param>
        private void OnStorageItemsReceived(string jsonData)
        {
            // Jsonデータからセーブデータへデシリアライズしてセーブデータテーブルをクリア
            var saveData = JsonUtility.FromJson <RpgAtsumaruSaveData>(jsonData);

            saveDataTable.Clear();


            // セーブデータレコードの数分ループ
            var saveDataItems = saveData.SaveDataItems;

            for (int i = 0; i < saveDataItems.Length; ++i)
            {
                // レコードの内容をそのまますべて受け取る
                var key   = saveDataItems[i].key;
                var value = saveDataItems[i].value;
                saveDataTable[key] = new CachedData(key, value);
            }


            // データの準備ができたのでシグナルを設定
            getItemsAwaitable.Set();
        }
예제 #7
0
        public int GetByteBuffer(out byte[] buffer)
        {
            if (bufferSize <= 0)
            {
                buffer = null;
                return(-1);
            }
            CachedData data;
            int        index = -1;

            for (int i = 0, count = cache.Count; i < count; i++)
            {
                data = cache[i];
                if (data.isUsing)
                {
                    continue;
                }

                index = i;
                break;
            }

            if (index < 0)
            {
                data      = new CachedData();
                data.data = new byte[bufferSize];
                index     = cache.Count;
                cache.Add(data);
                Debugger.LogError("----------------------------------------cached bytebuffer size->" + cache.Count);
            }

            data         = cache[index];
            data.isUsing = true;
            buffer       = data.data;

            return(index);
        }
예제 #8
0
        public void Save()
        {
            using (TransactionScope transaction = new TransactionScope())
            {
                StringBuilder persistScript = new StringBuilder();

                // add insert portion to script
                Dictionary <Guid, KeyValuePair <PropertyInfo, object> > inserts = AddInsertScript(persistScript);

                #region Updates

                foreach (object updateObj in Changes[ChangeType.Update])
                {
                    if (updateObj != null)
                    {
                        Type updateType = updateObj.GetType();
                        if (Tables.ContainsKey(updateType))
                        {
                            TableData tableData = Tables[updateType];

                            // Add Update script building

                            // invalidate cache data
                            if (CachedData.ContainsKey(updateType))
                            {
                                CachedData.Remove(updateType);
                            }
                        }
                    }
                }

                #endregion

                #region Deletes

                foreach (object deleteObj in Changes[ChangeType.Delete])
                {
                    if (deleteObj != null)
                    {
                        Type deleteType = deleteObj.GetType();
                        if (Tables.ContainsKey(deleteType))
                        {
                            TableData tableData = Tables[deleteType];

                            // Add Delete script building

                            // invalidate cache data
                            if (CachedData.ContainsKey(deleteType))
                            {
                                CachedData.Remove(deleteType);
                            }
                        }
                    }
                }

                #endregion

                ExecutePersist(persistScript.ToString(), inserts);

                transaction.Complete();
            }

            // clear out lists of changes
            foreach (List <object> changeList in Changes.Values)
            {
                changeList.Clear();
            }
        }
예제 #9
0
    public ErrCode SaveParamsIntoCache(CachedData cachedData)
    {
        ErrCode err = new ErrCode();
        /*DataTable cdat = tempData1.Tables["CachingData"];
        ErrCode err = new ErrCode();
        DataRow row = tempData1.Tables["CachingData"].Rows[0];
        row.BeginEdit();
            row["functionary_id"] = cachedData.FunctionaryId;
        row.EndEdit();
        row.AcceptChanges();
        err.Message = "Редактирование строки";
        err.Number = Convert.ToInt32(tempData1.Tables["CachingData"].Rows[0]["functionary_id"]);*/
        /*CachingData.DateBegin = cachedData.DateBegin;
        CachingData.DateEnd = cachedData.DateEnd;
        CachingData.SiteId = cachedData.SiteID;
        CachingData.Callsign = cachedData.Callsign;
        CachingData.IsArchive = cachedData.IsArchive;
        CachingData.FunctionaryId = cachedData.FunctionaryId;
        CachingData.LastName = cachedData.LastName;
        CachingData.FirstName = cachedData.FirstName;
        CachingData.Patronymic = cachedData.Patronymic;
        CachingData.Status = cachedData.Status;
        CachingData.AccountFailure = cachedData.AccountFailure;
        CachingData.AccountElements = cachedData.AccountElements;*/

        return err;
    }
예제 #10
0
    public void gvFlightLogs_RowDataBound(Object sender, GridViewRowEventArgs e)
    {
        if (e == null)
        {
            throw new ArgumentNullException("e");
        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            int cCols = e.Row.Cells.Count;

            for (int i = cCols - 1; i >= 1; i--)
            {
                e.Row.Cells.RemoveAt(i);
            }
            e.Row.Cells[0].ColumnSpan = cCols;
        }
        else if (e.Row.RowType == DataControlRowType.Pager)
        {
            ((Label)e.Row.FindControl("lblNumFlights")).Text = String.Format(CultureInfo.CurrentCulture, Resources.LocalizedText.NumberOfFlights, CachedData.Count());
        }
        else if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LogbookEntryDisplay le = (LogbookEntryDisplay)e.Row.DataItem;

            // Wire up the drop-menu.  We have to do this here because it is an iNamingContainer and can't access the gridviewrow
            Controls_popmenu popup = (Controls_popmenu)e.Row.FindControl("popmenu1");
            ((Controls_mfbMiniFacebook)popup.FindControl("mfbMiniFacebook")).FlightEntry = le;
            ((Controls_mfbTweetThis)popup.FindControl("mfbTweetThis")).FlightToTweet     = le;
            ((LinkButton)popup.FindControl("lnkReverse")).CommandArgument    = ((LinkButton)popup.FindControl("lnkClone")).CommandArgument = le.FlightID.ToString(CultureInfo.InvariantCulture);
            ((LinkButton)popup.FindControl("lnkSendFlight")).CommandArgument = le.FlightID.ToString(CultureInfo.InvariantCulture);
            ((HyperLink)popup.FindControl("lnkEditThisFlight")).NavigateUrl  = EditPath(le.FlightID);
            HyperLink h = (HyperLink)popup.FindControl("lnkRequestSignature");
            h.Visible     = le.CanRequestSig;
            h.NavigateUrl = String.Format(CultureInfo.InvariantCulture, "~/Member/RequestSigs.aspx?id={0}", le.FlightID);

            // fix the ID of the delete button to prevent replay attacks
            string     szDelID  = String.Format(CultureInfo.InvariantCulture, "lnkDel{0}", le.FlightID);
            LinkButton lbDelete = (LinkButton)e.Row.FindControl("lnkDelete");
            lbDelete.ID = szDelID;
            // If the host wants notifications of deletions, register full postback.
            if (ItemDeleted != null)
            {
                ScriptManager.GetCurrent(Page).RegisterPostBackControl(lbDelete);
            }
            ((AjaxControlToolkit.ConfirmButtonExtender)e.Row.FindControl("ConfirmButtonExtender1")).TargetControlID = szDelID;

            // Bind to images.
            Controls_mfbImageList mfbIl = (Controls_mfbImageList)e.Row.FindControl("mfbilFlights");
            if (!SuppressImages)
            {
                // Flight images
                mfbIl.Key = le.FlightID.ToString(CultureInfo.InvariantCulture);
                mfbIl.Refresh();

                // wire up images
                if (mfbIl.Images.ImageArray.Count > 0 || le.Videos.Count > 0)
                {
                    e.Row.FindControl("pnlImagesHover").Visible = true;
                }
                else
                {
                    e.Row.FindControl("pnlFlightImages").Visible = false;
                }

                Aircraft ac = AircraftForUser.Find(a => a.AircraftID == le.AircraftID);
                string   szInstTypeDescription = ac == null ? string.Empty : AircraftInstance.ShortNameForInstanceType(ac.InstanceType);
                ((Label)e.Row.FindControl("lblInstanceTypeDesc")).Text = szInstTypeDescription;

                // And aircraft
                // for efficiency, see if we've already done this tail number; re-use if already done
                if (!m_dictAircraftHoverIDs.ContainsKey(le.AircraftID))
                {
                    if (ac != null)
                    {
                        mfbilAircraft.DefaultImage = ac.DefaultImage;
                    }

                    mfbilAircraft.Key = le.AircraftID.ToString(CultureInfo.InvariantCulture);
                    mfbilAircraft.Refresh();

                    // cache the attributes string - there's a bit of computation involved in it.
                    string szAttributes = ((Label)e.Row.FindControl("lblModelAttributes")).Text.EscapeHTML();

                    // and the image table.
                    m_dictAircraftHoverIDs[le.AircraftID] = szInstTypeDescription + " " + szAttributes + mfbilAircraft.AsHTMLTable();
                }

                e.Row.FindControl("plcTail").Controls.Add(new LiteralControl(m_dictAircraftHoverIDs[le.AircraftID]));
            }

            // Set style for the row
            HtmlGenericControl divDate = (HtmlGenericControl)e.Row.FindControl("divDateAndRoute");
            switch (le.RowType)
            {
            case LogbookEntryDisplay.LogbookRowType.Flight:
                if (le.IsPageBreak)
                {
                    e.Row.CssClass = e.Row.CssClass + " pageBreakRow";
                }
                break;

            case LogbookEntryDisplay.LogbookRowType.RunningTotal:
                e.Row.CssClass  = "runningTotalRow";
                divDate.Visible = false;
                break;

            case LogbookEntryDisplay.LogbookRowType.Subtotal:
                e.Row.CssClass  = (le.IsPageBreak) ? "subtotalRowPageBreak" : "subtotalRow";
                divDate.Visible = false;
                break;
            }
        }
    }
        private void Execute()
        {
            var cache = TestHelpers.GetCache();

            _response = cache.Get<CachedData>(_lookupKey);

            _metrics = BlendedCacheMetricsStore.GetCachedItemMetrics<CachedData, int>(_lookupKey) ?? new Metrics();
        }
 private static T DeserializeJsonContentAs <T>(CachedData data)
 {
     return(data == null ? default(T) : DeserializeJsonContentAs <T>(data, null));
 }
예제 #13
0
 /// <summary>
 /// Helper function for retrieving the local system time zone.
 /// May throw COMException, TimeZoneNotFoundException, InvalidTimeZoneException.
 /// Assumes cachedData lock is taken.
 /// </summary>
 /// <returns>A new TimeZoneInfo instance.</returns>
 private static TimeZoneInfo GetLocalTimeZone(CachedData cachedData)
 {
     throw new NotImplementedException();
 }
예제 #14
0
        //
        // GetLocalTimeZone -
        //
        // Helper function for retrieving the local system time zone.
        //
        // returns a new TimeZoneInfo instance
        //
        // may throw COMException, TimeZoneNotFoundException, InvalidTimeZoneException
        //
        // assumes cachedData lock is taken
        //
        static unsafe private TimeZoneInfo GetLocalTimeZone(CachedData cachedData)
        {
            String id = null;

            //
            // Try using the "kernel32!GetDynamicTimeZoneInformation" API to get the "id"
            //
            Interop.mincore.TIME_DYNAMIC_ZONE_INFORMATION dynamicTimeZoneInformation =
                new Interop.mincore.TIME_DYNAMIC_ZONE_INFORMATION();

            // call kernel32!GetDynamicTimeZoneInformation...
            long result = Interop.mincore.GetDynamicTimeZoneInformation(out dynamicTimeZoneInformation);
            if (result == Interop.mincore.TIME_ZONE_ID_INVALID)
            {
                // return a dummy entry
                return CreateCustomTimeZone(c_localId, TimeSpan.Zero, c_localId, c_localId);
            }

            TIME_ZONE_INFORMATION timeZoneInformation =
                new TIME_ZONE_INFORMATION(dynamicTimeZoneInformation);

            Boolean dstDisabled = dynamicTimeZoneInformation.DynamicDaylightTimeDisabled != 0;

            // check to see if we can use the key name returned from the API call
            if (!String.IsNullOrEmpty(new String(dynamicTimeZoneInformation.TimeZoneKeyName)))
            {
                TimeZoneInfo zone;
                Exception ex;

                if (TryGetTimeZone(new String(dynamicTimeZoneInformation.TimeZoneKeyName), dstDisabled, out zone, out ex, cachedData) == TimeZoneInfoResult.Success)
                {
                    // successfully loaded the time zone from the registry
                    return zone;
                }
            }

            // the key name was not returned or it pointed to a bogus entry - search for the entry ourselves                
            id = FindIdFromTimeZoneInformation(timeZoneInformation, out dstDisabled);

            if (id != null)
            {
                TimeZoneInfo zone;
                Exception ex;
                if (TryGetTimeZone(id, dstDisabled, out zone, out ex, cachedData) == TimeZoneInfoResult.Success)
                {
                    // successfully loaded the time zone from the registry
                    return zone;
                }
            }

            // We could not find the data in the registry.  Fall back to using
            // the data from the Win32 API
            return GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled);
        }
        private void Execute(IContextCache contextCache = null, IVolatileCache volatileCache = null, ILongTermCache longTermCache = null)
        {
            var cache = TestHelpers.GetCache(_contextCache_Full);

            _response = cache.Get<CachedData>(_lookupKey);
            _metrics = BlendedCacheMetricsStore.GetCachedItemMetrics<CachedData, string>(_lookupKey) ?? new Metrics();
        }
        private void Execute(IContextCache contextCache = null, IVolatileCache volatileCache = null, ILongTermCache longTermCache = null)
        {
            var cache = TestHelpers.GetCache(contextCache, volatileCache, longTermCache, initialFlushMode: false);

            _response = cache.Get<CachedData>(_lookupKey);
        }
예제 #17
0
        public async Task <PaymentProcessingData> ExecuteAsync(UserId subscriberId, UserId creatorId, DateTime startTimeInclusive, DateTime endTimeExclusive, CommittedAccountBalance committedAccountBalance)
        {
            using (PaymentsPerformanceLogger.Instance.Log(typeof(GetPaymentProcessingData)))
            {
                subscriberId.AssertNotNull("subscriberId");
                creatorId.AssertNotNull("creatorId");
                committedAccountBalance.AssertNotNull("committedAccountBalance");

                IReadOnlyList <SubscriberChannelsSnapshot>       subscriberChannelsSnapshots;
                IReadOnlyList <SubscriberSnapshot>               subscriberSnapshots;
                IReadOnlyList <CalculatedAccountBalanceSnapshot> calculatedAccountBalances;
                IReadOnlyList <CreatorChannelsSnapshot>          creatorChannelsSnapshots;
                IReadOnlyList <CreatorFreeAccessUsersSnapshot>   creatorFreeAccessUsersSnapshots;
                IReadOnlyList <CreatorPost>   creatorPosts;
                CreatorPercentageOverrideData creatorPercentageOverride;

                bool updateCache = false;
                if (this.cachedData != null &&
                    subscriberId.Equals(this.cachedData.SubscriberId) &&
                    startTimeInclusive >= this.cachedData.StartTimeInclusive &&
                    endTimeExclusive <= this.cachedData.EndTimeExclusive)
                {
                    subscriberChannelsSnapshots = this.cachedData.SubscriberChannelsSnapshots;
                    subscriberSnapshots         = this.cachedData.SubscriberSnapshots;
                    calculatedAccountBalances   = this.cachedData.CalculatedAccountBalanceSnapshots;
                }
                else
                {
                    updateCache = true;
                    subscriberChannelsSnapshots = await this.getSubscriberChannelsSnapshots.ExecuteAsync(subscriberId, startTimeInclusive, endTimeExclusive);

                    subscriberSnapshots = await this.getSubscriberSnapshots.ExecuteAsync(subscriberId, startTimeInclusive, endTimeExclusive);

                    calculatedAccountBalances = await this.getCalculatedAccountBalances.ExecuteAsync(subscriberId, LedgerAccountType.FifthweekCredit, startTimeInclusive, endTimeExclusive);
                }

                if (this.cachedData != null &&
                    creatorId.Equals(this.cachedData.CreatorId) &&
                    startTimeInclusive >= this.cachedData.StartTimeInclusive &&
                    endTimeExclusive <= this.cachedData.EndTimeExclusive)
                {
                    creatorChannelsSnapshots        = this.cachedData.CreatorChannelsSnapshots;
                    creatorFreeAccessUsersSnapshots = this.cachedData.CreatorFreeAccessUsersSnapshots;
                    creatorPosts = this.cachedData.CreatorPosts;
                    creatorPercentageOverride = this.cachedData.CreatorPercentageOverride;
                }
                else
                {
                    updateCache = true;
                    creatorChannelsSnapshots = await this.getCreatorChannelsSnapshots.ExecuteAsync(creatorId, startTimeInclusive, endTimeExclusive);

                    creatorFreeAccessUsersSnapshots = await this.getCreatorFreeAccessUsersSnapshots.ExecuteAsync(creatorId, startTimeInclusive, endTimeExclusive);

                    creatorPosts = await this.GetCreatorPosts(creatorChannelsSnapshots, startTimeInclusive, endTimeExclusive);

                    creatorPercentageOverride = await this.getCreatorPercentageOverride.ExecuteAsync(creatorId, startTimeInclusive);
                }

                if (updateCache)
                {
                    this.cachedData = new CachedData(
                        subscriberId,
                        creatorId,
                        startTimeInclusive,
                        endTimeExclusive,
                        subscriberChannelsSnapshots,
                        subscriberSnapshots,
                        calculatedAccountBalances,
                        creatorChannelsSnapshots,
                        creatorFreeAccessUsersSnapshots,
                        creatorPosts,
                        creatorPercentageOverride);
                }

                return(new PaymentProcessingData(
                           subscriberId,
                           creatorId,
                           startTimeInclusive,
                           endTimeExclusive,
                           committedAccountBalance,
                           subscriberChannelsSnapshots,
                           subscriberSnapshots,
                           calculatedAccountBalances,
                           creatorChannelsSnapshots,
                           creatorFreeAccessUsersSnapshots,
                           creatorPosts,
                           creatorPercentageOverride));
            }
        }
예제 #18
0
    // Try #3 on negascout recursion -> (no evaluate) depth 4 = <1 sec | d 5 = 5 sec | d 6 = 20 sec 1,520,000 positions searched
    private int NegaScout(int alpha, int beta, bool currentplayer, int depth)
    {
        int    eval          = int.MinValue;
        int    originalalpha = alpha;
        string key           = HashCode();

        if (table.TryGetValue(key, out CachedData cd) && cd.depth <= depth)
        {
            tthits++;
            return(cd.score);
        }


        CachedData cd2 = new CachedData();

        if (depth == searchDepth || temp.checkwin(currentplayer) || temp.checkwin(!currentplayer))
        {
            int score = 0;
            leaves++;
            score = Evaluate(currentplayer, depth);
            return(score);
        }
        nodes++;

        bool flag = true;

        // Generate all possible moves
        List <Move> moves = temp.GenerateAllMoves(currentplayer);

        // Implementing move ordering
        SimpleMoveOrdering(moves);

        foreach (Move nextmove in moves)
        {
            if (flag)
            {
                flag = false;
                temp.MakeMove(nextmove);

                eval = -NegaScout(-beta, -alpha, !currentplayer, depth + 1);

                temp.Undomove(nextmove);
            }
            else
            {
                temp.MakeMove(nextmove);

                eval = -NegaScout(-(alpha + 1), -alpha, !currentplayer, depth + 1);

                temp.Undomove(nextmove);

                // if the current score is
                if (alpha < eval && eval < beta)
                {
                    temp.MakeMove(nextmove);

                    eval = -NegaScout(-beta, -eval, !currentplayer, depth + 1);

                    temp.Undomove(nextmove);
                }
            }
            alpha = max(eval, alpha);
            // Cutoff
            if (alpha >= beta)
            {
                break;
            }
        }
        if (alpha > originalalpha && alpha < beta)
        {
            cd2.score  = alpha;
            cd2.depth  = depth;
            table[key] = cd2;
        }
        return(alpha);
    }
        /// <summary>
        ///  every called method must proceed throught this method
        /// </summary>
        /// <param name="invocation"></param>
        public void Intercept(IInvocation invocation)
        {
            var attribute = getCustomAttribute <CacheMeAttribute>(invocation);

            //If request comes from kendoGrid methods and none filter has been set, no caching will be used
            if (attribute != null)
            {
                //argumentJson contain arguments ,they were passed by calling method
                List <string> argumentJson = new List <string>();
                foreach (var arg in invocation.Arguments)
                {
                    //cancellation token gives a different number for each request
                    if (arg is CancellationToken)
                    {
                        continue;
                    }
                    argumentJson.Add(JsonConvert.SerializeObject(arg,
                                                                 new JsonSerializerSettings {
                        NullValueHandling = NullValueHandling.Ignore, TypeNameHandling = TypeNameHandling.Auto
                    }));
                }
                //converts search parameters of user queries to string for making hashcode



                //var m = JsonConvert.DeserializeObject<object>(argumentJson);
                int hash = 0;
                foreach (var item in argumentJson)
                {
                    hash += item.GetHashCode();
                }


                var key = invocation.TargetType.FullName + "." + invocation.Method.Name + ":" + hash;
                //if result is cached,return cached value
                var cachedResult = cacheService.Get(key);
                if (cachedResult != null)
                {
                    HttpContext.Current.Items["ResultIsCached"] = true;
                    invocation.ReturnValue = ((CachedData)cachedResult).ReturnValue;
                }
                //else execute method and save result to cache
                else
                {
                    HttpContext.Current.Items["ResultIsCached"] = false;
                    var userName = HttpContext.Current.User.Identity.GetUserName();
                    invocation.Proceed();
                    var cachedData = new CachedData {
                        ReturnValue = invocation.ReturnValue,
                        Arguments   = argumentJson.ToArray(), UserId = userName, Created = DateTime.Now,
                        MethodName  = invocation.Method.Name
                    };
                    string   controller    = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();
                    TimeSpan cacheDuration = new TimeSpan(0, attribute.DurationInMinutes, 0);
                    string   applicationId = controller + "_" + "GridPageViewModel";

                    if (HttpContext.Current.Application[applicationId] != null)
                    {
                        //var  gridPageModel = (GridPageViewModel)HttpContext.Current.Application[applicationId];
                        //  cacheDuration = gridPageModel.CacheDuration;
                    }
                    cacheService.Add(key, cachedData, cacheDuration);
                }
            }
            //if method doesnt have cacheMe attribute,just execute it without caching
            else
            {
                HttpContext.Current.Items["ResultIsCached"] = false;
                invocation.Proceed();
            }
        }
예제 #20
0
 /// <summary>
 /// Publicly visible force-refresh method.  ALWAYS bypasses the cache and uses provided data or hits the database
 /// </summary>
 public void RefreshData()
 {
     FlushCache();
     BindData(Data);
     lblNumFlights.Text = String.Format(CultureInfo.CurrentCulture, Resources.LocalizedText.NumberOfFlights, CachedData.Count());
 }
예제 #21
0
 protected override void afterWriteNodeLogic()
 {
     CachedData.setHidden(value: true, SaveToDb: true);
     // BZ 9170
     _CswNbtResources.ConfigVbls.setConfigVariableValue("cache_lastupdated", DateTime.Now.ToString());
 }
예제 #22
0
            public virtual void ReadChildData(BinaryReader reader)
            {
                int x = 0;

                for (x = 0; (x < _shaders.Count); x = (x + 1))
                {
                    Shaders.Add(new DecoratorShaderReferenceBlockBlock());
                    Shaders[x].Read(reader);
                }
                for (x = 0; (x < _shaders.Count); x = (x + 1))
                {
                    Shaders[x].ReadChildData(reader);
                }
                for (x = 0; (x < _classes.Count); x = (x + 1))
                {
                    Classes.Add(new DecoratorClassesBlockBlock());
                    Classes[x].Read(reader);
                }
                for (x = 0; (x < _classes.Count); x = (x + 1))
                {
                    Classes[x].ReadChildData(reader);
                }
                for (x = 0; (x < _models.Count); x = (x + 1))
                {
                    Models.Add(new DecoratorModelsBlockBlock());
                    Models[x].Read(reader);
                }
                for (x = 0; (x < _models.Count); x = (x + 1))
                {
                    Models[x].ReadChildData(reader);
                }
                for (x = 0; (x < _rawVertices.Count); x = (x + 1))
                {
                    RawVertices.Add(new DecoratorModelVerticesBlockBlock());
                    RawVertices[x].Read(reader);
                }
                for (x = 0; (x < _rawVertices.Count); x = (x + 1))
                {
                    RawVertices[x].ReadChildData(reader);
                }
                for (x = 0; (x < _indices.Count); x = (x + 1))
                {
                    Indices.Add(new DecoratorModelIndicesBlockBlock());
                    Indices[x].Read(reader);
                }
                for (x = 0; (x < _indices.Count); x = (x + 1))
                {
                    Indices[x].ReadChildData(reader);
                }
                for (x = 0; (x < _cachedData.Count); x = (x + 1))
                {
                    CachedData.Add(new CachedDataBlockBlock());
                    CachedData[x].Read(reader);
                }
                for (x = 0; (x < _cachedData.Count); x = (x + 1))
                {
                    CachedData[x].ReadChildData(reader);
                }
                _resourceData.ReadBinary(reader);
                for (x = 0; (x < _resources.Count); x = (x + 1))
                {
                    Resources.Add(new GlobalGeometryBlockResourceBlockBlock());
                    Resources[x].Read(reader);
                }
                for (x = 0; (x < _resources.Count); x = (x + 1))
                {
                    Resources[x].ReadChildData(reader);
                }
            }
        private void Execute()
        {
            var longTermCache = new DictionaryLongTermCache(_cacheKey, _cachedItem);
            var cache = TestHelpers.GetCache(longTermCache: longTermCache);

            _contextCache = cache.GetContextCache();
            _volatileCache = cache.GetVolatileCache();

            _response = cache.Get<CachedData, Guid>(_lookupKey);

            _metrics = BlendedCacheMetricsStore.GetCachedItemMetrics<CachedData, Guid>(_lookupKey) ?? new Metrics();
        }
예제 #24
0
        //
        // TryGetTimeZone -
        //
        // Helper function for retrieving a TimeZoneInfo object by <time_zone_name>.
        //
        // This function may return null.
        //
        // assumes cachedData lock is taken
        //
        private static TimeZoneInfoResult TryGetTimeZone(string id, Boolean dstDisabled, out TimeZoneInfo value, out Exception e, CachedData cachedData)
        {
            TimeZoneInfoResult result = TimeZoneInfoResult.Success;
            e = null;
            TimeZoneInfo match = null;

            // check the cache
            if (cachedData._systemTimeZones != null)
            {
                if (cachedData._systemTimeZones.TryGetValue(id, out match))
                {
                    if (dstDisabled && match._supportsDaylightSavingTime)
                    {
                        // we found a cache hit but we want a time zone without DST and this one has DST data
                        value = CreateCustomTimeZone(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName);
                    }
                    else
                    {
                        value = new TimeZoneInfo(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName,
                                              match._daylightDisplayName, match._adjustmentRules, false);
                    }
                    return result;
                }
            }

            // fall back to reading from the local machine 
            // when the cache is not fully populated               
            if (!cachedData._allSystemTimeZonesRead)
            {
                result = TryGetTimeZoneByRegistryKey(id, out match, out e);
                if (result == TimeZoneInfoResult.Success)
                {
                    if (cachedData._systemTimeZones == null)
                        cachedData._systemTimeZones = new LowLevelDictionaryWithIEnumerable<System.TimeZoneInfo.CachedData.OrdinalIgnoreCaseString, TimeZoneInfo>();

                    cachedData._systemTimeZones.Add(id, match);

                    if (dstDisabled && match._supportsDaylightSavingTime)
                    {
                        // we found a cache hit but we want a time zone without DST and this one has DST data
                        value = CreateCustomTimeZone(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName);
                    }
                    else
                    {
                        value = new TimeZoneInfo(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName,
                                              match._daylightDisplayName, match._adjustmentRules, false);
                    }
                }
                else
                {
                    value = null;
                }
            }
            else
            {
                result = TimeZoneInfoResult.TimeZoneNotFoundException;
                value = null;
            }

            return result;
        }
예제 #25
0
        /// <summary>
        /// Returns true if data was retrieved
        /// </summary>
        /// <param name="onRefreshed">true if updated, false if from cache</param>
        public async Task <bool> WithRefreshAsync <T>(RequestToken token, string key, bool allowStaleData, bool forceRefresh, FetchedRequestDelegate <T> onRefreshed, Action <bool> onRefreshing, Func <Task <T> > createMethod)
            where T : class
        {
            this.EnsureInitialized();

            IDataCacheFilter[] filters = this.Filters.Values.ToArray();
            // see if we can use old data
            bool canReadCached = true;

            foreach (var item in filters)
            {
                if (!item.CanReadCached(this, key))
                {
                    canReadCached = false;
                    break;
                }
            }
            T foundData = null;

            // use old data if we can
            if (allowStaleData && canReadCached && CachedData.ContainsKey(key))
            {
                foundData = CachedData[key] as T;
                if (foundData == null)
                {
                    forceRefresh = true; //had it, but it was bad data
                }
            }
            // see if we need to refresh
            if (!forceRefresh)
            {
                foreach (var item in filters)
                {
                    if (item.RefreshRequired(this, key))
                    {
                        forceRefresh = true;
                        break;
                    }
                }
            }

            if (foundData != null)
            {
                if (onRefreshed != null)
                {
                    try
                    {
                        onRefreshed(token, false, foundData); // its not fresh
                    }
                    catch (Exception ex)
                    {
                        this.LogError(ex, "onRefreshed:old");
                    }
                }
            }

            // get the data if we need to
            if (foundData == null || forceRefresh || !canReadCached || !CachedData.ContainsKey(key))
            {
                // single request at a time
                lock (_ExecutingLock)
                {
                    if (this.Executing.Contains(key))
                    {
                        return(false);
                    }
                    this.Executing.Add(key);
                }
                try
                {
                    // get the data
                    foreach (var item in filters)
                    {
                        item.OnBeforeItemRetrieved(this, key);
                    }
                    if (onRefreshing != null)
                    {
                        try
                        {
                            onRefreshing(true);
                        }
                        catch (Exception ex)
                        {
                            this.LogError(ex, "onRefreshing:true");
                        }
                    }
                    T data = null;
                    if (createMethod != null)
                    {
                        data = await createMethod();
                    }

                    foreach (var item in filters)
                    {
                        item.OnAfterItemRetrieved(this, key, data);
                    }

                    if (data != null)
                    {
                        bool canWriteToCache = true;

                        foreach (var item in filters)
                        {
                            if (!item.CanSaveToCache(this, key, data))
                            {
                                canWriteToCache = false;
                                break;
                            }
                        }

                        if (canWriteToCache)
                        {
                            foreach (var item in filters)
                            {
                                item.OnBeforeItemSavedToCache(this, key, data);
                            }

                            this.AddToCache(key, data);

                            foreach (var item in filters)
                            {
                                item.OnAfterItemSavedToCache(this, key, data);
                            }
                        }
                        if (onRefreshed != null)
                        {
                            try
                            {
                                onRefreshed(token, true, data);
                            }
                            catch (Exception ex)
                            {
                                this.LogError(ex, "onRefreshed:new");
                            }
                        }
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                finally
                {
                    lock (_ExecutingLock)
                    {
                        this.Executing.Remove(key);
                    }
                    if (onRefreshing != null)
                    {
                        try
                        {
                            onRefreshing(false);
                        }
                        catch (Exception ex)
                        {
                            this.LogError(ex, "onRefreshing:false");
                        }
                    }
                }
            }
            else
            {
                if (onRefreshing != null)
                {
                    try
                    {
                        onRefreshing(false);
                    }
                    catch (Exception ex)
                    {
                        this.LogError(ex, "onRefreshing:false");
                    }
                }
                return(false);
            }
        }
예제 #26
0
        private static unsafe void ProcessMaterial(List <BatchingChunk> chunks, MaterialInstance material, Model prefabModel, HashSet <Entity> unbatched = null)
        {
            //actually create the mesh
            List <VertexPositionNormalTextureTangent> vertsNT = null;
            List <VertexPositionNormalColor>          vertsNC = null;
            List <uint> indiciesList = new List <uint>();
            BoundingBox bb           = new BoundingBox(new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity),
                                                       new Vector3(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity));
            uint indexOffset = 0;

            for (int i = 0; i < chunks.Count; i++)
            {
                BatchingChunk chunk = chunks[i];
                if (unbatched != null && unbatched.Contains(chunk.Entity))
                {
                    continue;                                                        // don't try batching other things in this entity if some failed
                }
                if (chunk.Entity != null)
                {
                    chunk.Entity.Transform.UpdateLocalMatrix();
                    chunk.Entity.Transform.UpdateWorldMatrixInternal(true, false);
                }
                Matrix worldMatrix = chunk.Entity == null ? (chunk.Transform ?? Matrix.Identity) : chunk.Entity.Transform.WorldMatrix;
                Matrix rot;
                if (worldMatrix != Matrix.Identity)
                {
                    worldMatrix.GetRotationMatrix(out rot);
                }
                else
                {
                    rot = Matrix.Identity;
                }
                for (int j = 0; j < chunk.Model.Meshes.Count; j++)
                {
                    Mesh modelMesh = chunk.Model.Meshes[j];
                    //process only right material
                    if (modelMesh.MaterialIndex == chunk.MaterialIndex)
                    {
                        Vector3[] positions = null, normals = null;
                        Vector4[] tangents  = null;
                        Vector2[] uvs       = null;
                        Color4[]  colors    = null;

                        //vertexes
                        if (CachedModelData.TryGet(modelMesh, out var information))
                        {
                            // clone positions and normals, since they may change
                            positions = (Vector3[])information.positions.Clone();
                            normals   = (Vector3[])information.normals.Clone();
                            tangents  = information.tangents;
                            uvs       = information.uvs;
                            colors    = information.colors;
                            for (int k = 0; k < information.indicies.Length; k++)
                            {
                                indiciesList.Add(information.indicies[k] + indexOffset);
                            }
                        }
                        else if (modelMesh.Draw is StagedMeshDraw)
                        {
                            StagedMeshDraw smd = modelMesh.Draw as StagedMeshDraw;

                            object verts = smd.Verticies;

                            if (verts is VertexPositionNormalColor[])
                            {
                                VertexPositionNormalColor[] vpnc = verts as VertexPositionNormalColor[];
                                positions = new Vector3[vpnc.Length];
                                normals   = new Vector3[vpnc.Length];
                                colors    = new Color4[vpnc.Length];
                                for (int k = 0; k < vpnc.Length; k++)
                                {
                                    positions[k] = vpnc[k].Position;
                                    normals[k]   = vpnc[k].Normal;
                                    colors[k]    = vpnc[k].Color;
                                }
                            }
                            else if (verts is VertexPositionNormalTexture[])
                            {
                                VertexPositionNormalTexture[] vpnc = verts as VertexPositionNormalTexture[];
                                positions = new Vector3[vpnc.Length];
                                normals   = new Vector3[vpnc.Length];
                                uvs       = new Vector2[vpnc.Length];
                                for (int k = 0; k < vpnc.Length; k++)
                                {
                                    positions[k] = vpnc[k].Position;
                                    normals[k]   = vpnc[k].Normal;
                                    uvs[k]       = vpnc[k].TextureCoordinate;
                                }
                            }
                            else if (verts is VertexPositionNormalTextureTangent[])
                            {
                                VertexPositionNormalTextureTangent[] vpnc = verts as VertexPositionNormalTextureTangent[];
                                positions = new Vector3[vpnc.Length];
                                normals   = new Vector3[vpnc.Length];
                                uvs       = new Vector2[vpnc.Length];
                                tangents  = new Vector4[vpnc.Length];
                                for (int k = 0; k < vpnc.Length; k++)
                                {
                                    positions[k] = vpnc[k].Position;
                                    normals[k]   = vpnc[k].Normal;
                                    uvs[k]       = vpnc[k].TextureCoordinate;
                                    tangents[k]  = vpnc[k].Tangent;
                                }
                            }
                            else
                            {
                                // unsupported StagedMeshDraw
                                if (unbatched != null)
                                {
                                    unbatched.Add(chunk.Entity);
                                }
                                continue;
                            }

                            // take care of indicies
                            for (int k = 0; k < smd.Indicies.Length; k++)
                            {
                                indiciesList.Add(smd.Indicies[k] + indexOffset);
                            }

                            // cache this for later
                            CachedModelData.Add(modelMesh,
                                                new CachedData()
                            {
                                colors    = colors,
                                indicies  = smd.Indicies,
                                normals   = (Vector3[])normals.Clone(),
                                positions = (Vector3[])positions.Clone(),
                                tangents  = tangents,
                                uvs       = uvs
                            }
                                                );
                        }
                        else
                        {
                            Xenko.Graphics.Buffer buf  = modelMesh.Draw?.VertexBuffers[0].Buffer;
                            Xenko.Graphics.Buffer ibuf = modelMesh.Draw?.IndexBuffer.Buffer;
                            if (buf == null || buf.VertIndexData == null ||
                                ibuf == null || ibuf.VertIndexData == null)
                            {
                                if (unbatched != null)
                                {
                                    unbatched.Add(chunk.Entity);
                                }
                                continue;
                            }

                            if (UnpackRawVertData(buf.VertIndexData, modelMesh.Draw.VertexBuffers[0].Declaration,
                                                  out positions, out normals, out uvs, out colors, out tangents) == false)
                            {
                                if (unbatched != null)
                                {
                                    unbatched.Add(chunk.Entity);
                                }
                                continue;
                            }

                            CachedData cmd = new CachedData()
                            {
                                colors    = colors,
                                positions = (Vector3[])positions.Clone(),
                                normals   = (Vector3[])normals.Clone(),
                                uvs       = uvs,
                                tangents  = tangents
                            };

                            // indicies
                            fixed(byte *pdst = ibuf.VertIndexData)
                            {
                                int numIndices = modelMesh.Draw.IndexBuffer.Count;

                                cmd.indicies = new uint[numIndices];

                                if (modelMesh.Draw.IndexBuffer.Is32Bit)
                                {
                                    var dst = (uint *)(pdst + modelMesh.Draw.IndexBuffer.Offset);
                                    for (var k = 0; k < numIndices; k++)
                                    {
                                        // Offset indices
                                        cmd.indicies[k] = dst[k];
                                        indiciesList.Add(dst[k] + indexOffset);
                                    }
                                }
                                else
                                {
                                    var dst = (ushort *)(pdst + modelMesh.Draw.IndexBuffer.Offset);
                                    for (var k = 0; k < numIndices; k++)
                                    {
                                        // Offset indices
                                        cmd.indicies[k] = dst[k];
                                        indiciesList.Add(dst[k] + indexOffset);
                                    }
                                }
                            }

                            CachedModelData.Add(modelMesh, cmd);
                        }

                        // what kind of structure will we be making, if we haven't picked one already?
                        if (vertsNT == null && vertsNC == null)
                        {
                            if (uvs != null)
                            {
                                vertsNT = new List <VertexPositionNormalTextureTangent>(positions.Length);
                            }
                            else
                            {
                                vertsNC = new List <VertexPositionNormalColor>(positions.Length);
                            }
                        }

                        // bounding box/finish list
                        bool needmatrix = worldMatrix != Matrix.Identity;
                        for (int k = 0; k < positions.Length; k++)
                        {
                            if (needmatrix)
                            {
                                Vector3.Transform(ref positions[k], ref worldMatrix, out positions[k]);

                                if (normals != null)
                                {
                                    Vector3.TransformNormal(ref normals[k], ref rot, out normals[k]);
                                }
                            }

                            // update bounding box?
                            Vector3 pos = positions[k];
                            if (pos.X > bb.Maximum.X)
                            {
                                bb.Maximum.X = pos.X;
                            }
                            if (pos.Y > bb.Maximum.Y)
                            {
                                bb.Maximum.Y = pos.Y;
                            }
                            if (pos.Z > bb.Maximum.Z)
                            {
                                bb.Maximum.Z = pos.Z;
                            }
                            if (pos.X < bb.Minimum.X)
                            {
                                bb.Minimum.X = pos.X;
                            }
                            if (pos.Y < bb.Minimum.Y)
                            {
                                bb.Minimum.Y = pos.Y;
                            }
                            if (pos.Z < bb.Minimum.Z)
                            {
                                bb.Minimum.Z = pos.Z;
                            }

                            if (vertsNT != null)
                            {
                                vertsNT.Add(new VertexPositionNormalTextureTangent
                                {
                                    Position          = positions[k],
                                    Normal            = normals != null ? normals[k] : Vector3.UnitY,
                                    TextureCoordinate = uvs[k],
                                    Tangent           = tangents != null ? tangents[k] : Vector4.UnitW
                                });
                            }
                            else
                            {
                                vertsNC.Add(new VertexPositionNormalColor
                                {
                                    Position = positions[k],
                                    Normal   = normals != null ? normals[k] : Vector3.UnitY,
                                    Color    = colors != null ? colors[k] : Color4.White
                                });
                            }
                        }

                        indexOffset += (uint)positions.Length;
                    }
                }
            }

            if (indiciesList.Count <= 0)
            {
                return;
            }

            uint[] indicies = indiciesList.ToArray();

            // make stagedmesh with verts
            StagedMeshDraw md;

            if (vertsNT != null)
            {
                var vertsNTa = vertsNT.ToArray();
                md = StagedMeshDraw.MakeStagedMeshDraw <VertexPositionNormalTextureTangent>(ref indicies, ref vertsNTa, VertexPositionNormalTextureTangent.Layout);
            }
            else if (vertsNC != null)
            {
                var vertsNCa = vertsNC.ToArray();
                md = StagedMeshDraw.MakeStagedMeshDraw <VertexPositionNormalColor>(ref indicies, ref vertsNCa, VertexPositionNormalColor.Layout);
            }
            else
            {
                return;
            }

            Mesh m = new Mesh
            {
                Draw          = md,
                BoundingBox   = bb,
                MaterialIndex = prefabModel.Materials.Count
            };

            prefabModel.Add(m);
            if (material != null)
            {
                prefabModel.Add(material);
            }
        }
예제 #27
0
 private static void PopulateAllSystemTimeZones(CachedData cachedData)
 {
     throw new NotImplementedException();
 }
예제 #28
0
    // Try #3 on negascout recursion -> (no evaluate) depth 4 = <1 sec | d 5 = 5 sec | d 6 = 20 sec 1,520,000 positions searched
    private int NegaScoutWithDebugging(int alpha, int beta, bool currentplayer, int depth)
    {
        int    eval          = int.MinValue;
        var    sw2           = System.Diagnostics.Stopwatch.StartNew();
        int    originalalpha = alpha;
        string key           = HashCode();

        if (table.TryGetValue(key, out CachedData cd) && cd.depth <= depth)
        {
            return(cd.score);
        }


        CachedData cd2 = new CachedData();

        sw2.Stop();
        transtime += sw2.ElapsedMilliseconds;

        if (depth == searchDepth || temp.checkwin(currentplayer) || temp.checkwin(!currentplayer))
        {
            int score = 0;
            var sw3   = System.Diagnostics.Stopwatch.StartNew();
            leaves++;
            score = Evaluate(currentplayer, depth);
            sw3.Stop();
            evaltime += sw3.ElapsedMilliseconds;
            return(score);
        }
        nodes++;

        bool flag = true;

        sw2 = System.Diagnostics.Stopwatch.StartNew();

        // Generate all possible moves
        List <Move> moves = temp.GenerateAllMoves(currentplayer);

        // Implementing move ordering
        SimpleMoveOrdering(moves);
        sw2.Stop();
        time += sw2.ElapsedMilliseconds;
        foreach (Move nextmove in moves)
        {
            if (flag)
            {
                flag = false;
                var sw4 = System.Diagnostics.Stopwatch.StartNew();
                temp.MakeMove(nextmove);
                sw4.Stop();
                MoveMaking += sw4.ElapsedMilliseconds;
                functioncalls++;
                eval = -NegaScout(-beta, -alpha, !currentplayer, depth + 1);
                var sw5 = System.Diagnostics.Stopwatch.StartNew();
                temp.Undomove(nextmove);
                sw5.Stop();
                MoveUndoing += sw5.ElapsedMilliseconds;
            }
            else
            {
                var sw4 = System.Diagnostics.Stopwatch.StartNew();
                temp.MakeMove(nextmove);
                sw4.Stop();
                MoveMaking += sw4.ElapsedMilliseconds;
                functioncalls++;
                eval = -NegaScout(-(alpha + 1), -alpha, !currentplayer, depth + 1);
                var sw5 = System.Diagnostics.Stopwatch.StartNew();
                temp.Undomove(nextmove);
                sw5.Stop();
                MoveUndoing += sw5.ElapsedMilliseconds;

                // if the current score is
                if (alpha < eval && eval < beta)
                {
                    sw4 = System.Diagnostics.Stopwatch.StartNew();
                    temp.MakeMove(nextmove);
                    sw4.Stop();
                    MoveMaking += sw4.ElapsedMilliseconds;
                    functioncalls++;
                    eval = -NegaScout(-beta, -eval, !currentplayer, depth + 1);
                    sw5  = System.Diagnostics.Stopwatch.StartNew();
                    temp.Undomove(nextmove);
                    sw5.Stop();
                    MoveUndoing += sw5.ElapsedMilliseconds;
                }
            }
            alpha = max(eval, alpha);
            // Cutoff
            if (alpha >= beta)
            {
                break;
            }
        }
        if (alpha > originalalpha && alpha < beta)
        {
            sw2        = System.Diagnostics.Stopwatch.StartNew();
            cd2.score  = alpha;
            cd2.depth  = depth;
            table[key] = cd2;
            sw2.Stop();
            transtime += sw2.ElapsedMilliseconds;
        }

        return(alpha);
    }
예제 #29
0
        //
        // TryGetTimeZone -
        //
        // Helper function for retrieving a TimeZoneInfo object by <time_zone_name>.
        //
        // This function may return null.
        //
        // assumes cachedData lock is taken
        //
        private static TimeZoneInfoResult TryGetTimeZone(ref TimeZoneInformation timeZoneInformation, bool dstDisabled, out TimeZoneInfo value, out Exception e, CachedData cachedData)
        {
            TimeZoneInfoResult result = TimeZoneInfoResult.Success;

            e = null;
            TimeZoneInfo match = null;

            // check the cache
            if (cachedData._systemTimeZones != null)
            {
                if (cachedData._systemTimeZones.TryGetValue(timeZoneInformation.TimeZoneKeyName, out match))
                {
                    if (dstDisabled && match._supportsDaylightSavingTime)
                    {
                        // we found a cache hit but we want a time zone without DST and this one has DST data
                        value = CreateCustomTimeZone(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName);
                    }
                    else
                    {
                        value = new TimeZoneInfo(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName,
                                                 match._daylightDisplayName, match._adjustmentRules, false);
                    }
                    return(result);
                }
            }

            // fall back to reading from the local machine
            // when the cache is not fully populated
            result = TryGetFullTimeZoneInformation(timeZoneInformation, out match, out e, timeZoneInformation.Dtzi.Bias);

            if (result == TimeZoneInfoResult.Success)
            {
                if (cachedData._systemTimeZones == null)
                {
                    cachedData._systemTimeZones = new Dictionary <string, TimeZoneInfo>();
                }

                cachedData._systemTimeZones.Add(timeZoneInformation.TimeZoneKeyName, match);

                if (dstDisabled && match._supportsDaylightSavingTime)
                {
                    // we found a cache hit but we want a time zone without DST and this one has DST data
                    value = CreateCustomTimeZone(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName);
                }
                else
                {
                    value = new TimeZoneInfo(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName,
                                             match._daylightDisplayName, match._adjustmentRules, false);
                }
            }
            else
            {
                value = null;
            }

            return(result);
        }
        private void Execute()
        {
            var volatileCache = new DictionaryVolatileCache(_cacheKey, _cachedItem);
            var cache = TestHelpers.GetCache(volatileCache: volatileCache);

            _contextCache = cache.GetContextCache();

            _response = cache.Get<CachedData>(_lookupKey);

            _metrics = BlendedCacheMetricsStore.GetCachedItemMetrics<CachedData, string>(_lookupKey) ?? new Metrics();
        }
예제 #31
0
        //
        // GetLocalTimeZone -
        //
        // Helper function for retrieving the local system time zone.
        //
        // returns a new TimeZoneInfo instance
        //
        // may throw COMException, TimeZoneNotFoundException, InvalidTimeZoneException
        //
        // assumes cachedData lock is taken
        //

        private static TimeZoneInfo GetLocalTimeZone(CachedData cachedData)
        {
            ////
            //// Try using the "mincore!GetDynamicTimeZoneInformation" API to get the "id"
            ////
            TimeZoneInformation timeZoneInformation;
            if (!GetTimeZoneInfo(out timeZoneInformation))
            {
                return CreateCustomTimeZone(c_localId, TimeSpan.Zero, c_localId, c_localId);
            }

            Boolean dstDisabled = timeZoneInformation.Dtzi.DynamicDaylightTimeDisabled != 0;

            //// check to see if we can use the key name returned from the API call
            if (!String.IsNullOrEmpty(timeZoneInformation.TimeZoneKeyName) || FindMatchToCurrentTimeZone(timeZoneInformation))
            {
                TimeZoneInfo zone = null;
                Exception ex;

                if (TryGetTimeZone(ref timeZoneInformation, dstDisabled, out zone, out ex, cachedData) == TimeZoneInfoResult.Success)
                {
                    return zone;
                }
            }

            // Fall back to using the data from the Win32 API
            return GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled);
        }
예제 #32
0
파일: Core.cs 프로젝트: pizyumi/CREA
        public void StartSystem()
        {
            if (isSystemStarted)
                throw new InvalidOperationException("core_started");

            ahdb = new AccountHoldersDatabase(databaseBasepath);
            thdb = new TransactionHistoriesDatabase(databaseBasepath);
            bcadb = new BlockchainAccessDB(databaseBasepath);
            bmdb = new BlockManagerDB(databaseBasepath);
            bdb = new BlockDB(databaseBasepath);
            bfpdb = new BlockFilePointersDB(databaseBasepath);
            ufadb = new UtxoFileAccessDB(databaseBasepath);
            ufpdb = new UtxoFilePointersDB(databaseBasepath);
            ufptempdb = new UtxoFilePointersTempDB(databaseBasepath);
            utxodb = new UtxoDB(databaseBasepath);

            accountHolders = new AccountHolders();
            accountHoldersFactory = new AccountHoldersFactory();

            byte[] ahDataBytes = ahdb.GetData();
            if (ahDataBytes.Length != 0)
                accountHolders.FromBinary(ahDataBytes);
            else
                accountHolders.LoadVersion0();

            transactionHistories = thdb.GetData().Pipe((data) => data.Length == 0 ? new TransactionHistories() : SHAREDDATA.FromBinary<TransactionHistories>(data));
            transactionHistories.UnconfirmedTransactionAdded += (sender, e) =>
            {
                foreach (var accountHolder in accountHolders.AllAccountHolders)
                    foreach (var account in accountHolder.Accounts)
                        foreach (var prevTxOut in e.senders)
                            if (account.Address.Equals(prevTxOut.Address))
                                account.accountStatus.unconfirmedAmount = new CurrencyUnit(account.accountStatus.unconfirmedAmount.rawAmount + prevTxOut.Amount.rawAmount);
            };
            transactionHistories.UnconfirmedTransactionRemoved += (sender, e) =>
            {
                foreach (var accountHolder in accountHolders.AllAccountHolders)
                    foreach (var account in accountHolder.Accounts)
                        foreach (var prevTxOut in e.receivers)
                            if (account.Address.Equals(prevTxOut.Address))
                                account.accountStatus.unconfirmedAmount = new CurrencyUnit(account.accountStatus.unconfirmedAmount.rawAmount - prevTxOut.Amount.rawAmount);
            };

            usableBalanceCache = new CachedData<CurrencyUnit>(() =>
            {
                long rawAmount = 0;
                foreach (var accountHolder in accountHolders.AllAccountHolders)
                    foreach (var account in accountHolder.Accounts)
                        rawAmount += account.accountStatus.usableAmount.rawAmount;
                return new CurrencyUnit(rawAmount);
            });
            unusableBalanceCache = new CachedData<CurrencyUnit>(() =>
            {
                long rawAmount = 0;
                foreach (var accountHolder in accountHolders.AllAccountHolders)
                    foreach (var account in accountHolder.Accounts)
                        rawAmount += account.accountStatus.unusableAmount.rawAmount;
                return new CurrencyUnit(rawAmount);
            });
            unconfirmedBalanceCache = new CachedData<CurrencyUnit>(() =>
            {
                long rawAmount = 0;
                foreach (var accountHolder in accountHolders.AllAccountHolders)
                    foreach (var account in accountHolder.Accounts)
                        rawAmount += account.accountStatus.unconfirmedAmount.rawAmount;
                return new CurrencyUnit(rawAmount);
            });
            usableBalanceWithUnconfirmedCache = new CachedData<CurrencyUnit>(() => new CurrencyUnit(usableBalanceCache.Data.rawAmount - unconfirmedBalanceCache.Data.rawAmount));
            unusableBalanceWithUnconformedCache = new CachedData<CurrencyUnit>(() => new CurrencyUnit(unusableBalanceCache.Data.rawAmount + unconfirmedBalanceCache.Data.rawAmount));

            blockChain = new BlockChain(bcadb, bmdb, bdb, bfpdb, ufadb, ufpdb, ufptempdb, utxodb);
            blockChain.LoadTransactionHistories(transactionHistories);

            //<未改良>暫定?
            if (blockChain.headBlockIndex == -1)
            {
                blockChain.UpdateChain(new GenesisBlock());

                this.RaiseNotification("genesis_block_generated", 5);
            }

            Dictionary<Account, EventHandler<Tuple<CurrencyUnit, CurrencyUnit>>> changeAmountDict = new Dictionary<Account, EventHandler<Tuple<CurrencyUnit, CurrencyUnit>>>();

            Action<bool> _UpdateBalance = (isOnlyUnconfirmed) =>
            {
                if (!isOnlyUnconfirmed)
                {
                    usableBalanceCache.IsModified = true;
                    unusableBalanceCache.IsModified = true;
                }
                unconfirmedBalanceCache.IsModified = true;
                usableBalanceWithUnconfirmedCache.IsModified = true;
                unusableBalanceWithUnconformedCache.IsModified = true;

                BalanceUpdated(this, EventArgs.Empty);
            };

            Action<Account, bool> _AddAddressEvent = (account, isUpdatebalance) =>
            {
                EventHandler<Tuple<CurrencyUnit, CurrencyUnit>> eh = (sender, e) =>
                {
                    account.accountStatus.usableAmount = e.Item1;
                    account.accountStatus.unusableAmount = e.Item2;
                };

                changeAmountDict.Add(account, eh);

                AddressEvent addressEvent = new AddressEvent(account.Address.Hash);
                addressEvent.BalanceUpdated += eh;

                blockChain.AddAddressEvent(addressEvent);

                long rawAmount = 0;
                foreach (var unconfirmedTh in transactionHistories.unconfirmedTransactionHistories.ToArray())
                    foreach (var prevTxOut in unconfirmedTh.senders)
                        if (prevTxOut.Address.Equals(account.Address))
                            rawAmount += prevTxOut.Amount.rawAmount;
                account.accountStatus.unconfirmedAmount = new CurrencyUnit(rawAmount);

                if (isUpdatebalance)
                    _UpdateBalance(false);
            };

            EventHandler<Account> _AccountAdded = (sender, e) =>
            {
                utxodb.Open();

                _AddAddressEvent(e, true);

                utxodb.Close();
            };
            EventHandler<Account> _AccountRemoved = (sender, e) =>
            {
                EventHandler<Tuple<CurrencyUnit, CurrencyUnit>> eh = changeAmountDict[e];

                changeAmountDict.Remove(e);

                AddressEvent addressEvent = blockChain.RemoveAddressEvent(e.Address.Hash);
                addressEvent.BalanceUpdated -= eh;

                _UpdateBalance(false);
            };

            utxodb.Open();

            foreach (var accountHolder in accountHolders.AllAccountHolders)
            {
                foreach (var account in accountHolder.Accounts)
                    _AddAddressEvent(account, false);

                accountHolder.AccountAdded += _AccountAdded;
                accountHolder.AccountRemoved += _AccountRemoved;
            }

            utxodb.Close();

            accountHolders.AccountHolderAdded += (sender, e) =>
            {
                e.AccountAdded += _AccountAdded;
                e.AccountRemoved += _AccountRemoved;
            };
            accountHolders.AccountHolderRemoved += (semder, e) =>
            {
                e.AccountAdded -= _AccountAdded;
                e.AccountRemoved -= _AccountRemoved;
            };

            blockChain.BalanceUpdated += (sender, e) => _UpdateBalance(false);

            _UpdateBalance(false);

            unconfirmedTtxs = new Dictionary<TransferTransaction, TransactionOutput[]>();
            mining = new Mining();
            mining.FoundNonce += (sender, e) => creaNodeTest.DiffuseNewBlock(e);

            blockChain.Updated += (sender, e) =>
            {
                foreach (var block in e)
                    foreach (var tx in block.Transactions)
                        foreach (var txIn in tx.TxInputs)
                        {
                            TransferTransaction contradiction = null;

                            foreach (var unconfirmedTx in unconfirmedTtxs)
                            {
                                foreach (var unconfirmedTxIn in unconfirmedTx.Key.TxInputs)
                                    if (txIn.PrevTxBlockIndex == unconfirmedTxIn.PrevTxBlockIndex && txIn.PrevTxIndex == unconfirmedTxIn.PrevTxIndex && txIn.PrevTxOutputIndex == unconfirmedTxIn.PrevTxOutputIndex)
                                    {
                                        contradiction = unconfirmedTx.Key;

                                        break;
                                    }

                                if (contradiction != null)
                                    break;
                            }

                            if (contradiction != null)
                                unconfirmedTtxs.Remove(contradiction);
                        }

                Mine();
            };

            Mine();

            //creaNodeTest = new CreaNode(ps.NodePort, creaVersion, appnameWithVersion, new FirstNodeInfosDatabase(p2pDirectory));
            creaNodeTest = new CreaNodeTest(blockChain, ps.NodePort, creaVersion, appnameWithVersion);
            creaNodeTest.ConnectionKeeped += (sender, e) => creaNodeTest.SyncronizeBlockchain();
            creaNodeTest.ReceivedNewTransaction += (sender, e) =>
            {
                TransferTransaction ttx = e as TransferTransaction;

                if (ttx == null)
                    return;

                TransactionOutput[] prevTxOuts = new TransactionOutput[ttx.TxInputs.Length];
                for (int i = 0; i < prevTxOuts.Length; i++)
                    prevTxOuts[i] = blockChain.GetMainBlock(ttx.TxInputs[i].PrevTxBlockIndex).Transactions[ttx.TxInputs[i].PrevTxIndex].TxOutputs[ttx.TxInputs[i].PrevTxOutputIndex];

                if (!ttx.Verify(prevTxOuts))
                    return;

                List<TransactionOutput> senders = new List<TransactionOutput>();
                List<TransactionOutput> receivers = new List<TransactionOutput>();

                long sentAmount = 0;
                long receivedAmount = 0;

                for (int i = 0; i < ttx.txInputs.Length; i++)
                    foreach (var accountHolder in accountHolders.AllAccountHolders)
                        foreach (var account in accountHolder.Accounts)
                            if (prevTxOuts[i].Address.Equals(account.Address.Hash))
                            {
                                sentAmount += prevTxOuts[i].Amount.rawAmount;

                                senders.Add(prevTxOuts[i]);
                            }

                for (int i = 0; i < ttx.TxOutputs.Length; i++)
                    foreach (var accountHolder in accountHolders.AllAccountHolders)
                        foreach (var account in accountHolder.Accounts)
                            if (ttx.TxOutputs[i].Address.Equals(account.Address.Hash))
                            {
                                receivedAmount += ttx.TxOutputs[i].Amount.rawAmount;

                                receivers.Add(ttx.TxOutputs[i]);
                            }

                if (senders.Count > 0 || receivers.Count > 0)
                {
                    TransactionHistoryType type = TransactionHistoryType.transfered;
                    if (receivers.Count < ttx.TxOutputs.Length)
                        type = TransactionHistoryType.sent;
                    else if (senders.Count < ttx.TxInputs.Length)
                        type = TransactionHistoryType.received;

                    transactionHistories.AddTransactionHistory(new TransactionHistory(true, false, type, DateTime.MinValue, 0, ttx.Id, senders.ToArray(), receivers.ToArray(), ttx, prevTxOuts, new CurrencyUnit(sentAmount), new CurrencyUnit(receivedAmount - sentAmount)));
                }

                utxodb.Open();

                for (int i = 0; i < ttx.TxInputs.Length; i++)
                    if (blockChain.FindUtxo(prevTxOuts[i].Address, ttx.TxInputs[i].PrevTxBlockIndex, ttx.TxInputs[i].PrevTxIndex, ttx.TxInputs[i].PrevTxOutputIndex) == null)
                        return;

                utxodb.Close();

                foreach (var txIn in ttx.TxInputs)
                    foreach (var unconfirmedTtx in unconfirmedTtxs)
                        foreach (var unconfirmedTxIn in unconfirmedTtx.Key.TxInputs)
                            if (txIn.PrevTxBlockIndex == unconfirmedTxIn.PrevTxBlockIndex && txIn.PrevTxIndex == unconfirmedTxIn.PrevTxIndex && txIn.PrevTxOutputIndex == unconfirmedTxIn.PrevTxOutputIndex)
                                return;

                unconfirmedTtxs.Add(ttx, prevTxOuts);

                Mine();
            };
            creaNodeTest.ReceivedNewBlock += (sender, e) => blockChain.UpdateChain(e).Pipe((ret) => this.RaiseResult("blockchain_update", 5, ret.ToString()));
            //creaNodeTest.Start();

            isSystemStarted = true;
        }
예제 #33
0
 public PersonalSettingsProvider(MongoClient mongoClient) : base(mongoClient)
 {
     personalSettingsCache = new CachedData <List <PersonalSettings.PersonalSetting> >(() => FetchPersonalSettingsSync(), TimeSpan.FromMinutes(10));
 }
예제 #34
0
 /// <summary>
 /// The number of items currently in memory
 /// </summary>
 /// <returns></returns>
 public int TotalCachedItems()
 {
     return(CachedData.Count(cd => cd != default(S)));
 }
예제 #35
0
        private static TimeZoneInfo GetLocalTimeZone(CachedData cachedData)
        {
            Byte[] rawData = GetLocalTzFile();

            if (rawData != null)
            {
                try
                {
                    return new TimeZoneInfo(rawData, false); // create a TimeZoneInfo instance from the TZif data w/ DST support
                }
                catch (ArgumentException) { }
                catch (InvalidTimeZoneException) { }
                try
                {
                    return new TimeZoneInfo(rawData, true); // create a TimeZoneInfo instance from the TZif data w/o DST support
                }
                catch (ArgumentException) { }
                catch (InvalidTimeZoneException) { }
            }
            // the data returned from the PAL is completely bogus; return a dummy entry
            return CreateCustomTimeZone(c_localId, TimeSpan.Zero, c_localId, c_localId);
        }
예제 #36
0
 private static void PopulateAllSystemTimeZones(CachedData cachedData)
 {
     Debug.Assert(Monitor.IsEntered(cachedData));
     // UNIXTODO
     throw new NotImplementedException();
 }
예제 #37
0
        public void StartSystem()
        {
            if (isSystemStarted)
            {
                throw new InvalidOperationException("core_started");
            }

            ahdb      = new AccountHoldersDatabase(databaseBasepath);
            thdb      = new TransactionHistoriesDatabase(databaseBasepath);
            bcadb     = new BlockchainAccessDB(databaseBasepath);
            bmdb      = new BlockManagerDB(databaseBasepath);
            bdb       = new BlockDB(databaseBasepath);
            bfpdb     = new BlockFilePointersDB(databaseBasepath);
            ufadb     = new UtxoFileAccessDB(databaseBasepath);
            ufpdb     = new UtxoFilePointersDB(databaseBasepath);
            ufptempdb = new UtxoFilePointersTempDB(databaseBasepath);
            utxodb    = new UtxoDB(databaseBasepath);

            accountHolders        = new AccountHolders();
            accountHoldersFactory = new AccountHoldersFactory();

            byte[] ahDataBytes = ahdb.GetData();
            if (ahDataBytes.Length != 0)
            {
                accountHolders.FromBinary(ahDataBytes);
            }
            else
            {
                accountHolders.LoadVersion0();
            }

            transactionHistories = thdb.GetData().Pipe((data) => data.Length == 0 ? new TransactionHistories() : SHAREDDATA.FromBinary <TransactionHistories>(data));
            transactionHistories.UnconfirmedTransactionAdded += (sender, e) =>
            {
                foreach (var accountHolder in accountHolders.AllAccountHolders)
                {
                    foreach (var account in accountHolder.Accounts)
                    {
                        foreach (var prevTxOut in e.senders)
                        {
                            if (account.Address.Equals(prevTxOut.Address))
                            {
                                account.accountStatus.unconfirmedAmount = new CurrencyUnit(account.accountStatus.unconfirmedAmount.rawAmount + prevTxOut.Amount.rawAmount);
                            }
                        }
                    }
                }
            };
            transactionHistories.UnconfirmedTransactionRemoved += (sender, e) =>
            {
                foreach (var accountHolder in accountHolders.AllAccountHolders)
                {
                    foreach (var account in accountHolder.Accounts)
                    {
                        foreach (var prevTxOut in e.receivers)
                        {
                            if (account.Address.Equals(prevTxOut.Address))
                            {
                                account.accountStatus.unconfirmedAmount = new CurrencyUnit(account.accountStatus.unconfirmedAmount.rawAmount - prevTxOut.Amount.rawAmount);
                            }
                        }
                    }
                }
            };

            usableBalanceCache = new CachedData <CurrencyUnit>(() =>
            {
                long rawAmount = 0;
                foreach (var accountHolder in accountHolders.AllAccountHolders)
                {
                    foreach (var account in accountHolder.Accounts)
                    {
                        rawAmount += account.accountStatus.usableAmount.rawAmount;
                    }
                }
                return(new CurrencyUnit(rawAmount));
            });
            unusableBalanceCache = new CachedData <CurrencyUnit>(() =>
            {
                long rawAmount = 0;
                foreach (var accountHolder in accountHolders.AllAccountHolders)
                {
                    foreach (var account in accountHolder.Accounts)
                    {
                        rawAmount += account.accountStatus.unusableAmount.rawAmount;
                    }
                }
                return(new CurrencyUnit(rawAmount));
            });
            unconfirmedBalanceCache = new CachedData <CurrencyUnit>(() =>
            {
                long rawAmount = 0;
                foreach (var accountHolder in accountHolders.AllAccountHolders)
                {
                    foreach (var account in accountHolder.Accounts)
                    {
                        rawAmount += account.accountStatus.unconfirmedAmount.rawAmount;
                    }
                }
                return(new CurrencyUnit(rawAmount));
            });
            usableBalanceWithUnconfirmedCache   = new CachedData <CurrencyUnit>(() => new CurrencyUnit(usableBalanceCache.Data.rawAmount - unconfirmedBalanceCache.Data.rawAmount));
            unusableBalanceWithUnconformedCache = new CachedData <CurrencyUnit>(() => new CurrencyUnit(unusableBalanceCache.Data.rawAmount + unconfirmedBalanceCache.Data.rawAmount));

            blockChain = new BlockChain(bcadb, bmdb, bdb, bfpdb, ufadb, ufpdb, ufptempdb, utxodb);
            blockChain.LoadTransactionHistories(transactionHistories);

            //<未改良>暫定?
            if (blockChain.headBlockIndex == -1)
            {
                blockChain.UpdateChain(new GenesisBlock());

                this.RaiseNotification("genesis_block_generated", 5);
            }

            Dictionary <Account, EventHandler <Tuple <CurrencyUnit, CurrencyUnit> > > changeAmountDict = new Dictionary <Account, EventHandler <Tuple <CurrencyUnit, CurrencyUnit> > >();

            Action <bool> _UpdateBalance = (isOnlyUnconfirmed) =>
            {
                if (!isOnlyUnconfirmed)
                {
                    usableBalanceCache.IsModified   = true;
                    unusableBalanceCache.IsModified = true;
                }
                unconfirmedBalanceCache.IsModified             = true;
                usableBalanceWithUnconfirmedCache.IsModified   = true;
                unusableBalanceWithUnconformedCache.IsModified = true;

                BalanceUpdated(this, EventArgs.Empty);
            };

            Action <Account, bool> _AddAddressEvent = (account, isUpdatebalance) =>
            {
                EventHandler <Tuple <CurrencyUnit, CurrencyUnit> > eh = (sender, e) =>
                {
                    account.accountStatus.usableAmount   = e.Item1;
                    account.accountStatus.unusableAmount = e.Item2;
                };

                changeAmountDict.Add(account, eh);

                AddressEvent addressEvent = new AddressEvent(account.Address.Hash);
                addressEvent.BalanceUpdated += eh;

                blockChain.AddAddressEvent(addressEvent);

                long rawAmount = 0;
                foreach (var unconfirmedTh in transactionHistories.unconfirmedTransactionHistories.ToArray())
                {
                    foreach (var prevTxOut in unconfirmedTh.senders)
                    {
                        if (prevTxOut.Address.Equals(account.Address))
                        {
                            rawAmount += prevTxOut.Amount.rawAmount;
                        }
                    }
                }
                account.accountStatus.unconfirmedAmount = new CurrencyUnit(rawAmount);

                if (isUpdatebalance)
                {
                    _UpdateBalance(false);
                }
            };

            EventHandler <Account> _AccountAdded = (sender, e) =>
            {
                utxodb.Open();

                _AddAddressEvent(e, true);

                utxodb.Close();
            };
            EventHandler <Account> _AccountRemoved = (sender, e) =>
            {
                EventHandler <Tuple <CurrencyUnit, CurrencyUnit> > eh = changeAmountDict[e];

                changeAmountDict.Remove(e);

                AddressEvent addressEvent = blockChain.RemoveAddressEvent(e.Address.Hash);
                addressEvent.BalanceUpdated -= eh;

                _UpdateBalance(false);
            };

            utxodb.Open();

            foreach (var accountHolder in accountHolders.AllAccountHolders)
            {
                foreach (var account in accountHolder.Accounts)
                {
                    _AddAddressEvent(account, false);
                }

                accountHolder.AccountAdded   += _AccountAdded;
                accountHolder.AccountRemoved += _AccountRemoved;
            }

            utxodb.Close();

            accountHolders.AccountHolderAdded += (sender, e) =>
            {
                e.AccountAdded   += _AccountAdded;
                e.AccountRemoved += _AccountRemoved;
            };
            accountHolders.AccountHolderRemoved += (semder, e) =>
            {
                e.AccountAdded   -= _AccountAdded;
                e.AccountRemoved -= _AccountRemoved;
            };

            blockChain.BalanceUpdated += (sender, e) => _UpdateBalance(false);

            _UpdateBalance(false);

            unconfirmedTtxs    = new Dictionary <TransferTransaction, TransactionOutput[]>();
            mining             = new Mining();
            mining.FoundNonce += (sender, e) => creaNodeTest.DiffuseNewBlock(e);

            blockChain.Updated += (sender, e) =>
            {
                foreach (var block in e)
                {
                    foreach (var tx in block.Transactions)
                    {
                        foreach (var txIn in tx.TxInputs)
                        {
                            TransferTransaction contradiction = null;

                            foreach (var unconfirmedTx in unconfirmedTtxs)
                            {
                                foreach (var unconfirmedTxIn in unconfirmedTx.Key.TxInputs)
                                {
                                    if (txIn.PrevTxBlockIndex == unconfirmedTxIn.PrevTxBlockIndex && txIn.PrevTxIndex == unconfirmedTxIn.PrevTxIndex && txIn.PrevTxOutputIndex == unconfirmedTxIn.PrevTxOutputIndex)
                                    {
                                        contradiction = unconfirmedTx.Key;

                                        break;
                                    }
                                }

                                if (contradiction != null)
                                {
                                    break;
                                }
                            }

                            if (contradiction != null)
                            {
                                unconfirmedTtxs.Remove(contradiction);
                            }
                        }
                    }
                }

                Mine();
            };

            Mine();

            //creaNodeTest = new CreaNode(ps.NodePort, creaVersion, appnameWithVersion, new FirstNodeInfosDatabase(p2pDirectory));
            creaNodeTest = new CreaNodeTest(blockChain, ps.NodePort, creaVersion, appnameWithVersion);
            creaNodeTest.ConnectionKeeped       += (sender, e) => creaNodeTest.SyncronizeBlockchain();
            creaNodeTest.ReceivedNewTransaction += (sender, e) =>
            {
                TransferTransaction ttx = e as TransferTransaction;

                if (ttx == null)
                {
                    return;
                }

                TransactionOutput[] prevTxOuts = new TransactionOutput[ttx.TxInputs.Length];
                for (int i = 0; i < prevTxOuts.Length; i++)
                {
                    prevTxOuts[i] = blockChain.GetMainBlock(ttx.TxInputs[i].PrevTxBlockIndex).Transactions[ttx.TxInputs[i].PrevTxIndex].TxOutputs[ttx.TxInputs[i].PrevTxOutputIndex];
                }

                if (!ttx.Verify(prevTxOuts))
                {
                    return;
                }

                List <TransactionOutput> senders   = new List <TransactionOutput>();
                List <TransactionOutput> receivers = new List <TransactionOutput>();

                long sentAmount     = 0;
                long receivedAmount = 0;

                for (int i = 0; i < ttx.txInputs.Length; i++)
                {
                    foreach (var accountHolder in accountHolders.AllAccountHolders)
                    {
                        foreach (var account in accountHolder.Accounts)
                        {
                            if (prevTxOuts[i].Address.Equals(account.Address.Hash))
                            {
                                sentAmount += prevTxOuts[i].Amount.rawAmount;

                                senders.Add(prevTxOuts[i]);
                            }
                        }
                    }
                }

                for (int i = 0; i < ttx.TxOutputs.Length; i++)
                {
                    foreach (var accountHolder in accountHolders.AllAccountHolders)
                    {
                        foreach (var account in accountHolder.Accounts)
                        {
                            if (ttx.TxOutputs[i].Address.Equals(account.Address.Hash))
                            {
                                receivedAmount += ttx.TxOutputs[i].Amount.rawAmount;

                                receivers.Add(ttx.TxOutputs[i]);
                            }
                        }
                    }
                }

                if (senders.Count > 0 || receivers.Count > 0)
                {
                    TransactionHistoryType type = TransactionHistoryType.transfered;
                    if (receivers.Count < ttx.TxOutputs.Length)
                    {
                        type = TransactionHistoryType.sent;
                    }
                    else if (senders.Count < ttx.TxInputs.Length)
                    {
                        type = TransactionHistoryType.received;
                    }

                    transactionHistories.AddTransactionHistory(new TransactionHistory(true, false, type, DateTime.MinValue, 0, ttx.Id, senders.ToArray(), receivers.ToArray(), ttx, prevTxOuts, new CurrencyUnit(sentAmount), new CurrencyUnit(receivedAmount - sentAmount)));
                }

                utxodb.Open();

                for (int i = 0; i < ttx.TxInputs.Length; i++)
                {
                    if (blockChain.FindUtxo(prevTxOuts[i].Address, ttx.TxInputs[i].PrevTxBlockIndex, ttx.TxInputs[i].PrevTxIndex, ttx.TxInputs[i].PrevTxOutputIndex) == null)
                    {
                        return;
                    }
                }

                utxodb.Close();

                foreach (var txIn in ttx.TxInputs)
                {
                    foreach (var unconfirmedTtx in unconfirmedTtxs)
                    {
                        foreach (var unconfirmedTxIn in unconfirmedTtx.Key.TxInputs)
                        {
                            if (txIn.PrevTxBlockIndex == unconfirmedTxIn.PrevTxBlockIndex && txIn.PrevTxIndex == unconfirmedTxIn.PrevTxIndex && txIn.PrevTxOutputIndex == unconfirmedTxIn.PrevTxOutputIndex)
                            {
                                return;
                            }
                        }
                    }
                }

                unconfirmedTtxs.Add(ttx, prevTxOuts);

                Mine();
            };
            creaNodeTest.ReceivedNewBlock += (sender, e) => blockChain.UpdateChain(e).Pipe((ret) => this.RaiseResult("blockchain_update", 5, ret.ToString()));
            //creaNodeTest.Start();

            isSystemStarted = true;
        }