public ActionResult Index(int? page)
        {
            int currentPage = Math.Max(page ?? 1, 1);

            SetHeader("Users");
            SelectMenuItem("Users");

            ViewData["PageNumbers"] = new PageNumber("/users?page=-1", Convert.ToInt32(Math.Ceiling(Current.DB.Users.Count() / 35m)), 50,
                                                     currentPage - 1, "pager fr");

            PagedList<User> data = Current.DB.Users.OrderBy(u => u.Login).ToPagedList(currentPage, 35);
            return View(data);
        }
        public ActionResult Index(string sitename, string order_by, string q, int? page, int? pagesize)
        {
            Site = GetSite(sitename);

            if (Site == null)
            {
                return PageNotFound();
            }

            QuerySearchCriteria searchCriteria = new QuerySearchCriteria(q);

            if (string.IsNullOrEmpty(order_by))
            {
                if (searchCriteria.IsValid)
                    order_by = searchCriteria.IsFeatured ? "featured" : "recent";
                else
                    order_by = "featured";
            }

            ViewData["Site"] = Site;
            SelectMenuItem("Queries");
            SetHeader(
                "All Queries",
                new SubHeaderViewData
                {
                    Description = "featured",
                    Title = "Interesting queries selected by the administrators",
                    Href = "/" + sitename + "/queries?order_by=featured",
                    Selected = (order_by == "featured")
                },
                new SubHeaderViewData
                {
                    Description = "recent",
                    Title = "Recently saved queries",
                    Href = "/" + sitename + "/queries?order_by=recent",
                    Selected = (order_by == "recent")
                },
                new SubHeaderViewData
                {
                    Description = "favorite",
                    Title = "Favorite saved queries",
                    Href = "/" + sitename + "/queries?order_by=favorite",
                    Selected = (order_by == "favorite")
                },
                new SubHeaderViewData
                {
                    Description = "popular",
                    Title = "Saved queries with the most views",
                    Href = "/" + sitename + "/queries?order_by=popular",
                    Selected = (order_by == "popular")
                },
                new SubHeaderViewData
                {
                    Description = "everything",
                    Title = "All queries recently executed on the site",
                    Href = "/" + sitename + "/queries?order_by=everything",
                    Selected = (order_by == "everything")
                }
            );

            pagesize = Math.Max(Math.Min(pagesize ?? 50, 100), 10);
            page = Math.Max(page ?? 1, 1);

            int start = ((page.Value - 1) * pagesize.Value) + 1;
            int finish = page.Value * pagesize.Value;
            bool useLatest = true;
            var builder = new SqlBuilder();
            SqlBuilder.Template pager = null, counter = null;

            if (order_by != "everything")
            {
                pager = builder.AddTemplate(@"
                    SELECT
                        *
                    FROM
                        (
                            SELECT
                                /**select**/, ROW_NUMBER() OVER(/**orderby**/) AS RowNumber
                            FROM
                                Metadata metadata
                                /**join**/
                                /**leftjoin**/
                                /**where**/
                        ) AS results
                    WHERE
                        RowNumber BETWEEN @start AND @finish
                    ORDER BY
                        RowNumber",
                    new { start = start, finish = finish }
                );
                counter = builder.AddTemplate("SELECT COUNT(*) FROM Metadata metadata /**join**/ /**leftjoin**/ /**where**/");

                builder.Select("metadata.RevisionId AS Id");
                builder.Select("metadata.LastActivity AS LastRun");
                builder.Join("Queries query ON query.Id = metadata.LastQueryId");
                builder.LeftJoin("Users [user] ON metadata.OwnerId = [user].Id");
                builder.Where("metadata.Hidden = 0");

                if (order_by == "featured" || order_by == "recent")
                {
                    if (order_by == "featured")
                    {
                        builder.Where("metadata.Featured = 1");
                        builder.Where("metadata.First = 1");
                        builder.OrderBy("metadata.Votes DESC");
                    }

                    builder.OrderBy("metadata.LastActivity DESC");
                }
                else
                {
                    int threshold = 0;

                    if (order_by == "popular")
                    {
                        builder.Where("metadata.Views > @threshold", new { threshold = threshold });
                        builder.OrderBy("metadata.Views DESC");
                        builder.OrderBy("metadata.Votes DESC");
                    }
                    else
                    {
                        builder.Where("metadata.Votes > @threshold", new { threshold = threshold });
                        builder.OrderBy("metadata.Votes DESC");
                        builder.OrderBy("metadata.Views DESC");
                    }
                }
            }
            else if (order_by == "everything")
            {
                pager = builder.AddTemplate(@"
                    SELECT
                        /**select**/
                    FROM
                        (
                            SELECT
                                Revisions.*, ROW_NUMBER() OVER(/**orderby**/) AS RowNumber
                            FROM
                                Revisions
                        ) AS revision
                    /**join**/
                    /**leftjoin**/
                    /**where**/
                    WHERE
                        RowNumber BETWEEN @start AND @finish
                    ORDER BY
                        RowNumber",
                    new { start = start, finish = finish }
                );
                counter = builder.AddTemplate("SELECT COUNT(*) FROM Revisions");

                builder.Select("revision.Id AS Id");
                builder.Select("revision.CreationDate AS LastRun");
                builder.Join(@"
                    Metadata metadata ON
                    (
                        metadata.RevisionId = revision.RootId AND
                        metadata.OwnerId = revision.OwnerId
                    ) OR (
                        metadata.RevisionId = revision.Id AND
                        metadata.OwnerId = revision.OwnerId AND
                        revision.RootId IS NULL
                    ) OR (
                        metadata.RevisionId = revision.Id AND
                        metadata.OwnerId IS NULL AND
                        revision.OwnerId IS NULL
                    )"
                );
                builder.Join("Queries query on query.Id = revision.QueryId");
                builder.LeftJoin("Users [user] ON revision.OwnerId = [user].Id");
                builder.OrderBy("CreationDate DESC");

                useLatest = false;
            }

            builder.Select("[user].Id as CreatorId");
            builder.Select("[user].Login as CreatorLogin");
            builder.Select("metadata.Title AS Name");
            builder.Select("metadata.[Description] AS [Description]");
            builder.Select("metadata.Votes AS FavoriteCount");
            builder.Select("metadata.Views AS Views");
            builder.Select("query.QueryBody AS [SQL]");

            if (searchCriteria.IsValid)
            {
                builder.Where("metadata.Title LIKE @search OR metadata.[Description] LIKE @search", new { search = '%' + searchCriteria.SearchTerm + '%' });
            }

            IEnumerable<QueryExecutionViewData> queries = Current.DB.Query<QueryExecutionViewData>(
                pager.RawSql,
                pager.Parameters
            ).Select<QueryExecutionViewData, QueryExecutionViewData>(
                (view) =>
                {
                    view.UseLatestLink = useLatest;
                    view.SiteName = Site.Name.ToLower();

                    return view;
                }
            );
            int total = Current.DB.Query<int>(counter.RawSql, counter.Parameters).First();

            string href = "/" + Site.Name.ToLower() + "/queries?order_by=" + order_by;

            if (searchCriteria.IsValid)
            {
                href += "&q=" + HtmlUtilities.UrlEncode(searchCriteria.RawInput);
            }

            ViewData["SearchCriteria"] = searchCriteria;
            ViewData["TotalQueries"] = total;
            ViewData["PageNumbers"] = new PageNumber(
                href + "&page=-1",
                Convert.ToInt32(Math.Ceiling(total / (decimal)pagesize)),
                pagesize.Value,
                page.Value - 1,
                "pager"
            );
            ViewData["PageSizer"] = new PageSizer(
                href + "&pagesize=-1",
                page.Value,
                pagesize.Value,
                total,
                "page-sizer fr"
            );

            return View(queries);
        }
        public ActionResult Show(int id, string name, string order_by, int? page)
        {
            User user = Current.DB.Users.FirstOrDefault(row => row.Id == id);
            if (user == null)
            {
                return PageNotFound();
            }
            // if this user has a display name, and the title is missing or does not match, permanently redirect to it
            if (user.UrlTitle.HasValue() && (string.IsNullOrEmpty(name) || name != user.UrlTitle))
            {
                return PageMovedPermanentlyTo(string.Format("/users/{0}/{1}",user.Id, HtmlUtilities.URLFriendly(user.Login)) + Request.Url.Query);
            }

            DBContext db = Current.DB;

            SetHeader(user.Login);
            SelectMenuItem("Users");

            order_by = order_by ?? "edited";

            ViewData["UserQueryHeaders"] = new SubHeader
            {
                Items = new List<SubHeaderViewData>
                {
                    new SubHeaderViewData
                    {
                        Description = "edited",
                        Title = "Recently edited queries",
                        Href =
                            "/users/" + user.Id + "?order_by=edited",
                        Selected = (order_by == "edited")
                    },
                    new SubHeaderViewData
                    {
                        Description = "favorite",
                        Title = "Favorite queries",
                        Href =
                            "/users/" + user.Id +
                            "?order_by=favorite",
                        Selected = (order_by == "favorite")
                    },
                    new SubHeaderViewData
                    {
                        Description = "recent",
                        Title = "Recently executed queries",
                        Href =
                            "/users/" + user.Id + "?order_by=recent",
                        Selected = (order_by == "recent")
                    }
                }
            };

            page = Math.Max(page ?? 1, 1);
            int? pagesize = 15; // In case we decide to make this a query param

            int start = ((page.Value - 1) * pagesize.Value) + 1;
            int finish = page.Value * pagesize.Value;
            bool useLatest = false;
            string message;
            var builder = new SqlBuilder();
            var pager = builder.AddTemplate(@"
                SELECT
                    *
                FROM
                    (
                        SELECT
                            /**select**/, ROW_NUMBER() OVER(/**orderby**/) AS RowNumber
                        FROM
                            Queries query
                            /**join**/
                            /**leftjoin**/
                            /**where**/
                    ) AS results
                WHERE
                    RowNumber BETWEEN @start AND @finish
                ORDER BY
                    RowNumber",
                new { start = start, finish = finish }
            );
            var counter = builder.AddTemplate("SELECT COUNT(*) FROM Queries query /**join**/ /**leftjoin**/ /**where**/");

            if (order_by == "recent")
            {
                builder.Select("execution.RevisionId AS Id");
                builder.Select("execution.LastRun");
                builder.Select("site.Name AS SiteName");
                builder.Join("QueryExecutions execution ON execution.QueryId = query.Id");
                builder.Join("Sites site ON site.Id = execution.SiteId");
                builder.Join("Revisions ON Revisions.Id = execution.RevisionId AND execution.UserId = @user", new { user = id });
                builder.Join(@"
                    Metadata metadata ON
                    (
                        metadata.RevisionId = Revisions.RootId AND
                        metadata.OwnerId = Revisions.OwnerId
                    ) OR (
                        metadata.RevisionId = Revisions.Id AND
                        metadata.OwnerId = Revisions.OwnerId AND
                        Revisions.RootId IS NULL
                    ) OR (
                        metadata.RevisionId = Revisions.Id AND
                        metadata.OwnerId IS NULL AND
                        Revisions.OwnerId IS NULL
                    )"
                );
                builder.OrderBy("execution.LastRun DESC");

                message = user.Id == CurrentUser.Id ?
                    "You have never ran any queries" : "No queries ran recently";
            }
            else
            {
                builder.Select("metadata.RevisionId AS Id");
                builder.Select("metadata.LastActivity AS LastRun");
                builder.Join("Metadata metadata on metadata.LastQueryId = query.Id");

                if (order_by == "favorite")
                {
                    builder.Join(@"
                        Votes ON
                        Votes.RootId = metadata.RevisionId AND
                        (
                            Votes.OwnerId = metadata.OwnerId OR
                            (Votes.OwnerId IS NULL AND metadata.OwnerID IS NULL)
                        ) AND
                        Votes.UserId = @user AND
                        Votes.VoteTypeId = @vote",
                        new { user = id, vote = (int)VoteType.Favorite }
                    );
                    builder.OrderBy("metadata.Votes DESC");

                    useLatest = true;
                    message = user.Id == CurrentUser.Id ?
                        "You have no favorite queries, click the star icon on a query to favorite it" : "No favorites";
                } else {
                    builder.Where("metadata.OwnerId = @user", new { user = id });
                    builder.Where("metadata.Hidden = 0");
                    builder.OrderBy("metadata.LastActivity DESC");

                    message = user.Id == CurrentUser.Id ?
                        "You haven't edited any queries" : "No queries";
                }
            }

            builder.Select("[user].Id as CreatorId");
            builder.Select("[user].Login as CreatorLogin");
            builder.Select("metadata.Title AS Name");
            builder.Select("metadata.[Description] AS [Description]");
            builder.Select("metadata.Votes AS FavoriteCount");
            builder.Select("metadata.Views AS Views");
            builder.Select("query.QueryBody AS [SQL]");
            builder.LeftJoin("Users [user] ON [user].Id = metadata.OwnerId");

            var queries = Current.DB.Query<QueryExecutionViewData>(
                pager.RawSql,
                pager.Parameters
            ).Select<QueryExecutionViewData, QueryExecutionViewData>(
                (view) =>
                {
                    view.UseLatestLink = useLatest;
                    view.SiteName = (view.SiteName ?? Site.Name).ToLower();

                    return view;
                }
            );
            int total = Current.DB.Query<int>(counter.RawSql, counter.Parameters).First();

            string href = string.Format("/users/{0}/{1}", user.Id, HtmlUtilities.URLFriendly(user.Login)) + "?order_by=" + order_by;

            ViewData["Queries"] = queries;
            ViewData["PageNumbers"] = new PageNumber(
                href + "&page=-1",
                Convert.ToInt32(Math.Ceiling(total / (decimal)pagesize)),
                pagesize.Value,
                page.Value - 1,
                "pager"
            );

            if (!queries.Any())
            {
                ViewData["EmptyMessage"] = message;
            }

            return View(user);
        }