Exemple #1
0
    // ----------------------------------------------------------------
    // Turn handling
    // ----------------------------------------------------------------

    public void NextTurn()
    {
        if (actors.Count <= 1)
        {
            EndCombat();
        }
        if (combatRunning)
        {
            if (currentTurn >= actors.Count)
            {
                currentTurn = 0;
                actors.RemoveAll(item => CustomHelpers.IsNullOrDestroyed(item)); // GC for null objects
            }

            // Debug.Log("Actor Turn: " + actors[currentTurn] + " at turn num: " + currentTurn + " with total actors: " + actors.Count);

            if (!CustomHelpers.IsNullOrDestroyed(actors[currentTurn]))
            {
                actors[currentTurn].TakeTurn();
                currentTurn++;
            }
            else
            {
                currentTurn++;
                EventManager.RaiseActorTurnOver();
            }
        }
    }
        public HttpResponseMessage GetApikey(String Email, String password)
        {
            if (Email == null || password == null)
            {
                var response = Request.CreateResponse(HttpStatusCode.BadRequest);
                return(response);
            }
            else
            {
                bool check = new AccountController().registeredUser(Email, password);
                if (check == true)
                {
                    var  ApiKey = db.Users.FirstOrDefault(u => u.Email == Email).ApiKey;
                    User newobj = db.Users.FirstOrDefault(u => u.Email == Email);

                    if (ApiKey == null)
                    {
                        var newapikey = "";
                        newapikey     = CustomHelpers.GetApiKey();
                        newobj.ApiKey = newapikey;
                        db.SaveChanges();
                    }

                    var response = Request.CreateResponse(HttpStatusCode.OK, ApiKey);
                    return(response);
                }
                else
                {
                    var responses = Request.CreateResponse(HttpStatusCode.Forbidden);
                    return(responses);
                }
            }
        }
Exemple #3
0
        public void SetLevels(SortMode sortMode, string searchRequest)
        {
            BeatmapLevelSO[] levels = null;
            if (lastPlaylist != null)
            {
                levels = lastPlaylist.songs.Where(x => x.level != null).Select(x => x.level).ToArray();
            }
            else
            {
                levels = _levelCollection.beatmapLevels.Cast <BeatmapLevelSO>().ToArray();
            }

            if (string.IsNullOrEmpty(searchRequest))
            {
                switch (sortMode)
                {
                case SortMode.Newest: { levels = SortLevelsByCreationTime(levels); }; break;

                case SortMode.Difficulty:
                {
                    levels = levels.AsParallel().OrderBy(x => { int index = ScrappedData.Songs.FindIndex(y => x.levelID.StartsWith(y.Hash)); return(index == -1 ? (x.levelID.Length < 32 ? int.MaxValue : int.MaxValue - 1) : index); }).ToArray();
                }; break;
                }
            }
            else
            {
                levels = levels.Where(x => ($"{x.songName} {x.songSubName} {x.levelAuthorName} {x.songAuthorName}".ToLower().Contains(searchRequest))).ToArray();
            }

            _levelListViewController.SetData(CustomHelpers.GetLevelPackWithLevels(levels, lastPlaylist?.playlistTitle ?? "Custom Songs", lastPlaylist?.icon));
            PopDifficultyAndDetails();
        }
Exemple #4
0
        public void Pluralize_DependingOnDoubleNumber_CorrectPluralizedFormIsReturned(
            double number, string singularForm, string expectedForm)
        {
            var pluralizeForm = CustomHelpers.Pluralize(null, number, singularForm);

            Assert.AreEqual(expectedForm, pluralizeForm.ToString());
        }
        public IEnumerator MatchKey()
        {
            if (!string.IsNullOrEmpty(key) || level == null || !(level is CustomPreviewBeatmapLevel))
            {
                yield break;
            }

            string songHash = null;

            if (!string.IsNullOrEmpty(hash))
            {
                songHash = hash;
            }
            else if (!string.IsNullOrEmpty(levelId))
            {
                songHash = CustomHelpers.GetSongHash(level.levelID);
            }

            if (songHash != null && SongDataCore.Plugin.BeatSaver.Data.Songs.ContainsKey(hash))
            {
                var song = SongDataCore.Plugin.BeatSaver.Data.Songs[hash];
                key = song.key;
            }
            else
            {
                // no more hitting api just to match a key.  We know the song hash.
                //yield return SongDownloader.Instance.RequestSongByLevelIDCoroutine(level.levelID.Split('_')[2], (Song bsSong) => { if (bsSong != null) key = bsSong.key; });
            }
        }
