示例#1
0
        public static IHtmlString RenderCategoryMenu(this HtmlHelper html)
        {
            CacheService cache = new CacheService();
            int currentCategoryId = 0;

            if (html.ViewContext.RouteData.Values.ContainsKey("categoryId"))  {
                currentCategoryId = html.ViewContext.RouteData.Values["categoryId"].ToString().AsInt();
            }

            return cache.Get("categoryMenu.{0}".FormatWith(currentCategoryId), () => {
                CategoryService categoryService = new CategoryService();
                int currentTopCategoryId = categoryService.GetTopParentOf(currentCategoryId);

                var sb = new StringBuilder();
                var categories = categoryService.GetMainCategories();

                sb.AppendWithTabs("<ul>", 3);

                foreach (var category in categories) {
                    var isCurrent = currentTopCategoryId == category.CategoryId;
                    sb.AppendWithTabs("<li>", 4);
                    sb.AppendWithTabs("<a href=\"{0}\"{1}>{2} <span class=\"count\">({3})</span></a>".FormatWith(category.Link, isCurrent ? "class=\"current\"" : "", category.Name, category.Snippets.Count), 5);

                    if (currentTopCategoryId == category.CategoryId && category.ChildrenCategories != null) {
                        AppendSubCategories(sb, category, currentCategoryId, 5);
                    }

                    sb.AppendWithTabs("</li>", 4);
                }

                sb.AppendWithTabs("</ul>", 3);

                return new HtmlString(sb.ToString());
            });
        }
示例#2
0
    public void MonitorExceptionTest()
    {

      using ( var provider = new MemoryCacheProvider( "Test" ).AsAsyncProvider() )
      {
        var cacheService = new CacheService( provider );
        var monitor = new CacheServiceMonitorWithException();
        cacheService.RegisterMonitor( monitor );


        Task.Run( (Func<Task>) (async () =>
        {

          await cacheService.FetchOrAdd<string>( (string) "Test", (Func<Task<string>>) (() => (Task<string>) Task.Run( (Func<string>) (() => (string) "Test") )), (Caching.CachePolicy) Caching.CachePolicy.Expires( (TimeSpan) TimeSpan.FromHours( (double) 1 ) ) );
          await cacheService.FetchOrAdd<string>( (string) "Test", (Func<Task<string>>) (() => (Task<string>) Task.Run( (Func<string>) (() => (string) "Test") )), (Caching.CachePolicy) Caching.CachePolicy.Expires( (TimeSpan) TimeSpan.FromHours( (double) 1 ) ) );

          await Task.Delay( 100 );

          await cacheService.FetchOrAdd<string>( (string) "Test", (Func<Task<string>>) (() => (Task<string>) Task.Run( (Func<string>) (() => (string) "Test") )), (Caching.CachePolicy) Caching.CachePolicy.Expires( (TimeSpan) TimeSpan.FromHours( (double) 1 ) ) );
          await cacheService.FetchOrAdd<string>( (string) "Test", (Func<Task<string>>) (() => (Task<string>) Task.Run( (Func<string>) (() => (string) "Test") )), (Caching.CachePolicy) Caching.CachePolicy.Expires( (TimeSpan) TimeSpan.FromHours( (double) 1 ) ) );

        })
        ).Wait();


        Assert.AreEqual( monitor.Misses, 1 );
        Assert.AreEqual( monitor.Hits, 3 );

      }

    }
 public void SaveEntityInCacheTest()
 {
     ICacheService target = new CacheService();
     var value = TestEntityFactory.GetEntity();
     target["Test"] = value;
     bool result = target["Test"].Equals(value);
     Assert.IsTrue(result);
 }
 public void RemoveEntityFromCacheTest()
 {
     ICacheService target = new CacheService();
     var value = TestEntityFactory.GetEntity();
     target["TestEntity2"] = value;
     target.Delete("Test");
     var result = target["Test"];
     Assert.IsNull(result);
 }
 public void ClearCacheTest()
 {
     ICacheService target = new CacheService();
     var value = TestEntityFactory.GetEntity();
     target["TestEntity2"] = value;
     target.Clear();
     var result = target["Test"];
     Assert.IsNull(result);
 }
示例#6
0
文件: Program.cs 项目: sgauzel/main
        static void Main(string[] args)
        {
            var cache = new CacheService();
             cache.Set(new CacheKeyBuilder("demo"), "my data");
             var data = cache.Get(new CacheKeyBuilder("demo"));
             Console.ReadKey();

            var context = new DataContext();
            var test = context.Categories.ToList();
        }
        public void SaveAListOfEntitiesInCacheTest()
        {
            ICacheService target = new CacheService();
            var value = new List<TestEntity>();

            for (int i = 0; i < 3; i++)
            {
                value.Add(TestEntityFactory.GetEntity());
            }

            target["TestEntityList"] = value;
            var result = target["TestEntityList"] as List<TestEntity>;
            Assert.IsNotNull(result);
        }
