Beispiel #1
0
        public override void Run()
        {
            MemoryCacher<int, string> d = new MemoryCacher<int, string>(ARRAY_SIZE);
            __sw.Reset();
            __sw.Start();

            Parallel.For(0, 1000000, i => d.Add(i, "abc"));

            __sw.Stop();

            Console.WriteLine("Parallel Add MemoryCacher: {0}", __sw.ElapsedTicks);
        }
        private void GivenPolicyWithSlidingExpirationOf(TimeSpan expiration)
        {
            var policy = new System.Runtime.Caching.CacheItemPolicy {
                SlidingExpiration = expiration
            };

            _cacheItemPolicyConverterMock = new Mock <ICacheItemPolicyConverter>();
            _cacheItemPolicyConverterMock
            .Setup(e => e.Convert(It.IsAny <CacheItemPolicy>()))
            .Returns(policy);

            _cacher = new MemoryCacher(_cacheItemPolicyConverterMock.Object, _cacheItemPriorityMock.Object);
        }
        public GameResponse CreateGame([FromUri] CreateGameRequest request)
        {
            Game newGame = new Game()
            {
                Phase  = new Phase(),
                Id     = Guid.NewGuid(),
                Name   = request.Name,
                Status = Status.WaitingRoom
            };

            MemoryCacher.Replace(newGame.Id.ToString(), newGame, DateTimeOffset.UtcNow.AddHours(1));
            return(new GameResponse(newGame));
        }
Beispiel #4
0
        public IHttpActionResult GetUserSurveys(Guid projectId)
        {
            if (projectId == Guid.Empty)
            {
                return(BadRequest("project id is empty"));
            }

            var project = UnitOfWork.ProjectsRepository.Find(projectId);

            if (project == null)
            {
                return(NotFound());
            }

            var assignment = CurrentOrgUser.Assignments.SingleOrDefault(a => a.ProjectId == projectId);

            if (assignment == null || !assignment.CanView)
            {
                return(Unauthorized());
            }

            // we want records from advice threads too, so can't filter by FilledById.
            // this might need a refactoring but works for now.

            //var surveys = UnitOfWork.FilledFormsRepository.AllAsNoTracking
            //    .Where(s => s.ProjectId == projectId && s.FilledById == CurrentOrgUser.Id)
            //    .OrderByDescending(s => s.DateCreated);

            var cacheKey   = $"{CACHE_KEY}_{projectId}_{CurrentOrgUser.Id}";
            var cacheEntry = MemoryCacher.GetValue(cacheKey);

            if (cacheEntry == null)
            {
                var surveys = UnitOfWork.FilledFormsRepository
                              .AllAsNoTracking
                              .Where(s => s.ProjectId == projectId)
                              .OrderByDescending(s => s.DateCreated)
                              .ToList()
                              .Select(s => Mapper.Map <FilledFormDTO>(s))
                              .ToList();

                MemoryCacher.Add(cacheKey, surveys, DateTimeOffset.UtcNow.AddMinutes(1));

                return(Ok(surveys));
            }
            else
            {
                var result = (List <FilledFormDTO>)cacheEntry;
                return(new CachedResult <List <FilledFormDTO> >(result, TimeSpan.FromMinutes(1), this));
            }
        }
        public override async Task <bool> Run()
        {
            try
            {
                if (MemoryCacher.getDateTime() == null)
                {
                    MemoryCacher.setDateTime(this.NextRun);
                }

                MemoryCacher.setLive(true);

                await _footballHub.Clients.All.SendAsync("StartSimulation",
                                                         new
                {
                    eventType = "startSimulation"
                });

                const int numberOfTeams = 20;
                var       teamCodeList  = Enumerable.Range(1, numberOfTeams).ToList();

                var calendario     = _generadorCosas.generaLiga(teamCodeList);
                var calendarioLiga = _generadorPartidos.generaListaCalendarioVOsLiga(calendario);

                var comp1 = new CompeticionTotalCO(new CompeticionVO("LFP 1ªDivision 14-15", "2014-2015", _generadorCosas.generarFechaAleatoriaPartido(),
                                                                     _generadorCosas.generarFechaAleatoriaPartido(), "ninguno", "~/images/titulos/eurocopa.jpg", "Liga"),
                                                   calendarioLiga, teamCodeList);

                int numeroJornada = 1;

                var matchSet = calendario[0];

                var taskList = new List <Task>();

                for (int i = 1; i < numberOfTeams / 2; i++)
                {
                    var cont = i;
                    var part = matchSet[cont];

                    var task = createMatchTask(comp1, part, numeroJornada, cont);
                    taskList.Add(task);
                }

                Task.WaitAll(taskList.ToArray());
            }
            catch (Exception ex)
            {
                // We need to log this somewhere.
            }

            return(true);
        }