Exemple #6
0
        //
        // GET: /Blog/

        public ActionResult Index(string slug = "")
        {
            // get the latest blog posts
            BlogViewModel BVM = new BlogViewModel();

            BVM.Blogs = context.Blogs.OrderByDescending(a => a.Date).Take(10).ToList();

            // check if there is any blog posts. if not, redirect to the home page
            if (BVM.Blogs.Count == 0)
            {
                return(RedirectToAction("Index", "Home"));
            }

            // get a specific blog post that matches the slug
            if (!String.IsNullOrEmpty(slug))
            {
                BVM.Blog = (from s in context.Blogs.AsEnumerable()
                            where CustomHelpers.CreateSlug(s.Headline) == slug
                            select s).SingleOrDefault();
            }

            // show the last blog post if the id isn't there, or if the requested id doesn't exist
            if (BVM.Blog == null)
            {
                // redirect to the most recent blog post
                return(RedirectToAction("Index", new { slug = CustomHelpers.CreateSlug(BVM.Blogs.FirstOrDefault().Headline) }));
            }

            // return the blog post
            return(View(BVM));
        }
Exemple #7
0
        public override void Execute()
        {
            #line 3 "..\..\Views\Shared\_Scripts.cshtml"

            var controller     = ViewContext.Controller;
            var controllerName = controller.GetControllerName();
            var area           = CustomHelpers.GetControllerArea(ViewContext.Controller.GetType());

            var jsFile = new List <string>
            {
                "~/Scripts/Controllers/" + controllerName + ".js",
                "~/Scripts/Controllers/" + controllerName + "/" + controllerName + ".js"
            };

            if (area.IsNotNullOrEmpty())
            {
                jsFile.Add($"~/Areas/{area}/Scripts/Controllers/{controllerName}.js");
                jsFile.Add(string.Format("~/Areas/{0}/Scripts/Controllers/{1}/{1}.js", area, controllerName));
            }


            #line default
            #line hidden
            WriteLiteral("\r\n\r\n");


            #line 21 "..\..\Views\Shared\_Scripts.cshtml"
            Write(Html.DynamicBundle(jsFile.ToArray()));


            #line default
            #line hidden
        }