示例#8
0
    public void DiskCacheTest()
    {


      Task.Run( (Func<Task>) (async () =>
      {

        using ( var provider = new DiskCacheProvider( Path.Combine( Path.GetTempPath(), "Cache" ) ) )
        {
          var service = new CacheService( (IAsyncCacheProvider) provider, (Caching.CachePolicy) Caching.CachePolicy.Expires( (TimeSpan) TimeSpan.FromHours( (double) 1 ) ) );


          Assert.AreEqual( await service.Fetch( Path.GetRandomFileName().Replace( ".", "" ), "ABC" ), "ABC" );


          for ( var i = 0; i < 1000; i++ )
          {
            var _value = await service.FetchOrAdd<object>( (string) "Test", (Func<Task<object>>) this.ValueFactory );
            Assert.AreEqual( (object) _value, value );
          }


          {
            await service.Remove( "Test" );
            value = null;

            var _value = await service.Fetch( "Test", "Test" );
            Assert.AreEqual( _value, "Test" );
            Assert.AreNotEqual( _value, value );
          }


          {
            await service.Update<object>( (string) "Test", (Func<Task<object>>) this.ValueFactory );
            var _value = await service.FetchOrAdd<object>( (string) "Test", (Func<Task<object>>) this.ValueFactory );
            Assert.AreEqual( (object) _value, value );
          }

          {
            await service.Clear();
            var _value = await service.Fetch( "Test", "Test" );
            Assert.AreEqual( _value, "Test" );
            Assert.AreNotEqual( _value, value );
          }



        }
      }) ).Wait();
    }
        public async Task <IHttpActionResult> Flush()
        {
            await CacheService.FlushAsync();

            return(Ok());
        }
        public ChooseDialogViewModel(ICacheService cacheService, ICommonErrorHandler errorHandler, IStateService stateService, INavigationService navigationService, IMTProtoService mtProtoService, ITelegramEventAggregator eventAggregator)
            : base(cacheService, errorHandler, stateService, navigationService, mtProtoService, eventAggregator)
        {
            FilteredItems = new CollectionViewSource {
                Source = Items
            }.View;
            FilteredItems.Filter += item =>
            {
                var dialog = item as TLDialog;
                if (dialog != null)
                {
                    var chat = dialog.With as TLChat41;
                    if (chat != null)
                    {
                        return(!chat.IsMigrated);
                    }

                    var user = dialog.With as TLUser;
                    if (user != null)
                    {
                        return(!user.IsSelf);
                    }
                }

                var dialog71 = dialog as TLDialog71;
                if (dialog71 != null)
                {
                    return(!dialog71.IsPromo);
                }

                return(true);
            };

            EventAggregator.Subscribe(this);

            LogFileName = StateService.LogFileName;
            StateService.LogFileName = null;

            ForwardedMessages            = StateService.ForwardMessages;
            StateService.ForwardMessages = null;

            SharedContact = StateService.SharedContact;
            StateService.SharedContact = null;

            _gameString             = StateService.GameString;
            StateService.GameString = null;

            _accessToken             = StateService.AccessToken;
            StateService.AccessToken = null;

            _bot             = StateService.Bot;
            StateService.Bot = null;

            _webLink             = StateService.WebLink;
            StateService.WebLink = null;

            _storageItems             = StateService.StorageItems;
            StateService.StorageItems = null;

            _url             = StateService.Url;
            StateService.Url = null;

            _text = StateService.UrlText;
            StateService.UrlText = null;

            _switchInlineButton             = StateService.SwitchInlineButton;
            StateService.SwitchInlineButton = null;

            Status = AppResources.Loading;

            BeginOnThreadPool(() =>
            {
                var isAuthorized = SettingsHelper.GetValue <bool>(Constants.IsAuthorizedKey);
                if (isAuthorized)
                {
                    var dialogs = CacheService.GetDialogs();

                    var dialogsCache   = new Dictionary <int, TLDialogBase>();
                    var clearedDialogs = new List <TLDialogBase>();
                    foreach (var dialog in dialogs)
                    {
                        if (!dialogsCache.ContainsKey(dialog.Index))
                        {
                            var user = dialog.With as TLUser;
                            if (user != null && user.IsSelf)
                            {
                                CurrentUser = dialog;
                            }

                            if (dialog is TLDialog || dialog is TLBroadcastDialog)
                            {
                                if (!SkipDialogForBot(_bot, dialog))
                                {
                                    clearedDialogs.Add(dialog);
                                }
                                dialogsCache[dialog.Index] = dialog;
                            }
                        }
                        else
                        {
                            var cachedDialog = dialogsCache[dialog.Index];
                            if (cachedDialog.Peer is TLPeerUser && dialog.Peer is TLPeerUser)
                            {
                                CacheService.DeleteDialog(dialog);
                                continue;
                            }
                            if (cachedDialog.Peer is TLPeerChat && dialog.Peer is TLPeerChat)
                            {
                                CacheService.DeleteDialog(dialog);
                                continue;
                            }
                        }
                    }

                    if (CurrentUser == null)
                    {
                        var currentUser = CacheService.GetUser(new TLInt(StateService.CurrentUserId));
                        if (currentUser != null)
                        {
                            var dialog = new TLDialog71
                            {
                                With  = currentUser,
                                Flags = new TLInt(0),
                                Peer  = new TLPeerUser {
                                    Id = currentUser.Id
                                },
                                Messages            = new ObservableCollection <TLMessageBase>(),
                                TopMessageId        = new TLInt(0),
                                ReadInboxMaxId      = new TLInt(0),
                                ReadOutboxMaxId     = new TLInt(0),
                                UnreadCount         = new TLInt(0),
                                UnreadMentionsCount = new TLInt(0),
                                NotifySettings      = new TLPeerNotifySettings78 {
                                    Flags = new TLInt(0), MuteUntil = new TLInt(0), Sound = new TLString("Default")
                                }
                            };
                            CurrentUser = dialog;
                        }
                    }

                    BeginOnUIThread(() =>
                    {
                        NotifyOfPropertyChange(() => CurrentUser);

                        foreach (var clearedDialog in clearedDialogs)
                        {
                            LazyItems.Add(clearedDialog);
                        }

                        var lastDialog = clearedDialogs.LastOrDefault(x => x.TopMessageId != null);
                        _maxId         = lastDialog != null ? lastDialog.TopMessageId.Value : 0;

                        Status             = LazyItems.Count == 0 ? AppResources.Loading : string.Empty;
                        var importantCount = 0;
                        var count          = 0;
                        for (var i = 0; i < LazyItems.Count && importantCount < FirstSliceLength; i++, count++)
                        {
                            Items.Add(LazyItems[i]);
                            var chat41 = LazyItems[i].With as TLChat41;
                            if (chat41 == null || chat41.MigratedTo == null)
                            {
                                importantCount++;
                            }
                        }

                        BeginOnUIThread(TimeSpan.FromSeconds(0.5), () =>
                        {
                            for (var i = count; i < LazyItems.Count; i++)
                            {
                                Items.Add(LazyItems[i]);
                            }
                            LazyItems.Clear();

                            LoadNextSlice();
                        });
                    });
                }
            });
        }
示例#11
0
 public void Then_Expected_Methods_Called()
 {
     ProviderAddressLoader.Received(1).AddAddressAsync(ProviderUkprn, AddAddressViewModel);
     CacheService.DidNotReceive().RemoveAsync <AddAddressViewModel>(CacheKey);
 }