Beispiel #6
0
 public HttpResponseMessage SendToList_Routine([FromBody] NotificationModel value)
 {
     try
     {
         if (value.RecipientIDs == null || string.IsNullOrEmpty(value.Content) || value.Routine == null || value.Routine.Time == null)
         {
             return(Request.CreateResponse(HttpStatusCode.BadRequest));
         }
         IEnumerable <string> _sessionGuid;
         User _usr = new User();
         if (Request.Headers.TryGetValues("SessionGuid", out _sessionGuid))
         {
             string _sessID = _sessionGuid.First();
             if (MemoryCacher.GetValue(_sessID) == null)
             {
                 return(Request.CreateResponse(HttpStatusCode.Forbidden));
             }
             string _userID = MemoryCacher.GetValue(_sessID).ToString();
             _usr = bus_user.Get_ById(_userID);
         }
         else
         {
             return(Request.CreateResponse(HttpStatusCode.BadRequest));
         }
         string _webappid = value.AppIDs.Where(x => bus_AppInfo.Get_ById(x).Type == AppTypeConst.WEBAPP).FirstOrDefault();
         if (_webappid != null)
         {
             NotificationActivity _notif = bus_NotificationActivity.Create(new NotificationActivity
             {
                 Content      = value.Content,
                 UserID       = _usr.Id,
                 RecipientIDs = value.RecipientIDs,
                 AppIDs       = new List <string> {
                     _webappid
                 },
                 IsRoutine = true,
                 Routine   = value.Routine
             });
             return(Request.CreateResponse(HttpStatusCode.OK, new { NotifID = _notif.Id }));
         }
         else
         {
             return(Request.CreateResponse(HttpStatusCode.BadRequest));
         }
     }
     catch (Exception ex)
     {
         LogGenerationHelper.WriteToFile(ex.Message);
         return(Request.CreateResponse(HttpStatusCode.InternalServerError));
     }
 }
        public Dictionary <string, string> GetListOfOrganizations(string culture = Culture.NorwegianCode)
        {
            MemoryCacher memCacher = new MemoryCacher();

            var cache = memCacher.GetValue("organizations_" + culture);

            Dictionary <string, string> Organizations = new Dictionary <string, string>();

            if (cache != null)
            {
                Organizations = cache as Dictionary <string, string>;
            }

            if (Organizations.Count < 1)
            {
                System.Net.WebClient c = new System.Net.WebClient();
                c.Encoding = System.Text.Encoding.UTF8;
                var data     = c.DownloadString(System.Web.Configuration.WebConfigurationManager.AppSettings["RegistryUrl"] + "api/register/organisasjoner");
                var response = Newtonsoft.Json.Linq.JObject.Parse(data);

                var orgs = response["containeditems"];

                c.Headers.Remove("Accept-Language");
                c.Headers.Add("Accept-Language", Culture.EnglishCode);

                var dataEnglish     = c.DownloadString(System.Web.Configuration.WebConfigurationManager.AppSettings["RegistryUrl"] + "api/register/organisasjoner");
                var responseEnglish = Newtonsoft.Json.Linq.JObject.Parse(dataEnglish);

                var orgsEnglish = responseEnglish["containeditems"];

                for (int o = 0; o < orgs.Count(); o++)
                {
                    if (!Organizations.ContainsKey(orgs[o]["label"].ToString()))
                    {
                        if (culture == Culture.NorwegianCode)
                        {
                            Organizations.Add(orgs[o]["label"].ToString(), orgs[o]["label"].ToString());
                        }
                        else
                        {
                            Organizations.Add(orgs[o]["label"].ToString(), orgsEnglish[o]["label"].ToString());
                        }
                    }
                }

                Organizations = Organizations.OrderBy(o => o.Value).ToDictionary(o => o.Key, o => o.Value);
                memCacher.Set("organizations_" + culture, Organizations, new DateTimeOffset(DateTime.Now.AddYears(1)));
            }

            return(Organizations);
        }
        public void Init()
        {
            _cacheItemPolicyConverterMock = new Mock<ICacheItemPolicyConverter>();
            _cacheItemPolicyConverterMock
                .Setup(e => e.Convert(It.IsAny<CacheItemPolicy>()))
                .Returns((System.Runtime.Caching.CacheItemPolicy)null);

            _cacheItemPriorityMock = new Mock<ICacheItemPriorityConverter>();
            _cacheItemPriorityMock
                .Setup(e => e.Convert(It.IsAny<CacheItemPriority>()))
                .Returns(System.Web.Caching.CacheItemPriority.Default);

            _cacher = new MemoryCacher(_cacheItemPolicyConverterMock.Object, _cacheItemPriorityMock.Object);
        }
