Ejemplo n.º 1
0
        public IActionResult ResponseCache()
        {
            CacheViewModel cacheViewModel = new CacheViewModel();

            cacheViewModel.Response = _paises;
            return(View(cacheViewModel));
        }
Ejemplo n.º 2
0
        // GET: Cache
        public ActionResult Index()
        {
            try
            {
                var viewModel = new CacheViewModel();

                return(View(viewModel));
            }
            catch (Exception ex)
            {
                string additionalErrorMessage = ex.Message;

                additionalErrorMessage += " Ensure Redis Server is Running on localhost: ";
                try
                {
                    additionalErrorMessage += " " + ConfigurationManager.AppSettings["RedisConnectionString"];
                    additionalErrorMessage += " " + ConfigurationManager.AppSettings["ReddisServerName"];
                }
                catch
                {
                    additionalErrorMessage +=
                        "Configuration Settings RedisConnectionString, ReddisServerName Not Found";
                }

                throw new Exception(additionalErrorMessage);
            }
        }
Ejemplo n.º 3
0
        // GET: Cache
        public ActionResult Index()
        {
            var viewModel = new CacheViewModel();

            viewModel.ShallowAthleteCount = 0; // _Cache.GetShallowAthletes("DUMMY").Count;
            return(View(viewModel));
        }
        public IActionResult Index()
        {
            CacheViewModel cacheViewModel = new CacheViewModel();

            cacheViewModel.InMemory = _memoryCache.GetOrCreate("paises", entry => {
                entry.SlidingExpiration = TimeSpan.FromSeconds(5);
                entry.Priority          = CacheItemPriority.High;
                return(_paises);
            });

            var paisesDC = _distributedCache.Get("paises");

            if (paisesDC == null)
            {
                _distributedCache.Set("paises",
                                      Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(_paises)),
                                      new DistributedCacheEntryOptions
                {
                    SlidingExpiration = TimeSpan.FromSeconds(4)
                }
                                      );

                cacheViewModel.Distributed = _paises;
            }
            else
            {
                cacheViewModel.Distributed = JsonConvert.DeserializeObject <List <string> >(Encoding.UTF8.GetString(_distributedCache.Get("paises")));
            }

            cacheViewModel.Response = _paises;
            return(View(cacheViewModel));
        }
Ejemplo n.º 5
0
 public static void SetupSimulation(SimulationParameters simulationParameters)
 {
     SimulationParameters = simulationParameters;
     SetMemory();
     _SetIndexCount();
     CacheViewModel = new CacheViewModel(IndexCount);
 }