示例#12
0
        public void Done()
        {
            if (SelectedMainRule == null)
            {
                return;
            }

            var rules = new TLVector <TLInputPrivacyRuleBase>();

            if (_selectedDisallowUsers != null &&
                _selectedDisallowUsers.Users != null &&
                _selectedDisallowUsers.Users.Count > 0)
            {
                var inputDisallowUsers = (TLInputPrivacyValueDisallowUsers)_selectedDisallowUsers.ToInputRule();

                foreach (var userId in _selectedDisallowUsers.Users)
                {
                    var user = CacheService.GetUser(userId);

                    if (user != null)
                    {
                        inputDisallowUsers.Users.Add(user.ToInputUser());
                    }
                }

                rules.Add(inputDisallowUsers);
            }

            if (_selectedAllowUsers != null &&
                _selectedAllowUsers.Users != null &&
                _selectedAllowUsers.Users.Count > 0)
            {
                var inputAllowUsers = (TLInputPrivacyValueAllowUsers)_selectedAllowUsers.ToInputRule();

                foreach (var userId in _selectedAllowUsers.Users)
                {
                    var user = CacheService.GetUser(userId);

                    if (user != null)
                    {
                        inputAllowUsers.Users.Add(user.ToInputUser());
                    }
                }

                rules.Add(inputAllowUsers);
            }

            var inputMainRule = SelectedMainRule.ToInputRule();

            rules.Add(inputMainRule);

            IsWorking = true;
            MTProtoService.SetPrivacyAsync(new TLInputPrivacyKeyChatInvite(),
                                           rules,
                                           result =>
            {
                IsWorking = false;

                //EventAggregator.Publish(new TLUpdatePrivacy{Key = new TLPrivacyKeyStatusTimestamp(), Rules = result.Rules});
                BeginOnUIThread(() => NavigationService.GoBack());
            },
                                           error =>
            {
                IsWorking = false;
                if (error.CodeEquals(ErrorCode.FLOOD))
                {
                    MessageBox.Show(AppResources.FloodWaitString + Environment.NewLine + "(" + error.Message + ")", AppResources.Error, MessageBoxButton.OK);
                }

                Execute.ShowDebugMessage("account.setPrivacy error " + error);
            });
        }
示例#13
0
 public ConfigurationController(IMemoryCache cache)
 {
     _cacheService = new CacheService(cache, GetConfigurationByPath("Paths:Localization"));
 }
示例#14
0
        /// <summary>
        /// Create a new server on endpoint with packet handler repository
        /// </summary>
        public RadiusServer(ServiceConfiguration serviceConfiguration, IRadiusDictionary dictionary, IRadiusPacketParser radiusPacketParser, CacheService cacheService, ILogger logger)
        {
            _serviceConfiguration = serviceConfiguration ?? throw new ArgumentNullException(nameof(serviceConfiguration));
            _dictionary           = dictionary ?? throw new ArgumentNullException(nameof(dictionary));
            _radiusPacketParser   = radiusPacketParser ?? throw new ArgumentNullException(nameof(radiusPacketParser));
            _cacheService         = cacheService ?? throw new ArgumentNullException(nameof(cacheService));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));

            _localEndpoint = serviceConfiguration.ServiceServerEndpoint;
            _router        = new RadiusRouter(serviceConfiguration, radiusPacketParser, logger);
        }
示例#15
0
        public void CacheDisabledDelete()
        {
            var service = new CacheService(null);

            Assert.IsFalse(service.Delete("cachekey"));
        }
示例#16
0
        private async Task SendGifAsync(StorageFile file, string caption)
        {
            var fileLocation = new TLFileLocation
            {
                VolumeId = TLLong.Random(),
                LocalId  = TLInt.Random(),
                Secret   = TLLong.Random(),
                DCId     = 0
            };

            var fileName  = string.Format("{0}_{1}_{2}.gif", fileLocation.VolumeId, fileLocation.LocalId, fileLocation.Secret);
            var fileCache = await FileUtils.CreateTempFileAsync(fileName);

            await file.CopyAndReplaceAsync(fileCache);

            var basicProps = await fileCache.GetBasicPropertiesAsync();

            var imageProps = await fileCache.Properties.GetImagePropertiesAsync();

            var thumbnailBase = await FileUtils.GetFileThumbnailAsync(file);

            var thumbnail = thumbnailBase as TLPhotoSize;

            var desiredName = string.Format("{0}_{1}_{2}.jpg", thumbnail.Location.VolumeId, thumbnail.Location.LocalId, thumbnail.Location.Secret);

            var date = TLUtils.DateToUniversalTimeTLInt(ProtoService.ClientTicksDelta, DateTime.Now);

            var document = new TLDocument
            {
                Id         = 0,
                AccessHash = 0,
                Date       = date,
                Size       = (int)basicProps.Size,
                MimeType   = fileCache.ContentType,
                Thumb      = thumbnail,
                Attributes = new TLVector <TLDocumentAttributeBase>
                {
                    new TLDocumentAttributeAnimated(),
                    new TLDocumentAttributeFilename
                    {
                        FileName = file.Name
                    },
                    new TLDocumentAttributeImageSize
                    {
                        W = (int)imageProps.Width,
                        H = (int)imageProps.Height
                    },
                    new TLDocumentAttributeVideo
                    {
                        W = (int)imageProps.Width,
                        H = (int)imageProps.Height,
                    }
                }
            };

            var media = new TLMessageMediaDocument
            {
                Caption  = caption,
                Document = document
            };

            var message = TLUtils.GetMessage(SettingsHelper.UserId, Peer.ToPeer(), TLMessageState.Sending, true, true, date, string.Empty, media, TLLong.Random(), null);

            if (Reply != null)
            {
                message.HasReplyToMsgId = true;
                message.ReplyToMsgId    = Reply.Id;
                message.Reply           = Reply;
                Reply = null;
            }

            var previousMessage = InsertSendingMessage(message);

            CacheService.SyncSendingMessage(message, previousMessage, async(m) =>
            {
                var fileId = TLLong.Random();
                var upload = await _uploadDocumentManager.UploadFileAsync(fileId, fileName, false).AsTask(media.Document.Upload());
                if (upload != null)
                {
                    var thumbFileId = TLLong.Random();
                    var thumbUpload = await _uploadDocumentManager.UploadFileAsync(thumbFileId, desiredName);
                    if (thumbUpload != null)
                    {
                        var inputMedia = new TLInputMediaUploadedDocument
                        {
                            File       = upload.ToInputFile(),
                            Thumb      = thumbUpload.ToInputFile(),
                            MimeType   = document.MimeType,
                            Caption    = media.Caption,
                            Attributes = document.Attributes
                        };

                        var result = await ProtoService.SendMediaAsync(Peer, inputMedia, message);
                    }
                }
            });
        }
示例#17
0
        public void CacheDisabledSet()
        {
            var service = new CacheService(null);

            Assert.IsFalse(service.Set("cachekey", "Hello", new TimeSpan(1, 0, 0, 0)));
        }