Beispiel #9
0
        public static void SaveToken(string token, string applicationId, int expirationTime)
        {
            var cache = new CacheObject
            {
                ApplicationId   = applicationId,
                RequestsTime    = new List <DateTimeOffset>(),
                IsExceededLimit = false
            };

            cache.RequestsTime.Add(DateTimeOffset.Now);

            //The session lifetime must be configurable in the database
            MemoryCacher.Add(token, cache, DateTimeOffset.UtcNow.AddMinutes(expirationTime));
        }
Beispiel #10
0
        public async Task <IEnumerable <Badge> > Get()
        {
            var badges = MemoryCacher.GetValue(Cache.Badges) as IEnumerable <Badge>;

            if (badges != null)
            {
                return(badges);
            }

            badges = await _databaseRepository.GetBadges();

            MemoryCacher.Add(Cache.Badges, badges);
            return(badges);
        }
        public void Init()
        {
            _cacheItemPolicyConverterMock = new Mock <ICacheItemPolicyConverter>();
            _cacheItemPolicyConverterMock
            .Setup(e => e.Convert(It.IsAny <CacheItemPolicy>()))
            .Returns((System.Runtime.Caching.CacheItemPolicy)null);

            _cacheItemPriorityMock = new Mock <ICacheItemPriorityConverter>();
            _cacheItemPriorityMock
            .Setup(e => e.Convert(It.IsAny <CacheItemPriority>()))
            .Returns(System.Web.Caching.CacheItemPriority.Default);

            _cacher = new MemoryCacher(_cacheItemPolicyConverterMock.Object, _cacheItemPriorityMock.Object);
        }
Beispiel #12
0
        public HttpResponseMessage ChangePassword([FromUri] int id, PasswordModel passwordModel)
        {
            var identity = (ClaimsIdentity)User.Identity;

            if (identity.Name != id.ToString())
            {
                return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Invalid Token"));
            }
            using (var db = new OnlineMusicEntities())
            {
                try
                {
                    var user = (from u in db.Users
                                where u.Id == id
                                select u).FirstOrDefault();

                    if (user == null)
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.NotFound, $"Tài khoản với id={id} không tồn tại"));
                    }
                    else
                    {
                        MemoryCacher cache         = new MemoryCacher();
                        string       cachePassword = cache.Get(user.Username) != null ? (string)cache.Get(user.Username) : String.Empty;
                        bool         isValid       = HashingPassword.ValidatePassword(passwordModel.OldPassword, user.Password);
                        if (!isValid)
                        {
                            // Try check cache password
                            isValid = !String.IsNullOrEmpty(cachePassword) && HashingPassword.ValidatePassword(passwordModel.OldPassword, cachePassword);
                        }

                        if (!isValid)
                        {
                            return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Mật khẩu cũ không đúng"));
                        }
                        else
                        {
                            user.Password = HashingPassword.HashPassword(passwordModel.NewPassword);
                            cache.Delete(user.Username);
                            db.SaveChanges();
                            return(Request.CreateResponse(HttpStatusCode.OK));
                        }
                    }
                }
                catch (Exception ex)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
                }
            }
        }
        public async Task <IHttpActionResult> Get(Guid?organisationId = null)
        {
            if (CurrentUser is OrgUser)
            {
                var isTeamManager = await ServiceContext.UserManager.IsInRoleAsync(CurrentOrgUser.Id, Role.ORG_TEAM_MANAGER);

                var cacheKey   = isTeamManager ? $"{CACHE_KEY}_MANAGER_{CurrentOrgUser.Id}" : $"{CACHE_KEY}_{CurrentOrgUser.OrganisationId}";
                var cacheEntry = MemoryCacher.GetValue(cacheKey);

                if (cacheEntry == null)
                {
                    if (isTeamManager)
                    {
                        var managerTeams = TeamService.GetManagerTeams(CurrentOrgUser.Id);
                        MemoryCacher.Add(cacheKey, managerTeams, DateTimeOffset.UtcNow.AddMinutes(1));

                        return(Ok(managerTeams));
                    }
                    else
                    {
                        var teams = TeamService.Get(CurrentOrgUser.OrganisationId);
                        MemoryCacher.Add(cacheKey, teams, DateTimeOffset.UtcNow.AddMinutes(1));

                        return(Ok(teams));
                    }
                }
                else
                {
                    var result = (List <OrganisationTeamDTO>)cacheEntry;
                    return(new CachedResult <List <OrganisationTeamDTO> >(result, TimeSpan.FromMinutes(1), this));
                }
            }

            // else if current user is SuperUser or PlatformUser
            var _cacheKey   = organisationId.HasValue ? $"{CACHE_KEY}_{organisationId}" : CACHE_KEY;
            var _cacheEntry = MemoryCacher.GetValue(_cacheKey);

            if (_cacheEntry == null)
            {
                var teams = organisationId.HasValue ? TeamService.Get(organisationId) : TeamService.Get();
                MemoryCacher.Add(_cacheKey, teams, DateTimeOffset.UtcNow.AddMinutes(1));

                return(Ok(teams));
            }
            else
            {
                var retVal = (List <OrganisationTeamDTO>)_cacheEntry;
                return(new CachedResult <List <OrganisationTeamDTO> >(retVal, TimeSpan.FromMinutes(1), this));
            }
        }
