Blog

Posts written in July 2018.

  • Published on
    -
    4 min read

    ASP.NET Core MVC Numbered Pagination

    This is a relatively simple pagination that will only be shown if there are enough items of data to paginate through. The user will have the ability to paginate by either clicking on the "Previous" and "Next" links as well as clicking on the individual page numbers from within the pagination.

    I created a PaginationHelper.CreatePagination() method that carries out all the paging calculations and outputs the pagination as an unordered list. The method requires the following parameters:

    • currentPage - the current page number being viewed.
    • totalNumberOfRecords - the total count of records from your dataset in order to determine how many pages should be displayed.
    • pageRequest - the current request from by passing in "HttpContext.Request" to get the page URL.
    • noOfPageLinks - the number of page numbers that should be shown. For example "1, 2, 3, 4".
    • pageSize - the number of items will be shown per page.
    using Microsoft.AspNetCore.Http;
    using System;
    using System.Text;
    
    namespace MyProject.Helpers
    {
        public static class PaginationHelper
        {
            /// <summary>
            /// Renders pagination used in listing pages.
            /// </summary>
            /// <param name="currentPage"></param>
            /// <param name="totalNumberOfRecords"></param>
            /// <param name="pageRequest">Current page request used to get the URL path of the page.</param>
            /// <param name="noOfPagesLinks">Number of pagination numbers to show.</param>
            /// <param name="pageSize"></param>
            /// <returns></returns>
            public static string CreatePagination(int currentPage, int totalNumberOfRecords, HttpRequest pageRequest, int noOfPagesLinks = 5, int pageSize = 10)
            {
                StringBuilder paginationHtml = new StringBuilder();
    
                // Only render the pagination markup if the total number of records is more than our page size.
                if (totalNumberOfRecords > pageSize)
                {
                    #region Pagination Calculations
    
                    int amountOfPages = (int)(Math.Ceiling(totalNumberOfRecords / Convert.ToDecimal(pageSize)));
    
                    int startPage = currentPage;
    
                    if (startPage == 1 || startPage == 2 || amountOfPages < noOfPagesLinks)
                        startPage = 1;
                    else
                        startPage -= 2;
    
                    int maxPage = startPage + noOfPagesLinks;
    
                    if (amountOfPages < maxPage)
                        maxPage = Convert.ToInt32(amountOfPages) + 1;
    
                    if (maxPage - startPage != noOfPagesLinks && maxPage > noOfPagesLinks)
                        startPage = maxPage - noOfPagesLinks;
    
                    int previousPage = currentPage - 1;
                    if (previousPage < 1)
                        previousPage = 1;
    
                    int nextPage = currentPage + 1;
    
                    #endregion
    
                    #region Get Current Path
    
                    // Get current path.
                    string path = pageRequest.Path.ToString();
    
                    int pos = path.LastIndexOf("/") + 1;
    
                    // Get last route value.
                    string lastRouteValue = path.Substring(pos, path.Length - pos).ToLower();
    
                    // Removes page number from end of path if path contains a page number.
                    if (lastRouteValue.StartsWith("page"))
                        path = path.Substring(0, path.LastIndexOf('/'));
    
                    #endregion
    
                    paginationHtml.Append("<ul>");
    
                    if (currentPage > 1)
                        paginationHtml.Append($"<li><a href=\"{path}/Page{previousPage}\"><span>Previous page</span></a></li>");
    
                    for (int i = startPage; i < maxPage; i++)
                    {
                        // If the current page equals one of the pagination numbers, set active state.
                        if (i == currentPage)
                            paginationHtml.Append($"<li><a href=\"{path}/Page{i}\" class=\"is-active\"><span>{i}</span></a></li>");
                        else
                            paginationHtml.Append($"<li><a href=\"{path}/Page{i}\"><span>{i}</span></a></li>");
                    }
    
                    if (startPage + noOfPagesLinks < amountOfPages && maxPage > noOfPagesLinks || currentPage < amountOfPages)
                        paginationHtml.Append($"<li><a href=\"{path}/Page{nextPage}\"><span>Next page</span></a></li>");
    
                    paginationHtml.Append("</ul>");
    
                    return paginationHtml.ToString();
                }
                else
                {
                    return string.Empty;
                }
            }
        }
    }
    

    The PaginationHelper.CreatePagination() method can then be used inside a controller where you would like to list your data as well as render the pagination. A simple example of this would be as follows:

    /// <summary>
    /// List all news articles.
    /// </summary>
    /// <param name="page"></param> 
    /// <param name="pageSize"></param>
    /// <returns></returns>
    [Route("/Articles")]
    [Route("/Articles/Page{page}")]
    public ActionResult Index(int page = 1, int pageSize = 10)
    {
        // Number of articles to skip.
        int skip = 0;
        if (page != 1)
            skip = (page - 1) * pageSize;
    
        // Get list of articles from my datasource.
        List<NewsArticle> articles = MyData.GetArticles().Skip(skip).Take(pageSize).ToList();
    
        //Render Pagination.
        ViewBag.PaginationHtml = PaginationHelper.CreatePagination(page, articles.Count, HttpContext.Request, pageSize: pageSize);
    
        return View(articles);
    }
    

    The pagination will be output to a ViewBag that can be called from within your view. I could have gone down a different route and developed Partial View along with the appropriate model. But for my use the method approach offers most flexibility, as I could have the option to either use this from within a controller or view.

  • Published on
    -
    2 min read

    Recovering A Hard Disk Full of Memories - Part 1

    Memories are what give life purpose. They allow us to go back to the past, into a time that shall forever be stateless. Most importantly memories are experiences that mould us into the person we are today.

    For some reason, when I think about the word memories the first thing that come to mind are pictures... Photos to be exact. I only started thinking how important photos are to me whilst I was having a conversation with my cousin Tajesh. Tajesh popped over this weekend gone by and like always has many fascinating stories to tell. One story in particular got my attention. He told me about an amazing trip he had in Australia many many years ago and how he lost all the photos he had taken after recently damaging his hard drive. On hearing his predicament, I was profoundly moved and imagined how I'd feel if I was in his position.

    Even though our brains are wired to remember events and experiences, memories seem to somehow fade away over time and we start forgetting the little detail of images until it forms into a hazy recall. We remember enough to transport us back to a time or a place, but the brain has a strange way of patching together what we once saw. As if they are pieces of a larger puzzle. If your brain is anything like mine where you can only selectively retrieve one piece of the puzzle that is most meaningful, we're missing a vast array of information.

    I decided I'd make an attempt to try and recover my cousins lost photos. He handed over his Western Digital Caviar edition hard drive carefully enclosed in an old VHS box, entrusting I'll have it's best interests at heart and keeping whatever memories that maybe locked away safe inside... A damaged hard drive is in some ways like our brains selective recall. The data is stored somewhere but we sometimes have problems accessing them.

    I'm no hard disk recovery expert and I am hoping some off the shelf software will help me in getting at least some photos back from his holiday. So what's the game plan?

    I'll start with using a piece of software I blogged about back in 2011 - EaseUs. EaseUs provides a line of software ranging from backup to recovery. It helped me then and (fingers crossed) it'll help me now. I'll also need a 3.5 inch disk caddy to allow the hard drive to be connected via USB and start the recovery process.

    As it stands, my cousins Western Digital Caviar disk doesn't seem to have any visible damage and there are no noises when run. It just doesn't boot.

    Stay tuned for future posts on how I get on.

    To be continued...

  • Published on
    -
    4 min read

    My Time At Melia Bali Hotel

    Family. Family is what comes to mind when I think of my time at Melia Bali. I only happen to come to this conclusion as I checked out on the calm and (strangely) cool evening before having to depart back to the UK.

    I don't generally write about my travels (or lack of!). But my time at Melia has energised me to write something and as a result, I scribble away madly trying to make sense of processing my erratic thoughts and feelings during my long flight back. Just so I can write this post.

    Melia Bali Coconut On The Beach

    I find it ironic I started writing this post about "family", when I happened to visit Bali with people to whom I deem most dear: mum, dad and sister. I feel that family forms centre place to the services they provide.

    If you happen to have the privilege of staying at the Melia Bali Hotel for long enough, you'd get a sense of familiarity of the people working there. To some extent I hope I am perhaps familiar to them - The Indian guy with the ridiculously frizzy hair (a result of the climate ;-) ).

    These people truly are the back bone of the hotel and make it what it is. Yes, Melia is a pretty place on the surface but it's the people that make it truly shine when compared to the other hotels staggered along the beach shoreline. They are without a doubt amazing at what they do. From the lady who cooks me the most delicious fluffy omelette in the morning down to the lobby personnel who are willing to help with any query or concern.

    From the moment I wake up and make my way to the breakfast hall to the moment I enter the lobby at the end of a long day gallivanting, I am greeted with many smiles. You can't help but be infected with a sense of positivity and happiness, something I don't think I've ever come across when holidaying elsewhere.

    The lobby statues and wondrous ceiling mural makes for a welcome sight at any time, setting the ambience and standard for the hotel. If you're lucky to be at the lobby during the evening, you'd be greeted by two classically trained balinese dancers dressed from an era of time gone by. As they dance with delicate intricacy to the tune of the rindik, I am reminded of similarities when compared to classical Indian dances - a lost art and cultural heritage slowly eroding with time, making for a visceral experience and something you can't help but appreciate.

    Melia Bali Dancers

    Melia offers around five restaurants to cater for the guests varying palettes - each with their own theme and cuisines. We found ourselves venturing outside to nearby restaurants as after a few nights as we found the prices a little dear based on the portion sizes of the main meals. Even though the food was very tasty, my western belly expected something more sizeable. When taking into consideration the 21% combined tax and service charge on top of the prices on the menu - not so cheap. There are many fine eateries at the Bali Collection for consideration, just a 5-10 minute walk away.

    When there are issues, it is family that are there to support at time of need. We happened to experience some very loud noises from the room above us at an unsightly hour. Spoiling the serenity we become accustomed to. Now this went on for a couple nights. We just happened to make a remark of our problem in passing to one of the workers whilst feasting on the morning breakfast buffet and within a a short period of time this was communicated to the customer service representative who apologised and organised a room change swiftly.

    The rooms themselves are all very well maintained, clean and provided nice views from the balcony. Based on our room change, you can expect subtle differences in terms of the what the rooms offer. For example, our first room just had a shower, but the second room had a shower/bath. My only quibble is the shower head position - not a deal breaker. There are generous bathroom amenities, consisting of toothbrush, toothpaste, vanity kit, shampoo, conditioner, shower gel, shaving kit and body lotion. All fully restocked daily. The crazy thing is that you get a new toothbrush every day! As much as I like a new toothbrush, I sometimes have to question the environmental impact.

    Melia Bali - View from Lobby

    Even though our noisy neighbour was no fault of thier own, Melia took us under their wing to ensure our holiday was perfect. We were even given a fruit platter for our troubles. I think what struck a chord with me is before we departed, is that the management seem to know everything about a guests stay to a granular level. The hotel manager hoped we'd comeback again to visit even with the minor inconvenience we experienced.

    If I do get another opportunity to visit again, I will consider paying a little extra for "The Level" experience. I have to admit, I was quite envious of all the things I heard about this upgrade when talking to other guests on the beach. I felt like a pauper. I like the idea of having a little more privacy in terms of accomodation and your own space on the beach. More importantly it's adults only. No noisy kids! :-)

    Melia Bali - Entrance At Night

    I look back at my time at Melia Bali with fond memories that will be permanently etched into my memory. For me, Melia compliments Bali as the wondrous land of Bali compliments Melia.