示例#18
0
        public void CacheDisabledGet()
        {
            var service = new CacheService(null);

            Assert.IsNull(service.Get <string>("cachekey"));
        }
示例#19
0
        public void CacheDisabled()
        {
            var service = new CacheService(null);

            Assert.IsFalse(service.CacheEnabled);
        }
示例#20
0
 public void Init()
 {
     cacheService = CacheService.Instance;
     PECommon.Log("登录系统初始化完成...");
 }
示例#21
0
 public TreeController(PagePresenterService pages, TreePresenterService tree, CacheService cache)
 {
     _pages = pages;
     _tree  = tree;
     _cache = cache;
 }
示例#22
0
		public async Task Invalidate_WithAttributes_ShouldRemoveCacheEntry(
			[Frozen] Mock<ICacheEntryRepository> cacheEntryRepo,
			CacheService sut,
			string key,
			CacheEntry<TestCacheReturnValue> entry,
			Dictionary<string,string> attributes)
		{
			//arrange
			cacheEntryRepo.Setup(c => c.Get<TestCacheReturnValue>(It.IsAny<CancellationToken>(), key, attributes))
			              .ReturnsTask(entry);

			//act
			await sut.Invalidate<TestCacheReturnValue>(CancellationToken.None, key, attributes);

			//assert
			cacheEntryRepo.Verify(c => c.Remove<TestCacheReturnValue>(CancellationToken.None, key, entry.Id));
		}
示例#23
0
 public AccountsCache(CacheService cache, TzktContext db)
 {
     Cache = cache;
     Db    = db;
 }
示例#24
0
		public void Sut_ShouldBeCacheService(
			CacheService sut)
		{
			sut.Should().BeAssignableTo<ICacheService>();
		}
示例#25
0
 private void ChatNotifyExecute(Chat chat)
 {
     _notificationsService.SetMuteFor(chat, CacheService.GetNotificationSettingsMuteFor(chat) > 0 ? 0 : 632053052);
 }
示例#26
0
        private void UpdatePrivacy(UserPrivacySettingRules rules)
        {
            _rules = rules;
            var          badge      = string.Empty;
            PrivacyValue?primary    = null;
            var          restricted = 0;
            var          allowed    = 0;
            UserPrivacySettingRuleAllowUsers          allowedUsers          = null;
            UserPrivacySettingRuleAllowChatMembers    allowedChatMembers    = null;
            UserPrivacySettingRuleRestrictUsers       restrictedUsers       = null;
            UserPrivacySettingRuleRestrictChatMembers restrictedChatMembers = null;

            foreach (var current in rules.Rules)
            {
                if (current is UserPrivacySettingRuleAllowAll && primary == null)
                {
                    primary = PrivacyValue.AllowAll;
                    badge   = Strings.Resources.LastSeenEverybody;
                }
                else if (current is UserPrivacySettingRuleAllowContacts && primary == null)
                {
                    primary = PrivacyValue.AllowContacts;
                    badge   = Strings.Resources.LastSeenContacts;
                }
                else if (current is UserPrivacySettingRuleRestrictAll && primary == null)
                {
                    primary = PrivacyValue.DisallowAll;
                    badge   = Strings.Resources.LastSeenNobody;
                }
                else if (current is UserPrivacySettingRuleRestrictUsers disallowUsers)
                {
                    restrictedUsers = disallowUsers;
                    restricted     += disallowUsers.UserIds.Count;
                }
                else if (current is UserPrivacySettingRuleAllowUsers allowUsers)
                {
                    allowedUsers = allowUsers;
                    allowed     += allowUsers.UserIds.Count;
                }
                else if (current is UserPrivacySettingRuleRestrictChatMembers restrictChatMembers)
                {
                    restrictedChatMembers = restrictChatMembers;

                    foreach (var chatId in restrictChatMembers.ChatIds)
                    {
                        var chat = CacheService.GetChat(chatId);
                        if (chat == null)
                        {
                            continue;
                        }

                        if (CacheService.TryGetBasicGroup(chat, out BasicGroup basicGroup))
                        {
                            restricted += basicGroup.MemberCount;
                        }
                        else if (CacheService.TryGetSupergroup(chat, out Supergroup supergroup))
                        {
                            restricted += supergroup.MemberCount;
                        }
                    }
                }
                else if (current is UserPrivacySettingRuleAllowChatMembers allowChatMembers)
                {
                    allowedChatMembers = allowChatMembers;

                    foreach (var chatId in allowChatMembers.ChatIds)
                    {
                        var chat = CacheService.GetChat(chatId);
                        if (chat == null)
                        {
                            continue;
                        }

                        if (CacheService.TryGetBasicGroup(chat, out BasicGroup basicGroup))
                        {
                            allowed += basicGroup.MemberCount;
                        }
                        else if (CacheService.TryGetSupergroup(chat, out Supergroup supergroup))
                        {
                            allowed += supergroup.MemberCount;
                        }
                    }
                }
            }

            if (primary == null)
            {
                primary = PrivacyValue.DisallowAll;
                badge   = Strings.Resources.LastSeenNobody;
            }

            var list = new List <string>();

            if (restricted > 0)
            {
                list.Add("-" + restricted);
            }
            if (allowed > 0)
            {
                list.Add("+" + allowed);
            }

            if (list.Count > 0)
            {
                badge = string.Format("{0} ({1})", badge, string.Join(", ", list));
            }

            _restrictedUsers       = restrictedUsers ?? new UserPrivacySettingRuleRestrictUsers(new int[0]);
            _restrictedChatMembers = restrictedChatMembers ?? new UserPrivacySettingRuleRestrictChatMembers(new long[0]);

            _allowedUsers       = allowedUsers ?? new UserPrivacySettingRuleAllowUsers(new int[0]);
            _allowedChatMembers = allowedChatMembers ?? new UserPrivacySettingRuleAllowChatMembers(new long[0]);

            BeginOnUIThread(() =>
            {
                SelectedItem = primary ?? PrivacyValue.DisallowAll;

                Badge           = badge;
                AllowedBadge    = allowed > 0 ? Locale.Declension("Users", allowed) : Strings.Resources.EmpryUsersPlaceholder;
                RestrictedBadge = restricted > 0 ? Locale.Declension("Users", restricted) : Strings.Resources.EmpryUsersPlaceholder;
            });
        }