Beispiel #14
0
        public void LoadJson()
        {
            if ((MemoryCacher.GetValue("ProtechContext") == null))
            {
                using (StreamReader r = new StreamReader(HttpRuntime.AppDomainAppPath + "getResponse.json"))
                {
                    string             json = r.ReadToEnd();
                    var                func = JsonConvert.DeserializeObject <Funcionario>(json);
                    List <Funcionario> list = new List <Funcionario>();
                    list.Add(func);

                    MemoryCacher.Add("ProtechContext", list);
                }
            }
        }
Beispiel #15
0
        public async Task <Menu> GetMenu()
        {
            Menu menu;
            var  cacheMenu = MemoryCacher.GetValue(Cache.Menu) as Menu;

            if (cacheMenu != null)
            {
                menu = cacheMenu;
            }
            else
            {
                menu = await _databaseRepository.GetEnabledMenu();
            }
            return(menu);
        }
Beispiel #16
0
        public override void Run()
        {
            MemoryCacher<int, string> d = new MemoryCacher<int, string>(ARRAY_SIZE);
            __sw.Reset();
            __sw.Start();

            for (int i = 0; i < 1000000; i++)
            {
                d.Add(i, "abc");
            }

            __sw.Stop();

            Console.WriteLine("Loop Add MemoryCacher: {0}", __sw.ElapsedTicks);
        }
Beispiel #17
0
        public bool CachingValidToken(string cacheKey, GatewayToken authToken)
        {
            var cacheExpirationTime = ConfigurationManager.AppSettings["CacheExpirationTime"];

            var result = int.TryParse(cacheExpirationTime, out var timeInMinutes);

            if (!result)
            {
                timeInMinutes = 60;
            }

            MemoryCacher.Add(cacheKey, authToken, DateTimeOffset.UtcNow.AddMinutes(timeInMinutes));

            return(true);
        }
Beispiel #18
0
 public void TestBFSAlgorithm()
 {
     foreach (var mazeId in mazeIds)
     {
         maze = MemoryCacher.GetMazeFromCache(mazeId);
         Stack <int> stack = BreadthFirstSearchAlgorithm.BFSAlgorithm(maze, false, false);
         Assert.True(stack.Count() > 0);
         stack = BreadthFirstSearchAlgorithm.BFSAlgorithm(maze, true, false);
         Assert.True(stack.Count() > 0);
         stack = BreadthFirstSearchAlgorithm.BFSAlgorithm(maze, true, true);
         Assert.True(stack.Count() > 0);
         stack = BreadthFirstSearchAlgorithm.BFSAlgorithm(maze, false, true);
         Assert.True(stack.Count() > 0);
     }
 }