Exemple #8
0
        public async Task <List <PS_PaySubGroup_Dto> > GetAllBySearchAsync(PS_PaySubGroup_Search_Dto data)
        {
            try
            {
                List <PS_PaySubGroup_Dto> result = await Task.Run(() => Repository
                                                                  .Include(x => x.PayGroup)
                                                                  .Include(x => x.LegalEntity)
                                                                  .Include(x => x.Frequency)
                                                                  .Include(x => x.PayrollPeriod)
                                                                  .ThenInclude(x => x.PayPeriods)
                                                                  .Include(x => x.AllowedBanks)
                                                                  .Select(MapToGetListOutputDto).ToList());

                for (int i = 0; i < result.Count; i++)
                {
                    if (!CustomHelpers.CheckIfMatches(result[i], data))
                    {
                        result.Remove(result[i]);
                    }
                }

                return(result);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Exemple #9
0
    protected override void SetAI()
    {
        Vector3 newDest = new Vector3();

        newDest.x          = myPosition.position.x + CustomHelpers.GetRandomValue(-2, 2);
        newDest.y          = myPosition.position.y + CustomHelpers.GetRandomValue(-2, 2);
        aIPath.destination = newDest;
    }
Exemple #10
0
        public ActionResult Edit(StoreItem storeItem, IEnumerable <HttpPostedFileBase> files)
        {
            if (ModelState.IsValid)
            {
                // allowed file extensions
                string[] fileExt = { ".png", ".jpg", ".gif", ".jpeg" };

                foreach (var fileBase in files)
                {
                    // save the background image
                    if (fileBase != null && fileBase.ContentLength > 0)
                    {
                        try
                        {
                            // make sure that the file extension is among the allowed
                            if (Array.IndexOf(fileExt, Path.GetExtension(fileBase.FileName.ToLower())) < 0)
                            {
                                throw new Exception(String.Format("File extension not allowed. Only these files are allowed:<br><br>{0}", string.Join(", ", fileExt)));
                            }

                            var fileName = Path.GetFileName(fileBase.FileName);

                            // fix bug that iPad/iPhone names all the files "image.jpg"
                            if (fileName == "image.jpg")
                            {
                                fileName = String.Format("{0}{1}", CustomHelpers.GeneratePassword(6), Path.GetExtension(fileBase.FileName.ToLower()));
                            }

                            var path = Server.MapPath("~/Images/Store/");

                            // instantiate object
                            var image = new CircuitBentCMS.Models.StoreItemImage();
                            image.ImageUrl    = fileName;
                            image.StoreItemId = storeItem.StoreItemId;

                            context.StoreItemImages.Add(image);

                            fileBase.SaveAs(Path.Combine(path, fileName));

                            ImageBuilder.Current.Build(Path.Combine(path, fileName), Path.Combine(path, "thumb_" + fileName), new ResizeSettings("maxwidth=240&maxheight=240&crop=auto"));
                        }
                        catch (Exception e)
                        {
                            TempData["ErrorMessage"] = e.Message;
                        }
                    }
                }

                context.Entry(storeItem).State = EntityState.Modified;
                context.SaveChanges();

                // display a friendly success message
                TempData["StatusMessage"] = "The changes were saved successfully!";

                return(RedirectToAction("Edit", new { id = storeItem.StoreItemId }));
            }
            return(View(storeItem));
        }
Exemple #11
0
 protected override void Patrol()
 {
     if (aIPath.reachedEndOfPath)
     {
         Vector3 newDest = new Vector3();
         newDest.x          = myPosition.position.x + CustomHelpers.GetRandomValue(-2, 2);
         newDest.y          = myPosition.position.y + CustomHelpers.GetRandomValue(-2, 2);
         aIPath.destination = newDest;
     }
 }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var area = CustomHelpers.GetControllerArea(filterContext.Controller);

            if (!string.IsNullOrEmpty(area))
            {
                filterContext.Controller.ViewBag.Area = area;
            }

            base.OnActionExecuting(filterContext);
        }
Exemple #13
0
        public NewFlowerpotPageViewModel(INavigationService navigationService,
                                         IPageDialogService pageDialogService,
                                         IFlowerpotRepository flowerpotRepository)
            : base(navigationService)
        {
            this.navigationService   = navigationService;
            this.pageDialogService   = pageDialogService;
            this.flowerpotRepository = flowerpotRepository;

            CloseModalCommand = new Command(async() => await CloseModalAsync());
            SaveCommand       = new Command(async() => await SaveCommandAsync());
            DaysOfTheWeek     = new List <string>(CustomHelpers.GetWeekdays(DayOfWeek.Monday));
        }
        public static string DynamicAction(
            this UrlHelper url,
            string action,
            Type controller,
            object routeValues = null,
            bool absoluteUrl   = false)
        {
            var route          = CustomHelpers.AddAreaRouteValue(controller, routeValues);
            var controllerName = controller.GetControllerName();

            return(absoluteUrl
                ? url.AbsoluteAction(action, controllerName, route)
                : url.Action(action, controllerName, route));
        }
Exemple #15
0
        public ActionResult Details(string slug)
        {
            var storeItem = (from s in context.StoreItems.AsEnumerable()
                             where CustomHelpers.CreateSlug(s.Title) == slug
                             select s).FirstOrDefault();

            if (storeItem == null)
            {
                TempData["ErrorMessage"] = "Item not found.";

                return(RedirectToAction("Index"));
            }

            return(View(storeItem));
        }
        /// <summary>
        /// Add Song to Editing Playlist
        /// </summary>
        /// <param name="songInfo"></param>
        public void AddSongToEditingPlaylist(IBeatmapLevel songInfo)
        {
            if (this.CurrentEditingPlaylist == null)
            {
                return;
            }

            this.CurrentEditingPlaylist.songs.Add(new PlaylistSong()
            {
                songName = songInfo.songName,
                levelId  = songInfo.levelID,
                hash     = CustomHelpers.GetSongHash(songInfo.levelID),
            });

            this.CurrentEditingPlaylistLevelIds.Add(songInfo.levelID);
            this.CurrentEditingPlaylist.SavePlaylist();
        }
Exemple #17
0
        public static string RecentBlogs(string input, IEnumerable <Blog> blogs)
        {
            string insertCode = "<div class='blog-recent'>";

            foreach (var item in blogs)
            {
                insertCode += String.Format("<a href='/blog/{0}'>{1} <span class='blog-date'>({2}/{3})</span></a><br />",
                                            CustomHelpers.CreateSlug(item.Headline), item.Headline, item.Date.Day, item.Date.Month);
            }

            insertCode += "</div>";

            // insert the code
            input = input.Replace("[widget=recentblogs]", insertCode);

            return(input);
        }
Exemple #18
0
    private void Awake()
    {
        if (GameObject.FindGameObjectsWithTag("MainCamera").Length > 1)
        {
            // Destroy any extra cameras.
            Destroy(transform.parent.gameObject);
        }

        CustomHelpers.CheckForInitializedFields(this);

        // DontDestroyOnLoad(gameObject);
        xOffset = thisCamera.orthographicSize * Screen.width / Screen.height;
        yOffset = thisCamera.orthographicSize;

        xMin = minBoundaryX.bounds.min.x + xOffset;
        xMax = maxBoundaryX.bounds.max.x - xOffset;
        yMin = minBoundaryY.bounds.min.y + yOffset;
        yMax = maxBoundaryY.bounds.max.y - yOffset;
    }
        public ActionResult AddTicketUsers(TicketUserViewModel ticketUser)
        {
            var applicationUserId        = User.Identity.GetUserId();
            var developerRole            = DbContext.Roles.FirstOrDefault(r => r.Name == "Developer").Id;
            var unassignedDeveloperUsers = DbContext.Users;
            var user = DbContext.Users.Where(u => u.Roles.Any(p => p.RoleId == developerRole))
                       .FirstOrDefault(p => p.Id == ticketUser.UserID);

            var ticket = DbContext.Tickets.FirstOrDefault(
                p => p.ID == ticketUser.ID);

            if (user == null)
            {
                return(RedirectToAction(nameof(ManageProjectUsersController.EditProjectUsers)));
            }

            var historyWriter = new CustomHelpers();

            historyWriter.MakeTicketHistories(ticket, user, applicationUserId);
            var message = new IdentityMessage
            {
                Destination = $"{user.Email}",
                Subject     = $"You've been assigned to a new a new ticket: {ticket.Title}",
                Body        = $"new ticket--- {ticket.Title}: {ticket.Description}"
            };
            var emailService = new EmailService();

            emailService.SendAsync(message);

            ticket.AssignedToUserID = user.Id;

            var ticketNotification = new TicketNotification
            {
                UserID   = user.Id,
                TicketID = ticket.ID
            };

            DbContext.TicketNotifications.Add(ticketNotification);

            DbContext.SaveChanges();
            return(RedirectToAction("EditTicketUsers", "ManageTicketUsers", new { id = ticketUser.ID }));
        }
        /// <summary>
        /// Filter songs based on ranked or unranked status.
        /// </summary>
        /// <param name="levels"></param>
        /// <param name="includeRanked"></param>
        /// <param name="includeUnranked"></param>
        /// <returns></returns>
        private List <IPreviewBeatmapLevel> FilterRanked(List <IPreviewBeatmapLevel> levels, bool includeRanked, bool includeUnranked)
        {
            return(levels.Where(x =>
            {
                var hash = CustomHelpers.GetSongHash(x.levelID);
                double maxPP = 0.0;
                if (SongDataCore.Plugin.ScoreSaber.Data.Songs.ContainsKey(hash))
                {
                    maxPP = SongDataCore.Plugin.ScoreSaber.Data.Songs[hash].diffs.Max(y => y.pp);
                }

                if (maxPP > 0f)
                {
                    return includeRanked;
                }
                else
                {
                    return includeUnranked;
                }
            }).ToList());
        }
Exemple #21
0
        private void DeletePressed()
        {
            IBeatmapLevel level = _detailViewController.selectedDifficultyBeatmap.level;

            _simpleDialog.Init("Delete song", $"Do you really want to delete \"{ level.songName} {level.songSubName}\"?", "Delete", "Cancel",
                               (selectedButton) =>
            {
                freePlayFlowCoordinator.InvokePrivateMethod("DismissViewController", new object[] { _simpleDialog, null, false });
                if (selectedButton == 0)
                {
                    try
                    {
                        var levelsTableView = _levelListViewController.GetPrivateField <LevelPackLevelsTableView>("_levelPackLevelsTableView");

                        List <IPreviewBeatmapLevel> levels = levelsTableView.GetPrivateField <IBeatmapLevelPack>("_pack").beatmapLevelCollection.beatmapLevels.ToList();
                        int selectedIndex = levels.FindIndex(x => x.levelID == _detailViewController.selectedDifficultyBeatmap.level.levelID);

                        SongDownloader.Instance.DeleteSong(new Song(SongLoader.CustomLevels.First(x => x.levelID == _detailViewController.selectedDifficultyBeatmap.level.levelID)));

                        if (selectedIndex > -1)
                        {
                            int removedLevels = levels.RemoveAll(x => x.levelID == _detailViewController.selectedDifficultyBeatmap.level.levelID);
                            Logger.Log("Removed " + removedLevels + " level(s) from song list!");

                            _levelListViewController.SetData(CustomHelpers.GetLevelPackWithLevels(levels.Cast <BeatmapLevelSO>().ToArray(), lastPlaylist?.playlistTitle ?? "Custom Songs", lastPlaylist?.icon));
                            TableView listTableView = levelsTableView.GetPrivateField <TableView>("_tableView");
                            listTableView.ScrollToCellWithIdx(selectedIndex, TableView.ScrollPositionType.Beginning, false);
                            levelsTableView.SetPrivateField("_selectedRow", selectedIndex);
                            listTableView.SelectCellWithIdx(selectedIndex, true);
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Error("Unable to delete song! Exception: " + e);
                    }
                }
            });
            freePlayFlowCoordinator.InvokePrivateMethod("PresentViewController", new object[] { _simpleDialog, null, false });
        }
        public ActionResult RemoveTicketUsers(TicketUserViewModel ticketUser)
        {
            var applicationUserId = User.Identity.GetUserId();
            var user = DbContext.Users.FirstOrDefault(
                p => p.Id == ticketUser.UserID);

            var ticket = DbContext.Tickets.FirstOrDefault(
                p => p.ID == ticketUser.ID);

            if (user == null)
            {
                return(RedirectToAction(nameof(ManageProjectUsersController.EditProjectUsers)));
            }

            var historyWriter = new CustomHelpers();

            historyWriter.MakeTicketHistories(ticket, applicationUserId);

            ticket.AssignedToUserID = null;

            DbContext.SaveChanges();
            return(RedirectToAction("EditTicketUsers", "ManageTicketUsers", new { id = ticketUser.ID }));
        }
        public async Task <List <PS_PaymentBankFile_Dto> > GetAllBySearchAsync(PS_PaymentBankFile_Dto data)
        {
            try
            {
                List <PS_PaymentBankFile_Dto> result = await Task.Run(() => Repository
                                                                      .Include(x => x.PaymentBanks)
                                                                      .Select(MapToGetListOutputDto).ToList());

                for (int i = 0; i < result.Count; i++)
                {
                    if (!CustomHelpers.CheckIfMatches(result[i], data))
                    {
                        result.Remove(result[i]);
                    }
                }

                return(result);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
        /// <summary>
        /// Sorting by star rating.
        /// </summary>
        /// <param name="levels"></param>
        /// <returns></returns>
        private List <IPreviewBeatmapLevel> SortStars(List <IPreviewBeatmapLevel> levels)
        {
            Logger.Info("Sorting song list by star points...");

            if (!SongDataCore.Plugin.ScoreSaber.IsDataAvailable())
            {
                return(levels);
            }

            return(levels
                   .OrderByDescending(x =>
            {
                var hash = CustomHelpers.GetSongHash(x.levelID);
                var stars = 0.0;
                if (SongDataCore.Plugin.ScoreSaber.Data.Songs.ContainsKey(hash))
                {
                    var diffs = SongDataCore.Plugin.ScoreSaber.Data.Songs[hash].diffs;
                    stars = diffs.Max(y => y.star);
                }

                //Logger.Debug("Stars={0}", stars);
                if (stars != 0)
                {
                    return stars;
                }

                if (_settings.invertSortResults)
                {
                    return double.MaxValue;
                }
                else
                {
                    return double.MinValue;
                }
            })
                   .ToList());
        }
        /// <summary>
        /// Sorting by PP.
        /// </summary>
        /// <param name="levels"></param>
        /// <returns></returns>
        private List <IPreviewBeatmapLevel> SortPerformancePoints(List <IPreviewBeatmapLevel> levels)
        {
            Logger.Info("Sorting song list by performance points...");

            if (!SongDataCore.Plugin.ScoreSaber.IsDataAvailable())
            {
                return(levels);
            }

            return(levels
                   .OrderByDescending(x =>
            {
                var hash = CustomHelpers.GetSongHash(x.levelID);
                if (SongDataCore.Plugin.ScoreSaber.Data.Songs.ContainsKey(hash))
                {
                    return SongDataCore.Plugin.ScoreSaber.Data.Songs[hash].diffs.Max(y => y.pp);
                }
                else
                {
                    return 0;
                }
            })
                   .ToList());
        }
        /// <summary>
        /// Sorting by BeatSaver heat stat.
        /// </summary>
        /// <param name="levelIds"></param>
        /// <returns></returns>
        private List <IPreviewBeatmapLevel> SortBeatSaverHeat(List <IPreviewBeatmapLevel> levelIds)
        {
            Logger.Info("Sorting song list by BeatSaver Heat!");

            // Do not always have data when trying to sort by heat
            if (!SongDataCore.Plugin.BeatSaver.IsDataAvailable())
            {
                return(levelIds);
            }

            return(levelIds
                   .OrderByDescending(x => {
                var hash = CustomHelpers.GetSongHash(x.levelID);
                if (SongDataCore.Plugin.BeatSaver.Data.Songs.ContainsKey(hash))
                {
                    return SongDataCore.Plugin.BeatSaver.Data.Songs[hash].stats.heat;
                }
                else
                {
                    return int.MinValue;
                }
            })
                   .ToList());
        }
Exemple #27
0
        public static MvcHtmlString ExportLinks(this HtmlHelper helper)
        {
            var stringBuilder = new StringBuilder();

            foreach (var type in ExportConfiguration.ExportTypes)
            {
                if (!Enum.TryParse(type, true, out ExportFactory.ExportType exportType))
                {
                    continue;
                }

                var html = string.Format(
                    "<a class='option {3} export-js' title='{0}' href='#' data-controller='{1}' data-action='Export' data-area='{2}' data-type='{0}'>" +
                    "<svg class='icon currentColor1'><use xlink:href='#dl'></use></svg>{0}</a>" +
                    "</a>",
                    type.ToUpper(),
                    helper.ViewContext.Controller.GetControllerName(),
                    CustomHelpers.GetControllerArea(helper.ViewContext.Controller),
                    ExportFactory.GetCssStyleByType(exportType));
                stringBuilder.Append(html);
            }

            return(new MvcHtmlString(stringBuilder.ToString()));
        }
Exemple #28
0
        protected override void Seed(GameManager.DAL.GameManagerContext context)
        {
            var users = new List <User> {
                new User {
                    Email = "*****@*****.**", Password = Crypto.HashPassword("password"), ApiKey = CustomHelpers.GetApiKey(), Role = Roles.StoreAdmin
                },
            };

            users.ForEach(u => context.Users.AddOrUpdate(u));
        }
Exemple #29
0
        public ActionResult Create(Page page, HttpPostedFileBase socialImage)
        {
            if (ModelState.IsValid)
            {
                page.LastUpdated = DateTime.Now;

                // perfor some basic verification that it is an int
                int subPageId = Convert.ToInt32(page.SubPageToPageId);

                // set the order by counting the current pages
                // also need to check if it's a main page or a sub page
                if (subPageId == 0)
                {
                    // update the order for the remaining pages
                    // this is because the order is not correct otherwise
                    var pages = context.Pages.Where(a => a.SubPageToPageId == 0).OrderBy(a => a.Order).ToList();
                    for (int i = 0; i < pages.Count; i++)
                    {
                        pages[i].Order = i + 1;
                    }

                    context.SaveChanges();

                    page.Order = context.Pages.Where(a => a.SubPageToPageId == 0).ToList().Count + 1;
                }
                else
                {
                    // update the order for the remaining pages
                    // this is because the order is not correct otherwise
                    var pages = context.Pages.Where(a => a.SubPageToPageId == subPageId).OrderBy(a => a.Order).ToList();
                    for (int i = 0; i < pages.Count; i++)
                    {
                        pages[i].Order = i + 1;
                    }

                    context.SaveChanges();

                    page.Order = context.Pages.Where(a => a.SubPageToPageId == subPageId).ToList().Count + 1;
                }

                // allowed file extensions
                string[] fileExt = { ".png", ".jpg", ".gif", ".jpeg" };

                // save the social media image
                if (socialImage != null && socialImage.ContentLength > 0)
                {
                    try
                    {
                        // make sure that the file extension is among the allowed
                        if (Array.IndexOf(fileExt, Path.GetExtension(socialImage.FileName.ToLower())) < 0)
                        {
                            throw new Exception("Social media image was in an unsupported format. Only images (JPEG, GIF, PNG) allowed.");
                        }

                        var path = Path.Combine(Server.MapPath("~/Images/PageImages"), CustomHelpers.RemoveSwedishChars(socialImage.FileName));
                        page.SocialMediaImage = CustomHelpers.RemoveSwedishChars(socialImage.FileName);
                        socialImage.SaveAs(path);
                    }
                    catch (Exception e)
                    {
                        TempData["ErrorMessage"] = e.Message;
                    }
                }

                context.Pages.Add(page);
                context.SaveChanges();

                // display a friendly success message
                TempData["StatusMessage"] = "Page created successfully!";

                // if the user added a special page, redirect back to index
                // this is because there isn't really much to continue editing except the title
                if (!String.IsNullOrEmpty(page.CustomPage))
                {
                    return(RedirectToAction("Index"));
                }

                // the user added a blank page, therefore we redirect back to the edit page
                return(RedirectToAction("Edit", new { id = page.PageId }));
            }

            return(View(page));
        }
Exemple #30
0
        public ActionResult Edit(Page page, HttpPostedFileBase socialImage)
        {
            var path = Server.MapPath("~/Images/PageImages");

            if (ModelState.IsValid)
            {
                page.LastUpdated = DateTime.Now;

                // allowed file extensions
                string[] fileExt = { ".png", ".jpg", ".gif", ".jpeg" };

                // save the social media image
                if (socialImage != null && socialImage.ContentLength > 0)
                {
                    try
                    {
                        // make sure that the file extension is among the allowed
                        if (Array.IndexOf(fileExt, Path.GetExtension(socialImage.FileName.ToLower())) < 0)
                        {
                            throw new Exception("Social media image was in an unsupported format. Only images (JPEG, GIF, PNG) allowed.");
                        }

                        // delete the current image
                        if (!String.IsNullOrEmpty(page.SocialMediaImage))
                        {
                            if (System.IO.File.Exists(Path.Combine(path, page.SocialMediaImage)))
                            {
                                System.IO.File.Delete(Path.Combine(path, page.SocialMediaImage));
                            }
                        }


                        page.SocialMediaImage = CustomHelpers.RemoveSwedishChars(socialImage.FileName);
                        socialImage.SaveAs(Path.Combine(Server.MapPath("~/Images/PageImages"), CustomHelpers.RemoveSwedishChars(socialImage.FileName)));
                    }
                    catch (Exception e)
                    {
                        TempData["ErrorMessage"] = e.Message;
                    }
                }

                // update the page
                context.Entry(page).State = EntityState.Modified;
                context.SaveChanges();

                // display a friendly success message
                TempData["StatusMessage"] = "The changes were saved successfully!";

                // if the user added a special page, redirect back to index
                // this is because there isn't really much to continue editing except the title
                if (!String.IsNullOrEmpty(page.CustomPage))
                {
                    return(RedirectToAction("Index"));
                }

                // redirect to the same edit page in case the user wants to make more changes
                if (!String.IsNullOrEmpty(Request.QueryString["scripts"]))
                {
                    return(RedirectToAction("Edit", new { id = page.PageId, scripts = "true" }));
                }

                return(RedirectToAction("Edit", new { id = page.PageId }));
            }


            // ModelState not valid
            return(View(page));
        }