示例#27
0
    public void ExcepionTest()
    {

      using ( var provider = new MemoryCacheProvider( "Test" ).AsAsyncProvider() )
      {
        var cacheService = new CacheService( provider );


        Task.Run( (Func<Task>) (async () =>
          {

            bool exception_catched = false;

            try
            {

              await cacheService.FetchOrAdd<string>( (string) "Test", (Func<Task<string>>) this.ValueFactoryWithException, (Caching.CachePolicy) Caching.CachePolicy.Expires( (TimeSpan) TimeSpan.FromHours( (double) 1 ) ) );
            }
            catch
            {
              exception_catched = true;
            }

            Assert.IsTrue( exception_catched );

            var value = await cacheService.FetchOrAdd<string>( (string) "Test", (Func<Task<string>>) this.ValueFactory, (Caching.CachePolicy) Caching.CachePolicy.Expires( (TimeSpan) TimeSpan.FromHours( (double) 1 ) ) );
            Assert.AreEqual( (string) value, _value );


          })
        ).Wait();

      }
    }
示例#28
0
 public ListController(TolkDbContext tolkDbContext, CacheService cacheService, ISwedishClock timeService)
 {
     _dbContext    = tolkDbContext;
     _cacheService = cacheService;
     _timeService  = timeService;
 }
示例#29
0
        public async Task SendAudioAsync(StorageFile file, int duration, bool voice, string title, string performer, string caption)
        {
            var fileLocation = new TLFileLocation
            {
                VolumeId = TLLong.Random(),
                LocalId  = TLInt.Random(),
                Secret   = TLLong.Random(),
                DCId     = 0
            };

            var fileName  = string.Format("{0}_{1}_{2}.ogg", fileLocation.VolumeId, fileLocation.LocalId, fileLocation.Secret);
            var fileCache = await FileUtils.CreateTempFileAsync(fileName);

            await file.CopyAndReplaceAsync(fileCache);

            var basicProps = await fileCache.GetBasicPropertiesAsync();

            var imageProps = await fileCache.Properties.GetImagePropertiesAsync();

            var date = TLUtils.DateToUniversalTimeTLInt(ProtoService.ClientTicksDelta, DateTime.Now);

            var media = new TLMessageMediaDocument
            {
                Caption  = caption,
                Document = new TLDocument
                {
                    Id         = TLLong.Random(),
                    AccessHash = TLLong.Random(),
                    Date       = date,
                    MimeType   = "audio/ogg",
                    Size       = (int)basicProps.Size,
                    Thumb      = new TLPhotoSizeEmpty
                    {
                        Type = string.Empty
                    },
                    Version    = 0,
                    DCId       = 0,
                    Attributes = new TLVector <TLDocumentAttributeBase>
                    {
                        new TLDocumentAttributeAudio
                        {
                            IsVoice   = voice,
                            Duration  = duration,
                            Title     = title,
                            Performer = performer
                        }
                    }
                }
            };

            var message = TLUtils.GetMessage(SettingsHelper.UserId, Peer.ToPeer(), TLMessageState.Sending, true, true, date, string.Empty, media, TLLong.Random(), null);

            if (Reply != null)
            {
                message.HasReplyToMsgId = true;
                message.ReplyToMsgId    = Reply.Id;
                message.Reply           = Reply;
                Reply = null;
            }

            var previousMessage = InsertSendingMessage(message);

            CacheService.SyncSendingMessage(message, previousMessage, async(m) =>
            {
                var fileId = TLLong.Random();
                var upload = await _uploadAudioManager.UploadFileAsync(fileId, fileName, false).AsTask(Upload(media.Document as TLDocument, progress => new TLSendMessageUploadAudioAction {
                    Progress = progress
                }));
                if (upload != null)
                {
                    var inputMedia = new TLInputMediaUploadedDocument
                    {
                        File       = upload.ToInputFile(),
                        MimeType   = "audio/ogg",
                        Caption    = media.Caption,
                        Attributes = new TLVector <TLDocumentAttributeBase>
                        {
                            new TLDocumentAttributeAudio
                            {
                                IsVoice   = voice,
                                Duration  = duration,
                                Title     = title,
                                Performer = performer
                            }
                        }
                    };

                    var result = await ProtoService.SendMediaAsync(Peer, inputMedia, message);
                }
            });
        }
 public void Then_SessionActivity_Is_Not_Recored()
 {
     CacheService.DidNotReceive().SetAsync(CacheKey, Arg.Any <DateTime>());
 }
 public LookupService(IGeneralRepository repo)
 {
     this._repo = repo;
     this._cacheService = new CacheService<LookupModel>();
 }