Beispiel #19
0
        private ListResult <PlateListItem> GetPromotional(int siteId)
        {
            ListResult <PlateListItem> data = null;

            if (base.IsUseCache)
            {
                data = MemoryCacher.GetValue("SITE-PROMOTIONAL") as ListResult <PlateListItem>;

                if (data != null)
                {
                    return(data);
                }
            }

            IList <PromotionalInfo> list = VShopHelper.GetAllPromotional(ClientType.App);

            List <PlateListItem> items = new List <PlateListItem>();

            if (list != null)
            {
                PlateListItem item = null;

                foreach (var current in list)
                {
                    item = new PlateListItem();

                    item.Id              = current.BannerId;
                    item.Title           = current.ShortDesc;
                    item.ImageUrl        = Util.AppendImageHost(current.ImageUrl);
                    item.NavigationType  = (int)current.LocationType;
                    item.Values          = current.Url;
                    item.DisplaySequence = current.DisplaySequence;

                    items.Add(item);
                }
            }

            data = new ListResult <PlateListItem>();
            data.TotalNumOfRecords = items.Count;;
            data.Results           = items;

            if (base.IsUseCache)
            {
                MemoryCacher.Add("SITE-PROMOTIONAL", data, DateTimeOffset.UtcNow.AddMinutes(SITE_CACHE_KEEP_TIME));
            }

            return(data);
        }
        public IHttpActionResult Redeem(string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                return(BadRequest("voucher code is empty"));
            }

            if (CurrentOrgUser.AccountType != AccountType.MobileAccount)
            {
                return(BadRequest("vouchers are only available to mobile users"));
            }

            var result = SubscriptionService.RedeemCode(code, CurrentOrgUser);

            switch (result)
            {
            case RedeemCodeStatus.AlreadyRedeemed:
                return(BadRequest("this code has already been redeemed"));

            case RedeemCodeStatus.SubscriptionDisabled:
                return(Content(HttpStatusCode.Forbidden, "subscriptions are disabled. contact your administrator."));

            case RedeemCodeStatus.SubscriptionRateNotSet:
                return(Content(HttpStatusCode.Forbidden, "subscription rate is not set. contact your administrator."));

            case RedeemCodeStatus.SubscriptionCountLessThanOne:
                return(Content(HttpStatusCode.Forbidden, "invalid subscription period. contact your administrator."));

            case RedeemCodeStatus.Error:
                return(BadRequest("an error has occured processing your code. try again or contact your administrator"));

            case RedeemCodeStatus.NotFound:
                return(NotFound());

            case RedeemCodeStatus.OK:
            {
                NotifyUserAboutVoucherSubscription();
                UnitOfWork.Save();

                MemoryCacher.DeleteStartingWith(CACHE_KEY);

                return(Ok());
            }

            default:
                return(NotFound());
            }
        }
        public IHttpActionResult Get()
        {
            if (CurrentUser is OrgUser)
            {
                var cacheKey   = $"{CACHE_KEY}_{CurrentOrgUser.OrganisationId}";
                var cacheEntry = MemoryCacher.GetValue(cacheKey);

                if (cacheEntry == null)
                {
                    var categories = UnitOfWork.FormTemplateCategoriesRepository
                                     .AllAsNoTracking
                                     .Where(c => c.OrganisationId == CurrentOrgUser.OrganisationId)
                                     .ToList()
                                     .Select(c => Mapper.Map <FormTemplateCategoryDTO>(c))
                                     .ToList();

                    MemoryCacher.Add(cacheKey, categories, DateTimeOffset.UtcNow.AddMinutes(1));

                    return(Ok(categories));
                }
                else
                {
                    var result = (List <FormTemplateCategoryDTO>)cacheEntry;
                    return(new CachedResult <List <FormTemplateCategoryDTO> >(result, TimeSpan.FromMinutes(1), this));
                }
            }

            // else if current user is SuperUser
            var _cacheEntry = MemoryCacher.GetValue(CACHE_KEY);

            if (_cacheEntry == null)
            {
                var _categories = UnitOfWork.FormTemplateCategoriesRepository
                                  .AllAsNoTracking
                                  .ToList()
                                  .Select(c => Mapper.Map <FormTemplateCategoryDTO>(c))
                                  .ToList();

                MemoryCacher.Add(CACHE_KEY, _categories, DateTimeOffset.UtcNow.AddMinutes(1));

                return(Ok(_categories));
            }
            else
            {
                var retVal = (List <FormTemplateCategoryDTO>)_cacheEntry;
                return(new CachedResult <List <FormTemplateCategoryDTO> >(retVal, TimeSpan.FromMinutes(1), this));
            }
        }
Beispiel #22
0
        public async Task <Menu> GetActiveMenu()
        {
            if (MemoryCacher.GetValue(Cache.Menu) is Menu cacheMenu)
            {
                return(cacheMenu);
            }

            var menu = await _databaseRepository.GetEnabledMenu();

            if (menu != null)
            {
                MemoryCacher.Add(Cache.Menu, menu);
            }

            return(menu);
        }
Beispiel #23
0
        public HttpResponseMessage Post([FromBody] UserModel value)
        {
            //Request.Headers.GetValues("SessionID");
            User _user = bus_user.Get_ByLogin(value.UserName, value.Password);

            if (_user != null)
            {
                string _sessionGuid = Guid.NewGuid().ToString();
                MemoryCacher.Add(_sessionGuid, _user.Id, DateTimeOffset.Now.AddHours(1));
                return(Request.CreateResponse(HttpStatusCode.OK, new { SessionGuid = _sessionGuid }));
            }
            else
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound));
            }
        }