Ejemplo n.º 6
0
        public bool SetUserPermissionsAndCode(string uniqueName, string code)
        {
            try
            {
                var userPermissions = (from u in _context.Users
                                       join up in _context.UsersPermissions on u.UniqueName equals up.UniqueName
                                       join r in _context.Resources on up.ResourceID equals r.ResourceID
                                       join m in _context.Modules on r.ModuleID equals m.ModuleID
                                       where up.UniqueName == uniqueName && r.ResourceSequence > 0
                                       orderby r.CategorySequence, r.ResourceSequence
                                       select new PermissionsToBeCachedViewModel
                {
                    Endpoint = m.Endpoint,
                    Module = m.ModuleName,
                    Resource = r.ResourceName,
                    Category = r.Category,
                    DisplayName = r.DisplayName
                }).ToList();

                var propertiesToCache = new CacheViewModel(code, userPermissions);
                _cache.Set(uniqueName, Util.GetBytes(propertiesToCache.ToString()));

                return(true);
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 7
0
        CacheViewModel GetUserPermissionsCached(string uniqueName)
        {
            CacheViewModel cachedView = null;

            byte[] arraySerializedCached = null;

            if (uniqueName == null)
            {
                throw new ArgumentNullException("GetUserPermissionsCached(uniqueName: null)");
            }

            //try
            //{
            //    arraySerializedCached = _cache.Get(uniqueName);
            //}
            //catch(StackExchange.Redis.RedisConnectionException)
            //{
            //    // Ignore transient network issues
            //}

            if (arraySerializedCached != null)
            {
                var propertiesSerializedCached = Util.GetString(arraySerializedCached);
                cachedView = new CacheViewModel(propertiesSerializedCached);
            }

            return(cachedView);
        }
Ejemplo n.º 8
0
        internal IHttpHandler Cache()
        {
            var cache = new HttpCacheShim();
            var model = new CacheViewModel(cache)
            {
                Success = true
            };

            return(base.Json(model));
        }
Ejemplo n.º 9
0
        public static void SetupSimulation(SimulationParameters simulationParameters)
        {
            SimulationParameters = simulationParameters;
            SetMemory();
            _SetIndexCount();
            CacheViewModel = new CacheViewModel(IndexCount);

            CacheLineFrequencies    = new List <Int32>(new Int32[IndexCount]);
            CacheLineLastUsageTimes = new List <Int32>(new Int32[IndexCount]);
            Fifo = new List <Int32>();
        }
Ejemplo n.º 10
0
        public ActionResult Index()
        {
            CacheViewModel viewModel = new CacheViewModel()
            {
                IsCacheEnabled = ApplicationSettings.UseObjectCache,
                PageKeys       = _pageViewModelCache.GetAllKeys(),
                ListKeys       = _listCache.GetAllKeys(),
                SiteKeys       = _siteCache.GetAllKeys()
            };

            return(View(viewModel));
        }
Ejemplo n.º 11
0
        public HttpResponseMessage AddEntityToCache(string EntityName)
        {
            try
            {
                var viewModel = new CacheViewModel();

                return(viewModel.AddEntityToCache(EntityName));
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Ejemplo n.º 12
0
        public HttpResponseMessage Delete(string key)
        {
            try
            {
                var viewModel = new CacheViewModel();

                return(viewModel.DeleteFromCache(key));
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Ejemplo n.º 13
0
        public HttpResponseMessage DeleteAllKeys()
        {
            try
            {
                var viewModel = new CacheViewModel();

                return(viewModel.DeleteAllFromCache());
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Ejemplo n.º 14
0
        public APIResultModel SetCache([FromBody] CacheViewModel cache)
        {
            ICacheBusiness cacheBusiness = CacheFactory.Instance("redis");

            var cacheResult = cacheBusiness.SetValue(cache.Key, cache.Value.ToString());

            APIResultModel result = new APIResultModel()
            {
                Success = cacheResult.Success,
                Message = cacheResult.Message
            };

            return(result);
        }
Ejemplo n.º 15
0
        public string GetUserMenuSerialized(string uniqueName)
        {
            var    menu = new List <Tuple <string, Tuple <string, string, string> > >();
            string propertiesSerializedCached;

            try
            {
                propertiesSerializedCached = Util.GetString(_cache.Get(uniqueName));
            }
            catch (Exception)
            {
                SetUserPermissionsAndCode(uniqueName, string.Empty);
                propertiesSerializedCached = Util.GetString(_cache.Get(uniqueName));
            }

            try
            {
                var permissions = new CacheViewModel(propertiesSerializedCached).Permissions;

                foreach (var p in permissions)
                {
                    if (!p.Endpoint.Contains("/api"))
                    {
                        string category   = p.Category;
                        string display    = p.DisplayName;
                        string controller = p.Module;
                        string action     = p.Resource;
                        //string url = p.Endpoint + "/" + p.Module + "/" + p.Resource;

                        menu.Add(Tuple.Create(category, Tuple.Create(display, controller, action)));
                    }
                }

                var menuGrouped = (from m in menu
                                   group m.Item2 by m.Item1 into g
                                   select new
                {
                    Category = g.Key,
                    Items = g.ToList()
                }).ToList();


                return(JsonConvert.SerializeObject(menuGrouped));
            }
            catch (Exception)
            {
                return(string.Empty);
            }
        }
Ejemplo n.º 16
0
        public ActionResult PopulateAthletesPerRace()
        {
            InitializeStorage();

            var raceIds = _DbContext.Races.Select(r => r.RaceId);

            foreach (var raceId in raceIds)
            {
                AddQueueMessage(raceId);
            }

            var viewModel = new CacheViewModel();

            viewModel.ShallowAthleteCount = 0;

            return(View("Index", viewModel));
        }
Ejemplo n.º 17
0
        // GET: SiteTools
        public ActionResult Cache()
        {
            var model = new CacheViewModel();

            if (Request.HttpMethod == "POST")
            {
                if (!string.IsNullOrEmpty(Request.Form["btnFlushCache"]))
                {
                    //flush the entire cache
                    CacheHandler.Invalidate(null);
                    model.Message = "Cache flushed.";
                }
            }

            model.CacheItems      = CacheHandler.ListForSiteTools();
            model.CacheMemoryFree = string.Format("Physical memory available for caching: {0}% ({1} MB)", HttpRuntime.Cache.EffectivePercentagePhysicalMemoryLimit.ToString(), (HttpRuntime.Cache.EffectivePrivateBytesLimit / 1024) / 1024);

            return(View(model));
        }
Ejemplo n.º 18
0
        public void index_should_return_viewmodel_with_filled_properties()
        {
            // Arrange
            _applicationSettings.UseObjectCache = true;
            _pageCache.Add(1, new PageViewModel());
            _listCache.Add <string>("test", new List <string>());
            _siteCache.AddMenu("menu");

            // Act
            ViewResult result = _cacheController.Index() as ViewResult;

            // Assert
            Assert.That(result, Is.Not.Null, "ViewResult");

            CacheViewModel model = result.ModelFromActionResult <CacheViewModel>();

            Assert.NotNull(model, "Null model");
            Assert.That(model.IsCacheEnabled, Is.True);
            Assert.That(model.PageKeys.Count(), Is.EqualTo(1));
            Assert.That(model.ListKeys.Count(), Is.EqualTo(1));
            Assert.That(model.SiteKeys.Count(), Is.EqualTo(1));
        }
Ejemplo n.º 19
0
        public bool VerifyIfUserAdmin(string uniqueName)
        {
            try
            {
                var propertiesSerializedCached = Util.GetString(_cache.Get(uniqueName));
                var permissions = new CacheViewModel(propertiesSerializedCached).Permissions;

                var permToReview = permissions.First(p => p.Module == "Users" && p.Resource == "Review");
                if (permToReview != null)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception)
            {
                return(false);
            }
        }
Ejemplo n.º 20
0
        public bool VerifyUserAccessToResource(string uniqueName, string module, string resource)
        {
            try
            {
                var propertiesSerializedCached = Util.GetString(_cache.Get(uniqueName));
                if (propertiesSerializedCached != null)
                {
                    var permissions = new CacheViewModel(propertiesSerializedCached).Permissions;

                    var perm = (from p in permissions
                                where p.Resource.ToLower().Equals(resource) && p.Module.ToLower().Equals(module)
                                select p).First();

                    if (perm != null)
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                if (ex.Message == "Sequence contains no elements")
                {
                    return(false);
                }
                else
                {
                    throw;
                }
            }
        }
Ejemplo n.º 21
0
        //TODO [ValidateAntiForgeryToken]
        public ActionResult Cache()
        {
            var model = new CacheViewModel();

            if (Request.HttpMethod == "POST")
            {
                if (!string.IsNullOrEmpty(Request.Form["btnFlushCache"]))
                {
                    //flush the entire cache
                    CacheManagement.CacheHandler.Invalidate(null);
                    model.Message = AppGlobal.Language.GetText(this, "CacheFlushed", "Cache Flushed");
                }
                else if (!string.IsNullOrEmpty(Request.Form["btnReloadLanguages"]))
                {
                    //flush cache of all languages
                    AppGlobal.Language.ReloadLanguage(0);
                    model.Message = AppGlobal.Language.GetText(this, "LanguagesFlushed", "Languages Flushed");
                }
                else if (!string.IsNullOrEmpty(Request.Form["btnReloadConfiguration"]))
                {
                    //flush cache of all configuration settings
                    Constants.ConfigSettings.Refresh();
                    model.Message = AppGlobal.Language.GetText(this, "ConfigurationReloaded",
                                                               "Configuration settings reloaded");
                }
            }

            model.CacheItems = CacheManagement.CacheHandler.ListForSiteTools();
            var memAvailable = AppGlobal.Language.GetText(this, "CacheMemoryAvailable",
                                                          "Physical memory available for caching: {0}% ({1} MB)");

            model.CacheMemoryFree = string.Format(memAvailable,
                                                  HttpRuntime.Cache.EffectivePercentagePhysicalMemoryLimit.ToString(),
                                                  (HttpRuntime.Cache.EffectivePrivateBytesLimit / 1024) / 1024);

            return(View(model));
        }
Ejemplo n.º 22
0
        public ActionResult BuyTickets(FormCollection data)
        {
            var kidsRetirees = int.Parse(data["kidsRetirees"]);
            var students     = int.Parse(data["students"]);
            var adults       = int.Parse(data["adults"]);
            var projectionID = int.Parse(data["projectionID"]);
            var seats        = data["seats"].Split(',').Select(int.Parse).ToArray();

            List <decimal> ticketTypesPrices = new List <decimal>();
            var            ticketsBought     = new Dictionary <Ticket, int[]>();

            if (kidsRetirees != 0)
            {
                for (int i = 1; i <= kidsRetirees; i++)
                {
                    ticketTypesPrices.Add(TicketPrices.kidsRetirees);
                }
            }

            if (students != 0)
            {
                for (int i = 1; i <= students; i++)
                {
                    ticketTypesPrices.Add(TicketPrices.students);
                }
            }

            if (adults != 0)
            {
                for (int i = 1; i <= adults; i++)
                {
                    ticketTypesPrices.Add(TicketPrices.adults);
                }
            }


            using (var context = new CinemaTicketsDbContext())
            {
                try
                {
                    var tickets       = context.Projections.FirstOrDefault(p => p.ProjectionID == projectionID).Tickets.ToList();
                    var counter       = 0;
                    var usernameEmail = (string)Session["usernameEmail"];
                    foreach (var ticket in tickets)
                    {
                        foreach (var seat in seats)
                        {
                            if (ticket.SeatID == seat)
                            {
                                var userSoldCurrentTicket = context.Employees.FirstOrDefault(e => e.Email == usernameEmail);
                                var currentSeat           = ticket.Seat;
                                ticket.IsSold   = true;
                                ticket.Price    = ticketTypesPrices[counter];
                                ticket.Employee = userSoldCurrentTicket;
                                counter++;
                                ticketsBought[ticket] = new int[] { currentSeat.Row, currentSeat.Column };
                            }
                        }
                    }
                    context.SaveChanges();
                }
                catch (OptimisticConcurrencyException ex)
                {
                }
            }
            CacheViewModel.CacheModel(ticketsBought);
            return(new HttpStatusCodeResult(200, "OK"));
        }
        public ActionResult RedirectProjectionData(FormCollection data)
        {
            try
            {
                var kidsRetirees   = int.Parse(data["kidsRetirees"]);
                var students       = int.Parse(data["students"]);
                var adults         = int.Parse(data["adults"]);
                var projectionID   = int.Parse(data["projectionID"]);
                var totalPrice     = decimal.Parse(data["totalPrice"]);
                var projectionTime = data["projectionTime"].Split(' ');
                Session["ticketDate"] = projectionTime[0];
                Session["ticketHour"] = projectionTime[1] + projectionTime[2];

                var seatDtos = new List <SeatDTO>();
                using (var context = new CinemaTicketsDbContext())
                {
                    var projection = context.Projections.FirstOrDefault(p => p.ProjectionID == projectionID);
                    var hallNumber = context.Halls.FirstOrDefault(h => h.HallID == projection.HallID).HallNumber;
                    Session["hallNumber"] = hallNumber;
                    var tickets = projection.Tickets.ToList();

                    foreach (var ticket in tickets)
                    {
                        var seatDto = new SeatDTO
                        {
                            Column = ticket.Seat.Column,
                            Row    = ticket.Seat.Row,
                            HallID = ticket.Seat.HallID,
                            SeatID = ticket.Seat.SeatID
                        };

                        if (ticket.IsSold)
                        {
                            seatDto.IsTaken = true;
                        }
                        else
                        {
                            seatDto.IsTaken = false;
                        }
                        seatDtos.Add(seatDto);
                    }
                }

                var model = new SeatViewModel()
                {
                    Adults       = adults,
                    KidsRetirees = kidsRetirees,
                    SeatDtos     = seatDtos,
                    Students     = students,
                    TotalPrice   = totalPrice,
                    ProjectionID = projectionID
                };
                CacheViewModel.CacheModel(model);
            }

            catch (Exception e)
            {
                return(new HttpStatusCodeResult(400, "Something went wrong! :("));
            }

            return(new HttpStatusCodeResult(200, "OK"));
        }
Ejemplo n.º 24
0
        public string GetUserMenuSerialized(string uniqueName)
        {
            var    menu = new List <Tuple <string, Tuple <string, string, string> > >();
            string propertiesSerializedCached = null;

            byte[] arraySerializedCached = null;

            //try
            //{
            //    arraySerializedCached = _cache.Get(uniqueName);
            //}
            //catch (StackExchange.Redis.RedisConnectionException)
            //{
            //    // Ignore transient network failures
            //}


            if (arraySerializedCached != null)
            {
                propertiesSerializedCached = Util.GetString(arraySerializedCached);
            }
            else
            {
                var cachedView = GetUserPermissionsAndCode(uniqueName, string.Empty);
                propertiesSerializedCached = cachedView.ToString();
            }

            //try
            //{
            //    _cache.Set(uniqueName, Util.GetBytes(propertiesSerializedCached));
            //}
            //catch (StackExchange.Redis.RedisConnectionException)
            //{
            //    // Ignore transient network failures
            //}

            //try
            //{
            //    propertiesSerializedCached = Util.GetString(_cache.Get(uniqueName));
            //}
            //catch (Exception)
            //{
            //    SetUserPermissionsAndCode(uniqueName, string.Empty);
            //    propertiesSerializedCached = Util.GetString(_cache.Get(uniqueName));
            //}

            var permissions = new CacheViewModel(propertiesSerializedCached).Permissions;

            foreach (var p in permissions)
            {
                if (!p.Endpoint.Contains("/api"))
                {
                    string category   = p.Category;
                    string display    = p.DisplayName;
                    string controller = p.Module;
                    string action     = p.Resource;
                    //string url = p.Endpoint + "/" + p.Module + "/" + p.Resource;

                    menu.Add(Tuple.Create(category, Tuple.Create(display, controller, action)));
                }
            }

            var menuGrouped = (from m in menu
                               group m.Item2 by m.Item1 into g
                               select new
            {
                Category = g.Key,
                Items = g.ToList()
            }).ToList();


            return(JsonConvert.SerializeObject(menuGrouped));
        }
Ejemplo n.º 25
0
        //Updates permissions on database and cache
        public bool UpdateUserPermissions(string uniqueName, PermissionsViewModel newUserPermissions)
        {
            //Delete old permissions from the database:
            var oldPermissions = _context.UsersPermissions.Where(up => up.UniqueName == uniqueName);

            _context.UsersPermissions.RemoveRange(oldPermissions);
            //_context.SaveChanges();

            //Update the database
            //Permissions:
            foreach (var permissionToQuery in newUserPermissions.permissions)
            {
                var resourceReturned = _context.Resources.First(r => r.Category == permissionToQuery.category && r.DisplayName == permissionToQuery.resource);

                _context.UsersPermissions.Add(new UsersPermission()
                {
                    UniqueName = uniqueName,
                    ResourceID = resourceReturned.ResourceID
                });
            }
            //User:
            var user = _context.Users.First(u => u.UniqueName == uniqueName);

            if (newUserPermissions.permissions.Count > 0)
            {
                user.Status = PermissionStatus.Permissions_Granted;
            }
            else
            {
                user.Status = PermissionStatus.Permissions_Denied;
            }

            _context.SaveChanges();

            //Update the cache
            CacheViewModel propertiesToCache = new CacheViewModel();

            byte[] arrPropertiesSerializedCached = null;

            try
            {
                // may raise exception
                //arrPropertiesSerializedCached = _cache.Get(uniqueName);

                // if data is not cached
                if (arrPropertiesSerializedCached != null)
                {
                    string propertiesSerializedCached = Util.GetString(arrPropertiesSerializedCached);
                    propertiesToCache = new CacheViewModel(propertiesSerializedCached);
                }
            }
            catch (StackExchange.Redis.RedisConnectionException)
            {
                // Ignore transient network errors
            }

            var userPermissions = (from up in _context.UsersPermissions
                                   join r in _context.Resources on up.ResourceID equals r.ResourceID
                                   join m in _context.Modules on r.ModuleID equals m.ModuleID
                                   where up.UniqueName == uniqueName && r.ResourceSequence > 0
                                   orderby r.CategorySequence, r.ResourceSequence
                                   select new PermissionsToBeCachedViewModel
            {
                Endpoint = m.Endpoint,
                Module = m.ModuleName,
                Resource = r.ResourceName,
                Category = r.Category,
                DisplayName = r.DisplayName
            }).ToList();

            if (userPermissions != null)
            {
                propertiesToCache.Permissions = userPermissions;
                //_cache.Set(uniqueName, Util.GetBytes(propertiesToCache.ToString()));
                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 26
0
 private void OnConnected()
 {
     Content = new CacheViewModel(_cacheClient, OnDisconnected);
 }