示例#32
0
        private void SendExecute()
        {
            var dialogs = SelectedItems.ToList();

            if (dialogs.Count == 0)
            {
                return;
            }

            var date = TLUtils.DateToUniversalTimeTLInt(ProtoService.ClientTicksDelta, DateTime.Now);

            if (_message != null)
            {
                foreach (var dialog in dialogs)
                {
                    TLInputPeerBase toPeer     = dialog.ToInputPeer();
                    TLInputPeerBase fromPeer   = null;
                    var             fwdMessage = _message;

                    var msgs   = new TLVector <TLMessage>();
                    var msgIds = new TLVector <int>();

                    var clone = fwdMessage.Clone();
                    clone.Id = 0;
                    clone.HasReplyToMsgId = false;
                    clone.ReplyToMsgId    = null;
                    clone.HasReplyMarkup  = false;
                    clone.ReplyMarkup     = null;
                    clone.Date            = date;
                    clone.ToId            = dialog.Peer;
                    clone.RandomId        = TLLong.Random();
                    clone.IsOut           = true;
                    clone.IsPost          = false;
                    clone.FromId          = SettingsHelper.UserId;
                    clone.IsMediaUnread   = dialog.Peer is TLPeerChannel ? true : false;
                    clone.IsUnread        = true;
                    clone.State           = TLMessageState.Sending;

                    if (clone.Media == null)
                    {
                        clone.HasMedia = true;
                        clone.Media    = new TLMessageMediaEmpty();
                    }

                    if (fwdMessage.Parent is TLChannel channel)
                    {
                        if (channel.IsBroadcast)
                        {
                            if (!channel.IsSignatures)
                            {
                                clone.HasFromId = false;
                                clone.FromId    = null;
                            }

                            // TODO
                            //if (IsSilent)
                            //{
                            //    clone.IsSilent = true;
                            //}

                            clone.HasViews = true;
                            clone.Views    = 1;
                        }
                    }

                    if (clone.Media is TLMessageMediaGame gameMedia)
                    {
                        clone.HasEntities = false;
                        clone.Entities    = null;
                        clone.Message     = null;
                    }

                    if (fromPeer == null)
                    {
                        fromPeer = fwdMessage.Parent.ToInputPeer();
                    }

                    if (clone.FwdFrom == null && !clone.IsGame())
                    {
                        if (fwdMessage.ToId is TLPeerChannel)
                        {
                            var fwdChannel = CacheService.GetChat(fwdMessage.ToId.Id) as TLChannel;
                            if (fwdChannel != null && fwdChannel.IsMegaGroup)
                            {
                                clone.HasFwdFrom = true;
                                clone.FwdFrom    = new TLMessageFwdHeader
                                {
                                    HasFromId = true,
                                    FromId    = fwdMessage.FromId,
                                    Date      = fwdMessage.Date
                                };
                            }
                            else
                            {
                                clone.HasFwdFrom = true;
                                clone.FwdFrom    = new TLMessageFwdHeader
                                {
                                    HasFromId = fwdMessage.HasFromId,
                                    FromId    = fwdMessage.FromId,
                                    Date      = fwdMessage.Date
                                };

                                if (fwdChannel.IsBroadcast)
                                {
                                    clone.FwdFrom.HasChannelId = clone.FwdFrom.HasChannelPost = true;
                                    clone.FwdFrom.ChannelId    = fwdChannel.Id;
                                    clone.FwdFrom.ChannelPost  = fwdMessage.Id;
                                }
                            }
                        }
                        else if (fwdMessage.ToId is TLPeerUser peerUser && peerUser.UserId == SettingsHelper.UserId)
                        {
                        }
                        else
                        {
                            clone.HasFwdFrom = true;
                            clone.FwdFrom    = new TLMessageFwdHeader
                            {
                                HasFromId = true,
                                FromId    = fwdMessage.FromId,
                                Date      = fwdMessage.Date
                            };
                        }
                    }

                    msgs.Add(clone);
                    msgIds.Add(fwdMessage.Id);

                    CacheService.SyncSendingMessage(clone, null, async(m) =>
                    {
                        var response = await ProtoService.ForwardMessagesAsync(toPeer, fromPeer, msgIds, msgs, IsWithMyScore);
                        if (response.IsSucceeded)
                        {
                            Aggregator.Publish(m);
                        }
                    });
                }

                NavigationService.GoBack();
            }
示例#33
0
		public async Task ExecuteWithCache_WhenValueIsNotCachedWithAttributes_ShouldAddEntryToCache(
			[Frozen] Mock<ICacheEntryRepository> cacheEntryRepo,
			CacheService sut,
			string key,
			TestCacheReturnValue expected,
			Dictionary<string, string> attributes)
		{
			//arrange
			cacheEntryRepo.Setup(c => c.Get<TestCacheReturnValue>(It.IsAny<CancellationToken>(), key, attributes))
			              .ReturnsTask(default(CacheEntry<TestCacheReturnValue>));
			cacheEntryRepo.Setup(c => c.AddOrUpdate(CancellationToken.None, It.Is<CacheEntry<TestCacheReturnValue>>(entry =>
				entry.CacheKey == key && entry.Value == expected && entry.Attributes == attributes)))
			              .ReturnsDefaultTask()
			              .Verifiable();

			//act
			await sut.ExecuteWithCache(CancellationToken.None, key, () => Task.FromResult(expected), TimeSpan.Zero, attributes);

			//assert
			cacheEntryRepo.Verify();
		}
示例#34
0
 public Validator(ProtocolHandler protocol)
 {
     Cache = protocol.Cache;
 }
示例#35
0
		public async Task ExecuteWithCache_WhenValueIsCachedAndAgeEntryIsTooOldWithAttributes_ShouldAddNewEntry(
			[Frozen] Mock<ICacheEntryRepository> cacheEntryRepo,
			CacheService sut,
			string key,
			TestCacheReturnValue expected,
			TestCacheReturnValue notExpected,
			DateTimeOffset now,
			Guid id,
			Dictionary<string, string> attributes)
		{
			//arrange
			cacheEntryRepo.Setup(c => c.Get<TestCacheReturnValue>(It.IsAny<CancellationToken>(), key, attributes))
			              .ReturnsTask(new CacheEntry<TestCacheReturnValue>(
				              id,
				              key,
				              new Dictionary<string, string>(),
				              now.Subtract(TimeSpan.FromMinutes(10)),
				              notExpected));
			cacheEntryRepo.Setup(c => c.AddOrUpdate(CancellationToken.None, It.Is<CacheEntry<TestCacheReturnValue>>(entry =>
				entry.CacheKey == key &&
				entry.Value == expected &&
				entry.Attributes == attributes)))
			              .ReturnsDefaultTask()
			              .Verifiable();

			//act
			await sut.ExecuteWithCache(CancellationToken.None, key, () => Task.FromResult(expected), TimeSpan.FromMinutes(5), attributes);

			//assert
			cacheEntryRepo.Verify();
		}
示例#36
0
        private async void TopChatDeleteExecute(Chat chat)
        {
            if (chat == null)
            {
                return;
            }

            var confirm = await TLMessageDialog.ShowAsync(string.Format(Strings.Resources.ChatHintsDelete, CacheService.GetTitle(chat)), Strings.Resources.AppName, Strings.Resources.OK, Strings.Resources.Cancel);

            if (confirm != ContentDialogResult.Primary)
            {
                return;
            }

            ProtoService.Send(new RemoveTopChat(new TopChatCategoryUsers(), chat.Id));
            TopChats.Remove(chat);
        }
示例#37
0
 public GameHub(CacheService cache)
 {
     this.cache = cache;
 }
示例#38
0
    public void DiskCache()
    {
      using ( var provider = new DiskCacheProvider( @"C:\Temp\Cache" ) )
      {
        var cacheService = new CacheService( provider );


        var tasks = new List<Task>();


        //测试并发创建值
        for ( int i = 0; i < 1000; i++ )
        {
          Func<int, Task> task = async ( j ) =>
          {
            await Task.Yield();

            var value = await cacheService.FetchOrAdd( "Test", ValueFactory, CachePolicy.Expires( TimeSpan.FromHours( 1 ) ) );
            Assert.AreEqual( value, _value );
          };

          tasks.Add( task( i ) );
        }

        Task.WaitAll( tasks.ToArray() );



        //测试从缓存读取
        for ( int i = 0; i < 1000; i++ )
        {
          Func<int, Task> task = async ( j ) =>
          {
            await Task.Yield();

            var value = await cacheService.FetchOrAdd( "Test", ValueFactory, CachePolicy.Expires( TimeSpan.FromHours( 1 ) ) );
            Assert.AreEqual( value, _value );
          };

          tasks.Add( task( i ) );
        }
        Task.WaitAll( tasks.ToArray() );




        //清除缓存
        cacheService.Clear();
        _value = null;




        //测试创建新值
        for ( int i = 0; i < 1000; i++ )
        {
          Func<int, Task> task = async ( j ) =>
          {
            await Task.Yield();

            var value = await cacheService.FetchOrAdd( "Test", ValueFactory, CachePolicy.Expires( TimeSpan.FromHours( 1 ) ) );
            Assert.AreEqual( value, _value );
          };

          tasks.Add( task( i ) );
        }
        Task.WaitAll( tasks.ToArray() );



        cacheService.Clear();
        {
          _value = null;
          var value = cacheService.FetchOrAdd( "Test", ValueFactory, CachePolicy.Expires( TimeSpan.FromHours( 1 ) ) ).Result;

          Assert.IsNotNull( _value );
          Assert.AreEqual( _value, value );
        }
      }
    }
示例#39
0
 public override void Given()
 {
     cacheResult = new AddLearnerRecordViewModel();
     CacheService.GetAsync <AddLearnerRecordViewModel>(CacheKey).Returns(cacheResult);
 }
 internal TimeBasedPassword(IHashAlgorithm hmac, CacheService cache, string secrectKey, int validityPeriodSeconds = DEFAULT_VALIDITY_PERIODE_SECONDS)
     :this(hmac, cache)
 {
     this._secret = secrectKey;
 }
示例#41
0
 public UnpkgProvider(IHostInteraction hostInteraction)
 {
     HostInteraction = hostInteraction;
     // TODO: {alexgav} Do we need multiple instances of CacheService?
     _cacheService = new CacheService(WebRequestHandler.Instance);
 }
示例#42
0
		public async Task ExecuteWithCache_WhenValueIsCachedAndAgeEntryIsTooOld_ShouldRemoveOldEntry(
			[Frozen] Mock<ICacheEntryRepository> cacheEntryRepo,
			CacheService sut,
			string key,
			TestCacheReturnValue expected,
			TestCacheReturnValue notExpected,
			DateTimeOffset now,
			Guid id)
		{
			//arrange
			cacheEntryRepo.Setup(c => c.Get<TestCacheReturnValue>(It.IsAny<CancellationToken>(), key, It.Is<IDictionary<string, string>>(d => d.Count == 0)))
			              .ReturnsTask(new CacheEntry<TestCacheReturnValue>(
				              id,
				              key,
				              new Dictionary<string, string>(),
				              now.Subtract(TimeSpan.FromMinutes(10)),
				              notExpected));

			//act
			await sut.ExecuteWithCache(CancellationToken.None, key, () => Task.FromResult(expected), TimeSpan.FromMinutes(5));

			//assert
			cacheEntryRepo.Verify(c => c.Remove<TestCacheReturnValue>(CancellationToken.None, key, id));
		}
示例#43
0
 public HomeController(ApplicationContext db, IWebHostEnvironment env, CacheService cache)
 {
     _db    = db;
     _env   = env;
     _cache = cache;
 }
示例#44
0
		public async Task ExecuteWithCache_WhenValueIsCachedWithAttributes_ShouldReturnCorrectValue(
			[Frozen] Mock<ICacheEntryRepository> cacheEntryRepo,
			CacheService sut,
			string key,
			TestCacheReturnValue expected,
			TestCacheReturnValue notExpected,
			DateTimeOffset now,
			Dictionary<string, string> attributes)
		{
			//arrange
			cacheEntryRepo.Setup(c => c.Get<TestCacheReturnValue>(It.IsAny<CancellationToken>(), key, attributes))
			              .ReturnsTask(new CacheEntry<TestCacheReturnValue>(Guid.NewGuid(), key, attributes, now, expected));

			//act
			var actual = await sut.ExecuteWithCache(CancellationToken.None, key, () => Task.FromResult(notExpected), TimeSpan.Zero, attributes);

			//assert
			actual.Should().Be(expected);
		}
示例#45
0
        public async void Handle(TLUpdatePhoneCall update)
        {
            await VoIPConnection.Current.SendUpdateAsync(update);

            await Task.Delay(2000);

            //if (update.PhoneCall is TLPhoneCallDiscarded discarded)
            //{
            //    if (discarded.IsNeedRating)
            //    {
            //        Debugger.Break();
            //    }

            //    if (discarded.IsNeedDebug)
            //    {
            //        Debugger.Break();
            //    }
            //}

            return;

            if (update.PhoneCall is TLPhoneCallRequested callRequested)
            {
                var reqReceived = new TLPhoneReceivedCall();
                reqReceived.Peer            = new TLInputPhoneCall();
                reqReceived.Peer.Id         = callRequested.Id;
                reqReceived.Peer.AccessHash = callRequested.AccessHash;

                ProtoService.SendRequestAsync <bool>("phone.receivedCall", reqReceived, null, null);

                var user = CacheService.GetUser(callRequested.AdminId) as TLUser;

                Execute.BeginOnUIThread(async() =>
                {
                    var dialog = await TLMessageDialog.ShowAsync(user.DisplayName, "CAAAALLL", "OK", "Cancel");
                    if (dialog == Windows.UI.Xaml.Controls.ContentDialogResult.Primary)
                    {
                        var config = await ProtoService.GetDHConfigAsync(0, 256);
                        if (config.IsSucceeded)
                        {
                            var dh = config.Result;
                            if (!TLUtils.CheckPrime(dh.P, dh.G))
                            {
                                return;
                            }

                            secretP = dh.P;

                            var salt         = new byte[256];
                            var secureRandom = new SecureRandom();
                            secureRandom.NextBytes(salt);

                            a_or_b = salt;

                            var g_b = MTProtoService.GetGB(salt, dh.G, dh.P);

                            var request = new TLPhoneAcceptCall
                            {
                                GB   = g_b,
                                Peer = new TLInputPhoneCall
                                {
                                    Id         = callRequested.Id,
                                    AccessHash = callRequested.AccessHash
                                },
                                Protocol = new TLPhoneCallProtocol
                                {
                                    IsUdpP2p       = true,
                                    IsUdpReflector = true,
                                    MinLayer       = 65,
                                    MaxLayer       = 65,
                                }
                            };

                            var response = await ProtoService.SendRequestAsync <TLPhonePhoneCall>("phone.acceptCall", request);
                            if (response.IsSucceeded)
                            {
                            }
                        }
                    }
                    else
                    {
                        var req             = new TLPhoneDiscardCall();
                        req.Peer            = new TLInputPhoneCall();
                        req.Peer.Id         = callRequested.Id;
                        req.Peer.AccessHash = callRequested.AccessHash;
                        req.Reason          = new TLPhoneCallDiscardReasonHangup();

                        ProtoService.SendRequestAsync <TLPhonePhoneCall>("phone.acceptCall", req, null, null);
                    }
                });
            }
            else if (update.PhoneCall is TLPhoneCall call)
            {
                var auth_key = computeAuthKey(call);
                var g_a      = call.GAOrB;

                var buffer = TLUtils.Combine(auth_key, g_a);
                var sha256 = Utils.ComputeSHA256(buffer);

                var emoji = EncryptionKeyEmojifier.EmojifyForCall(sha256);

                var user = CacheService.GetUser(call.AdminId) as TLUser;

                Execute.BeginOnUIThread(async() =>
                {
                    var dialog = await TLMessageDialog.ShowAsync(user.DisplayName, string.Join(" ", emoji), "OK");
                });
            }
        }
示例#46
0
		public async Task ExecuteWithCache_WhenValueIsNotCachedWithConcurrencyAndAttributes_ShouldReturnCorrectValue(
			[Frozen] Mock<ICacheEntryRepository> cacheEntryRepo,
			CacheService sut,
			string key,
			TestCacheReturnValue expected,
			TestCacheReturnValue notExpected,
			Dictionary<string, string> attributes)
		{
			//arrange
			cacheEntryRepo.Setup(c => c.Get<TestCacheReturnValue>(It.IsAny<CancellationToken>(), key, attributes))
			              .ReturnsTask(default(CacheEntry<TestCacheReturnValue>));


			//act
			Task<TestCacheReturnValue> actualTask = null;
			await sut.ExecuteWithCache(CancellationToken.None, key, () =>
			{
				actualTask = sut.ExecuteWithCache(CancellationToken.None, key, () => Task.FromResult(notExpected), TimeSpan.Zero, attributes);
				return Task.FromResult(expected);
			}, TimeSpan.Zero, attributes);
			var actual = await actualTask;

			//assert
			actual.Should().Be(expected);
		}
示例#47
0
        private static void Main(string[] args)
        {
            Console.WriteLine("=================紀錄Log測試==================");

            #region 紀錄Log

            //1.使用 ProxyFactory.GetProxyInstance 取得代理物件
            var t = ProxyFactory.GetProxyInstance <ServiceBase>(typeof(IntService));

            //2.執行方法
            var result = t.add(1, 2);
            t.SetPerson(new Person()
            {
                Age = 10
            });
            Console.WriteLine(result);

            #endregion 紀錄Log

            Console.WriteLine("=================權限驗證測試==================");

            #region  限攔截驗證

            //權限驗證:撰寫權限驗證 攔截代替寫入核心程式碼
            Console.WriteLine("權限驗證:只有RD可以查錢。");
            AuthService authService = ProxyFactory.GetProxyInstance <AuthService>();

            LoginInfo RDuser = new LoginInfo()
            {
                Name = "daniel",
                Type = AwesomeProxySample.AuthType.RD
            };

            LoginInfo PMuser = new LoginInfo()
            {
                Name = "Amy",
                Type = AwesomeProxySample.AuthType.PM
            };

            Console.WriteLine(authService.GetMoney(RDuser));
            Console.WriteLine(authService.GetMoney(PMuser));

            #endregion  限攔截驗證

            Console.WriteLine("===================快取測試====================");

            #region 快取測試

            Console.WriteLine("快取測試:測試資料是否被快取。");

            CacheService cache = ProxyFactory.GetProxyInstance <CacheService>();
            Console.WriteLine($"時間:{cache.GetCacheDate()}");

            Console.WriteLine("休息5秒鐘!~~");
            //睡眠5秒鐘
            Thread.Sleep(5000);

            Console.WriteLine($"時間:{cache.GetCacheDate()}");

            #endregion 快取測試

            Console.ReadKey();
        }
示例#48
0
		public async Task Invalidate_WithIsYoungerThanMinAge_ShouldNotRemoveCacheEntry(
			[Frozen] Mock<ICacheEntryRepository> cacheEntryRepo,
			CacheService sut,
			string key,
			TestCacheReturnValue value,
			DateTimeOffset now)
		{
			//arrange
			var entry = new CacheEntry<TestCacheReturnValue>(Guid.NewGuid(), key, new Dictionary<string, string>(), now.Subtract(TimeSpan.FromMinutes(2)), value);
			cacheEntryRepo.Setup(c => c.Get<TestCacheReturnValue>(It.IsAny<CancellationToken>(), key, It.Is<IDictionary<string, string>>(d => d.Count == 0)))
			              .ReturnsTask(entry);

			//act
			await sut.Invalidate<TestCacheReturnValue>(CancellationToken.None, key, TimeSpan.FromMinutes(2));

			//assert
			cacheEntryRepo.Verify(c => c.Remove<TestCacheReturnValue>(It.IsAny<CancellationToken>(), key, entry.Id), Times.Never());
		}
 public void Then_Expected_Methods_AreCalled()
 {
     CacheService.Received(1).GetAndRemoveAsync <LearnerRecordConfirmationViewModel>(ConfirmationCacheKey);
 }
示例#50
0
		public async Task ExecuteWithCache_WhenValueIsNotCached_ShouldReturnCorrectValue(
			[Frozen] Mock<ICacheEntryRepository> cacheEntryRepo,
			CacheService sut,
			string key,
			TestCacheReturnValue expected)
		{
			//arrange
			cacheEntryRepo.Setup(c => c.Get<TestCacheReturnValue>(It.IsAny<CancellationToken>(), key, It.Is<IDictionary<string, string>>(d => d.Count == 0)))
			              .ReturnsTask(default(CacheEntry<TestCacheReturnValue>));

			//act
			var actual = await sut.ExecuteWithCache(CancellationToken.None, key, () => Task.FromResult(expected), TimeSpan.Zero);

			//assert
			actual.Should().Be(expected);
		}
示例#51
0
 public void Then_Expected_Methods_Called()
 {
     CacheService.Received(1).RemoveAsync <AddLearnerRecordViewModel>(CacheKey);
 }