Beispiel #24
0
        private ListResult <BannerListItem> GetBanner(int siteId)
        {
            ListResult <BannerListItem> data = null;

            if (base.IsUseCache)
            {
                data = MemoryCacher.GetValue("SITE-BANNER") as ListResult <BannerListItem>;

                if (data != null)
                {
                    return(data);
                }
            }

            IList <BannerInfo>    allBanners = VShopHelper.GetAllBanners(ClientType.App);
            List <BannerListItem> items      = new List <BannerListItem>();

            if (allBanners != null)
            {
                BannerListItem item = null;
                allBanners = allBanners.Where(m => m.LocationType != LocationType.Register).ToList();
                foreach (var current in allBanners)
                {
                    item = new BannerListItem();

                    item.Id              = current.BannerId;
                    item.Title           = current.ShortDesc;
                    item.ImageUrl        = Util.AppendImageHost(current.ImageUrl);
                    item.BannerType      = (int)current.LocationType;
                    item.Values          = current.Url;
                    item.DisplaySequence = current.DisplaySequence;

                    items.Add(item);
                }
            }

            data = new ListResult <BannerListItem>();
            data.TotalNumOfRecords = items.Count;
            data.Results           = items;

            if (base.IsUseCache)
            {
                MemoryCacher.Add("SITE-BANNER", data, DateTimeOffset.UtcNow.AddMinutes(SITE_CACHE_KEEP_TIME));
            }

            return(data);
        }
        // PUT api/orgTeams/{id}
        public IHttpActionResult Put(Guid id, [FromBody] OrganisationTeamDTO value)
        {
            if (id == Guid.Empty)
            {
                return(BadRequest("id is empty"));
            }

            var team = UnitOfWork.OrganisationTeamsRepository.Find(Guid.Parse(value.Id));

            if (team == null)
            {
                return(NotFound());
            }

            team.Name        = value.Name;
            team.Description = value.Description;
            team.Colour      = value.Colour;
            team.IsActive    = value.IsActive;

            if (CurrentUser is OrgUser)
            {
                team.Organisation = CurrentOrgUser.Organisation;
            }
            else
            {
                if (value.Organisation == null)
                {
                    return(BadRequest("organisation is required"));
                }

                team.OrganisationId = Guid.Parse(value.Organisation.Id);
            }

            try
            {
                UnitOfWork.OrganisationTeamsRepository.InsertOrUpdate(team);
                UnitOfWork.Save();

                MemoryCacher.DeleteStartingWith(CACHE_KEY);

                return(Ok());
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
        public Dictionary <string, string> GetCodeList(string systemid, string culture = Culture.NorwegianCode)
        {
            MemoryCacher memCacher = new MemoryCacher();

            var cache = memCacher.GetValue(systemid + "_" + culture);

            Dictionary <string, string> CodeValues = new Dictionary <string, string>();

            if (cache != null)
            {
                CodeValues = cache as Dictionary <string, string>;
            }

            if (CodeValues.Count < 1)
            {
                string url             = System.Web.Configuration.WebConfigurationManager.AppSettings["RegistryUrl"] + "api/kodelister/" + systemid;
                System.Net.WebClient c = new System.Net.WebClient();
                c.Encoding = System.Text.Encoding.UTF8;
                c.Headers.Remove("Accept-Language");
                c.Headers.Add("Accept-Language", culture);
                var data     = c.DownloadString(url);
                var response = Newtonsoft.Json.Linq.JObject.Parse(data);

                var codeList = response["containeditems"];

                foreach (var code in codeList)
                {
                    JToken codevalueToken = code["codevalue"];
                    string codevalue      = codevalueToken?.ToString();

                    if (string.IsNullOrWhiteSpace(codevalue))
                    {
                        codevalue = code["label"].ToString();
                    }

                    if (!CodeValues.ContainsKey(codevalue))
                    {
                        CodeValues.Add(codevalue, code["label"].ToString());
                    }
                }

                CodeValues = CodeValues.OrderBy(o => o.Value).ToDictionary(o => o.Key, o => o.Value);
                memCacher.Set(systemid + "_" + culture, CodeValues, new DateTimeOffset(DateTime.Now.AddYears(1)));
            }

            return(CodeValues);
        }
        public async Task <IHttpActionResult> PutIPAddressRange(int id, IPAddressRange iPAddressRange)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != iPAddressRange.Id)
            {
                return(BadRequest());
            }

            if (!iPAddressRange.ValidAddresses())
            {
                return(BadRequest());
            }
            WhitelistIP whitelistIP = new WhitelistIP()
            {
                Id       = iPAddressRange.Id,
                RuleName = iPAddressRange.RuleName,
                StartIP  = iPAddressRange.StartAddress.GetBytes(),
                EndIP    = iPAddressRange.EndAddress.GetBytes(),
                IsActive = iPAddressRange.IsActive
            };

            db.Entry(whitelistIP).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();

                MemoryCacher.UpdateOrDelete(iPAddressRange);
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!IPAddressRangeExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
 public IEnumerable <SchoolBo> Get(out int recodeCount, int skip = 0, int take = 0, string sortBy = "", bool isASC = false, string search = null)
 {
     try
     {
         var details = MemoryCacher.GetValue(CacheVariables.SchoolList.ToString());
         if (details != null)
         {
             recodeCount = 0;
             return((IEnumerable <SchoolBo>)details);
         }
         else
         {
             Expression <Func <School, bool> > filter = null;
             Func <IQueryable <School>, IOrderedQueryable <School> > orderBy = null;
             if (!string.IsNullOrWhiteSpace(search))
             {
                 filter = (e) => e.Name.ToLower().Trim().StartsWith(search.ToLower().Trim());
             }
             if (!string.IsNullOrWhiteSpace(sortBy))
             {
                 if (sortBy == "id")
                 {
                     orderBy = (e) => (isASC) ? e.OrderBy(p => p.Id) : e.OrderByDescending(p => p.Id);
                 }
                 else if (sortBy == "name")
                 {
                     orderBy = (e) => (isASC) ? e.OrderBy(p => p.Name) : e.OrderByDescending(p => p.Name);
                 }
                 else
                 {
                     throw new ArgumentException("invalied sorting type");
                 }
             }
             // query
             var res = uof.SchoolRepository.Get(filter, orderBy, "");
             // add to the cache
             var result = res.Select(x => Mapper.Map <SchoolBo>(x)).ToList();
             MemoryCacher.Add(CacheVariables.SchoolList.ToString(), result);
             recodeCount = uof.SchoolRepository.GetRecodeCount();
             return(result);
         }
     }
     catch (Exception e)
     {
         throw;
     }
 }
Beispiel #29
0
        // Here I would add a way to handle exceptions, for example like my other repo on GitHub,
        // to handle the exceptions that i would catch and throw in BLL
        // Also i would use some notification system on top, for showing some message to the user,
        // for example like tostr, bootstrap errors, or some custom implementation
        // GET api/<controller>/{keyword}
        public List <Trailer> Get(string keyword)
        {
            List <Trailer> trailers = new List <Trailer>();

            var result = MemoryCacher.GetValue(keyword);

            if (result == null)
            {
                // Search for the title in IMDB and then search for trailers in YouTube
                trailers = _searchBLL.Search(keyword);

                MemoryCacher.Add(keyword, trailers, DateTimeOffset.UtcNow.AddHours(24));
                return(trailers);
            }

            return((List <Trailer>)result);
        }
        public GameResponse CreateGame([FromUri] CreateGameRequest request)
        {
            Game newGame = new Game()
            {
                Phase   = new Phase(),
                Id      = Guid.NewGuid(),
                Name    = request.GameName,
                Players = new List <Player>()
                {
                    Database.GetPlayer(request.PlayerId)
                },
                Status = Status.WaitingRoom
            };

            MemoryCacher.Replace(newGame.Id.ToString(), newGame, DateTimeOffset.UtcNow.AddHours(1));
            return(new GameResponse(newGame));
        }
        // GET: pony-challenge/Maze/GUID
        public GameState MoveCharacters(Guid mazeId, MoveCharactersInMazeModel moveModel)
        {
            string direction = moveModel.Direction;

            try
            {
                if (mazeId != null && mazeId != Guid.Empty)
                {
                    Maze        maze         = MemoryCacher.GetMazeFromCache(mazeId);
                    CellState[] mazeCells    = maze.GetCells();
                    int         ponyLocation = maze.GetPonyId();
                    int         mazeWidth    = maze.GetMazeWidth();
                    int         mazeHeight   = maze.GetMazeHeight();

                    StateResult result = MazeHelper.MoveCharacter(maze, direction, CellState.Pony);
                    if (result == StateResult.MoveAccepted)
                    {
                        if (DifficultyManager.CheckIfCurrentDifficultyIsAdaptible(maze))
                        {
                            MemoryCacher.AppendDomokunNextMove(mazeId, direction);
                        }

                        string DomokunDirection = DifficultyManager.GetDomokunDirection(maze);
                        result = MazeHelper.MoveCharacter(maze, DomokunDirection, CellState.Domokun);
                    }
                    MemoryCacher.UpdateMazeInCache(mazeId, maze);

                    return(new GameState
                    {
                        State = State.Active,
                        StateResult = result
                    });
                }
                else
                {
                    HttpResponseException exception = CreateResponseException(HttpStatusCode.BadRequest, ERRORMESSAGE_MAZEID_INVALID);
                    throw exception;
                }
            }
            catch (Exception ex)
            {
                HttpResponseException exception = CreateResponseException(HttpStatusCode.InternalServerError, ex.Message);
                throw exception;
            }
        }
        public async Task <IHttpActionResult> Get(Guid?organisationId = null)
        {
            if (CurrentUser is OrgUser)
            {
                var isOrgAdmin = await ServiceContext.UserManager.IsInRoleAsync(CurrentOrgUser.Id, Role.ORG_ADMINSTRATOR);

                var _cacheKey = isOrgAdmin ?
                                $"{CACHE_KEY}_{ORG_ADMIN_KEY}_{CurrentOrgUser.OrganisationId}" :
                                $"{CACHE_KEY}_{CurrentOrgUser.OrganisationId}_{CurrentOrgUser.Id}";

                var _cacheEntry = MemoryCacher.GetValue(_cacheKey);
                if (_cacheEntry == null)
                {
                    var values = ProjectService.Get(CurrentOrgUser, organisationId: null);
                    MemoryCacher.Add(_cacheKey, values, DateTimeOffset.UtcNow.AddMinutes(1));

                    return(Ok(values));
                }
                else
                {
                    var values = (List <ProjectDTO>)_cacheEntry;
                    return(new CachedResult <List <ProjectDTO> >(values, TimeSpan.FromMinutes(1), this));
                }
            }

            // else if CurrentUser is SuperUser
            var cacheKey = organisationId.HasValue ?
                           $"{CACHE_KEY}_{ADMIN_KEY}_{organisationId.Value}" :
                           $"{CACHE_KEY}_{ADMIN_KEY}";

            var cacheEntry = MemoryCacher.GetValue(cacheKey);

            if (cacheEntry == null)
            {
                var values = ProjectService.Get(CurrentUser, organisationId);
                MemoryCacher.Add(cacheKey, values, DateTimeOffset.UtcNow.AddMinutes(1));

                return(Ok(values));
            }
            else
            {
                var values = (List <ProjectDTO>)cacheEntry;
                return(new CachedResult <List <ProjectDTO> >(values, TimeSpan.FromMinutes(1), this));
            }
        }
Beispiel #33
0
        public IHttpActionResult GetOnRecordStaffMembers()
        {
            var cacheKey   = "ONRECORD_STAFF";
            var cacheEntry = MemoryCacher.GetValue(cacheKey);

            if (cacheEntry == null)
            {
                var staffMembers = UserService.GetOnRecordStaff();
                MemoryCacher.Add(cacheKey, staffMembers, DateTimeOffset.UtcNow.AddMinutes(1));

                return(Ok(staffMembers));
            }
            else
            {
                var result = (List <OrgUserDTO>)cacheEntry;
                return(new CachedResult <List <OrgUserDTO> >(result, TimeSpan.FromMinutes(1), this));
            }
        }
Beispiel #34
0
        public override void Run()
        {
            MemoryCacher<int, string> d = new MemoryCacher<int, string>(ARRAY_SIZE);

            for (int i = 0; i < 1000000; i++)
            {
                d.Add(i, "abc");
            }

            string s = string.Empty;

            __sw.Reset();
            __sw.Start();

            Parallel.For(0, 1000000, i => d[i] = s);

            __sw.Stop();

            Console.WriteLine("Parallel Update MemoryCacher: {0}", __sw.ElapsedTicks);
        }
 public TweetController()
 {
     censor = new Censor(words.Split(new[] { ',' }));
     cache = new MemoryCacher();
     
 }
 public void SetUp()
 {
     _cacher = new MemoryCacher();
 }
        private void GivenPolicyWithSlidingExpirationOf(TimeSpan expiration)
        {
            var policy = new System.Runtime.Caching.CacheItemPolicy { SlidingExpiration = expiration };

            _cacheItemPolicyConverterMock = new Mock<ICacheItemPolicyConverter>();
            _cacheItemPolicyConverterMock
                .Setup(e => e.Convert(It.IsAny<CacheItemPolicy>()))
                .Returns(policy);

            _cacher = new MemoryCacher(_cacheItemPolicyConverterMock.Object, _cacheItemPriorityMock.Object);
        }