Exemple #1
0
        public async Task <ActionResult> Index()
        {
            // If there are access restrictions
            if (!await PageSecurityHelper.CheckUserHasAccessToBlog(User))
            {
                return(new HttpUnauthorizedResult());
            }

            WorkContext.Breadcrumbs.Add(T(KoreCmsLocalizableStrings.Blog.Title));

            int tenantId = WorkContext.CurrentTenant.Id;

            string pageIndexParam = Request.Params["pageIndex"];
            int    pageIndex      = string.IsNullOrEmpty(pageIndexParam)
                ? 1
                : Convert.ToInt32(pageIndexParam);

            List <BlogPost> model = null;

            using (var connection = postService.Value.OpenConnection())
            {
                model = await connection.Query(x => x.TenantId == tenantId)
                        .Include(x => x.Category)
                        .Include(x => x.Tags)
                        .OrderByDescending(x => x.DateCreatedUtc)
                        .Skip((pageIndex - 1) * blogSettings.ItemsPerPage)
                        .Take(blogSettings.ItemsPerPage)
                        .ToListAsync();
            }

            return(await Posts(pageIndex, model));
        }
Exemple #2
0
    /// <summary>
    /// Processes the specified file.
    /// </summary>
    /// <param name="fileGuid">File guid</param>
    protected void ProcessFile(Guid fileGuid)
    {
        // Get the file
        ForumAttachmentInfo fileInfo = ForumAttachmentInfoProvider.GetForumAttachmentInfoWithoutBinary(fileGuid, SiteContext.CurrentSiteName);

        if (fileInfo != null)
        {
            #region "Security"

            // Indicates whether current user is granted to see this attachment
            bool attachmentAllowed = false;

            // Get forum
            ForumInfo fi = ForumInfoProvider.GetForumInfo(fileInfo.AttachmentForumID);
            if (fi != null)
            {
                // Check acess
                if (ForumViewer.CheckPermission("AccessToForum", SecurityHelper.GetSecurityAccessEnum(fi.ForumAccess, 6), fi.ForumGroupID, fi.ForumID))
                {
                    attachmentAllowed = true;
                }
            }

            // If attachment is not allowed for current user, redirect to the access denied page
            if (!attachmentAllowed)
            {
                URLHelper.Redirect(PageSecurityHelper.AccessDeniedPageURL(CurrentSiteName));
            }

            #endregion


            bool resizeImage = (ImageHelper.IsMimeImage(fileInfo.AttachmentMimeType) &&
                                ForumAttachmentInfoProvider.CanResizeImage(fileInfo, Width, Height, MaxSideSize));

            // Get the data
            if ((outputFile == null) || (outputFile.ForumAttachment == null))
            {
                outputFile             = new CMSOutputForumAttachment(fileInfo, fileInfo.AttachmentBinary);
                outputFile.Width       = Width;
                outputFile.Height      = Height;
                outputFile.MaxSideSize = MaxSideSize;
                outputFile.Resized     = resizeImage;
            }
        }
    }
Exemple #3
0
        public async Task <ActionResult> Category(string categorySlug)
        {
            // If there are access restrictions
            if (!await PageSecurityHelper.CheckUserHasAccessToBlog(User))
            {
                return(new HttpUnauthorizedResult());
            }

            int tenantId = WorkContext.CurrentTenant.Id;
            var category = await categoryService.Value.FindOneAsync(x => x.TenantId == tenantId && x.UrlSlug == categorySlug);

            if (category == null)
            {
                throw new EntityNotFoundException(string.Concat(
                                                      "Could not find a blog category with slug, '", categorySlug, "'"));
            }

            WorkContext.Breadcrumbs.Add(T(KoreCmsLocalizableStrings.Blog.Title), Url.Action("Index"));
            WorkContext.Breadcrumbs.Add(category.Name);

            string pageIndexParam = Request.Params["pageIndex"];
            int    pageIndex      = string.IsNullOrEmpty(pageIndexParam)
                ? 1
                : Convert.ToInt32(pageIndexParam);

            List <BlogPost> model = null;

            using (var connection = postService.Value.OpenConnection())
            {
                model = await connection.Query()
                        .Include(x => x.Category)
                        .Include(x => x.Tags)
                        .Where(x => x.CategoryId == category.Id)
                        .OrderByDescending(x => x.DateCreatedUtc)
                        .Skip((pageIndex - 1) * blogSettings.ItemsPerPage)
                        .Take(blogSettings.ItemsPerPage)
                        .ToListAsync();
            }

            return(await Posts(pageIndex, model));
        }
Exemple #4
0
        private async Task <ActionResult> PagePreview(PageVersion pageVersion)
        {
            if (pageVersion != null)
            {
                pageVersion.Page.IsEnabled = true; // Override here to make sure it passes the check here: PageSecurityHelper.CheckUserHasAccessToPage

                // If there are access restrictions
                if (!await PageSecurityHelper.CheckUserHasAccessToPage(pageVersion.Page, User))
                {
                    return(new HttpUnauthorizedResult());
                }

                // Else no restrictions (available for anyone to view)
                WorkContext.SetState("CurrentPageId", pageVersion.Id);
                WorkContext.Breadcrumbs.Add(pageVersion.Title);

                var pageType = await pageTypeService.Value.FindOneAsync(pageVersion.Page.PageTypeId);

                var korePageType = pageTypeService.Value.GetKorePageType(pageType.Name);
                korePageType.InstanceName     = pageVersion.Title;
                korePageType.InstanceParentId = pageVersion.Page.ParentId;

                korePageType.LayoutPath = string.IsNullOrWhiteSpace(pageType.LayoutPath)
                    ? KoreWebConstants.DefaultFrontendLayoutPath
                    : pageType.LayoutPath;

                korePageType.InitializeInstance(pageVersion);

                var contentBlocks = contentBlockService.Value.GetContentBlocks(pageVersion.Id, WorkContext.CurrentCultureCode);
                korePageType.ReplaceContentTokens(x => InsertContentBlocks(x, contentBlocks));

                return(View(korePageType.DisplayTemplatePath, korePageType));
            }

            return(HttpNotFound());
        }
    /// <summary>
    /// Processes the file.
    /// </summary>
    protected void ProcessFile()
    {
        if (fileGuid == Guid.Empty)
        {
            return;
        }

        // Get the file
        ForumAttachmentInfo fileInfo = ForumAttachmentInfoProvider.GetForumAttachmentInfoWithoutBinary(fileGuid, SiteContext.CurrentSiteName);

        if (fileInfo == null)
        {
            return;
        }

        // Check forum access
        var forum = ForumInfoProvider.GetForumInfo(fileInfo.AttachmentForumID);

        if ((forum == null) || !ForumViewer.CheckPermission("AccessToForum", SecurityHelper.GetSecurityAccessEnum(forum.ForumAccess, 6), forum.ForumGroupID, forum.ForumID, CurrentUser))
        {
            // If attachment is not allowed for current user, redirect to the access denied page
            URLHelper.Redirect(PageSecurityHelper.AccessDeniedPageURL(CurrentSiteName));
        }

        bool resizeImage = (ImageHelper.IsMimeImage(fileInfo.AttachmentMimeType) && ForumAttachmentInfoProvider.CanResizeImage(fileInfo, Width, Height, MaxSideSize));

        // Get the data
        if ((outputFile == null) || (outputFile.ForumAttachment == null))
        {
            outputFile             = new CMSOutputForumAttachment(fileInfo, fileInfo.AttachmentBinary);
            outputFile.Width       = Width;
            outputFile.Height      = Height;
            outputFile.MaxSideSize = MaxSideSize;
            outputFile.Resized     = resizeImage;
        }
    }
        public async Task <ActionResult> Index(string slug)
        {
            // Hack to make it search the correct path for the view
            if (!this.ControllerContext.RouteData.DataTokens.ContainsKey("area"))
            {
                this.ControllerContext.RouteData.DataTokens.Add("area", CmsConstants.Areas.Pages);
            }

            int tenantId       = WorkContext.CurrentTenant.Id;
            var currentCulture = WorkContext.CurrentCultureCode;

            //TODO: To support localized routes, we should probably first try get a single record by slug,
            //  then if there's only 1, fine.. return it.. if more than one.. then add cultureCode as
            //  we currently do...

            // First try get the latest published version for the current culture
            PageVersion pageVersion;

            using (var connection = pageVersionService.OpenConnection())
            {
                pageVersion = await connection.Query()
                              .Include(x => x.Page)
                              .Where(x =>
                                     x.TenantId == tenantId &&
                                     x.Status == VersionStatus.Published &&
                                     x.CultureCode == currentCulture &&
                                     x.Slug == slug)
                              .OrderByDescending(x => x.DateModifiedUtc)
                              .FirstOrDefaultAsync();
            }

            // If there isn't one...
            if (pageVersion == null)
            {
                // ...then try get the last archived one for the current culture
                // NOTE: there's no need to worry about the last one being a draft before being archived, because
                //  we ONLY archive the published ones, not drafts.. so getting the last archived one will be the last published one
                using (var connection = pageVersionService.OpenConnection())
                {
                    pageVersion = await connection.Query()
                                  .Include(x => x.Page)
                                  .Where(x =>
                                         x.TenantId == tenantId &&
                                         x.Status == VersionStatus.Archived &&
                                         x.CultureCode == currentCulture &&
                                         x.Slug == slug)
                                  .OrderByDescending(x => x.DateModifiedUtc)
                                  .FirstOrDefaultAsync();
                }
            }

            // If there isn't one...
            if (pageVersion == null)
            {
                // ...then try get the latest published version for the invariant culture
                using (var connection = pageVersionService.OpenConnection())
                {
                    pageVersion = await connection.Query()
                                  .Include(x => x.Page)
                                  .Where(x =>
                                         x.TenantId == tenantId &&
                                         x.Status == VersionStatus.Published &&
                                         x.CultureCode == null &&
                                         x.Slug == slug)
                                  .OrderByDescending(x => x.DateModifiedUtc)
                                  .FirstOrDefaultAsync();
                }
            }

            // If there isn't one...
            if (pageVersion == null)
            {
                // ...then try get the last archived one for the invariant culture (TODO: What if last archived was a draft??)
                using (var connection = pageVersionService.OpenConnection())
                {
                    pageVersion = await connection.Query()
                                  .Include(x => x.Page)
                                  .Where(x =>
                                         x.TenantId == tenantId &&
                                         x.Status == VersionStatus.Archived &&
                                         x.CultureCode == null &&
                                         x.Slug == slug)
                                  .OrderByDescending(x => x.DateModifiedUtc)
                                  .FirstOrDefaultAsync();
                }
            }

            if (pageVersion != null && pageVersion.Page.IsEnabled)
            {
                // If there are access restrictions
                if (!await PageSecurityHelper.CheckUserHasAccessToPage(pageVersion.Page, User))
                {
                    return(new HttpUnauthorizedResult());
                }

                // Else no restrictions (available for anyone to view)
                WorkContext.SetState("CurrentPageId", pageVersion.PageId);
                WorkContext.Breadcrumbs.Add(pageVersion.Title);

                var pageType = await pageTypeService.FindOneAsync(pageVersion.Page.PageTypeId);

                var korePageType = pageTypeService.GetKorePageType(pageType.Name);
                korePageType.InstanceName     = pageVersion.Title;
                korePageType.InstanceParentId = pageVersion.Page.ParentId;

                korePageType.LayoutPath = string.IsNullOrWhiteSpace(pageType.LayoutPath)
                    ? KoreWebConstants.DefaultFrontendLayoutPath
                    : pageType.LayoutPath;

                korePageType.InitializeInstance(pageVersion);

                var contentBlocks = contentBlockService.GetContentBlocks(pageVersion.PageId, WorkContext.CurrentCultureCode);
                korePageType.ReplaceContentTokens(x => InsertContentBlocks(x, contentBlocks.Where(y => IsVisible(y))));

                return(View(korePageType.DisplayTemplatePath, korePageType));
            }

            return(HttpNotFound());
        }
Exemple #7
0
        public async Task <ActionResult> Details(string slug)
        {
            // If there are access restrictions
            if (!await PageSecurityHelper.CheckUserHasAccessToBlog(User))
            {
                return(new HttpUnauthorizedResult());
            }

            int tenantId = WorkContext.CurrentTenant.Id;

            BlogPost model             = null;
            DateTime?previousEntryDate = null;
            DateTime?nextEntryDate     = null;

            using (var connection = postService.Value.OpenConnection())
            {
                model = await connection
                        .Query(x => x.TenantId == tenantId && x.Slug == slug)
                        .Include(x => x.Category)
                        .Include(x => x.Tags)
                        .FirstOrDefaultAsync();

                if (model == null)
                {
                    throw new KoreException("Blog post not found!");
                }

                bool hasPreviousEntry = await connection.Query(x => x.TenantId == tenantId).AnyAsync(x => x.DateCreatedUtc < model.DateCreatedUtc);

                if (hasPreviousEntry)
                {
                    previousEntryDate = await connection.Query(x => x.TenantId == tenantId && x.DateCreatedUtc < model.DateCreatedUtc)
                                        .Select(x => x.DateCreatedUtc)
                                        .MaxAsync();
                }

                bool hasNextEntry = await connection.Query(x => x.TenantId == tenantId).AnyAsync(x => x.DateCreatedUtc > model.DateCreatedUtc);

                if (hasNextEntry)
                {
                    nextEntryDate = await connection.Query(x => x.TenantId == tenantId && x.DateCreatedUtc > model.DateCreatedUtc)
                                    .Select(x => x.DateCreatedUtc)
                                    .MinAsync();
                }
            }

            WorkContext.Breadcrumbs.Add(T(KoreCmsLocalizableStrings.Blog.Title), Url.Action("Index"));
            WorkContext.Breadcrumbs.Add(model.Headline);

            ViewBag.PreviousEntrySlug = previousEntryDate.HasValue
                ? (await postService.Value.FindOneAsync(x => x.TenantId == tenantId && x.DateCreatedUtc == previousEntryDate)).Slug
                : null;

            ViewBag.NextEntrySlug = nextEntryDate.HasValue
                ? (await postService.Value.FindOneAsync(x => x.TenantId == tenantId && x.DateCreatedUtc == nextEntryDate)).Slug
                : null;

            ViewBag.UserName = (await membershipService.Value.GetUserById(model.UserId)).UserName;

            var tags = await tagService.Value.FindAsync(x => x.TenantId == tenantId);

            ViewBag.Tags    = tags.ToDictionary(k => k.Id, v => v.Name);
            ViewBag.TagUrls = tags.ToDictionary(k => k.Id, v => v.UrlSlug);

            var viewEngineResult = ViewEngines.Engines.FindView(ControllerContext, "Details", null);

            // If someone has provided a custom template (see LocationFormatProvider)
            if (viewEngineResult.View != null)
            {
                return(View(model));
            }

            // Else use default template
            return(View("Kore.Web.ContentManagement.Areas.Admin.Blog.Views.BlogContent.Details", model));
        }
Exemple #8
0
        public ActionResult AutoBreadcrumbs(string templateViewName)
        {
            var breadcrumbs = new List <Breadcrumb>();

            string currentUrlSlug = Request.Url.LocalPath.TrimStart('/');

            if (currentUrlSlug == "blog")
            {
                breadcrumbs.Add(new Breadcrumb
                {
                    Text = blogSettings.Value.PageTitle
                });
                return(View(templateViewName, breadcrumbs));
            }

            var pageService        = EngineContext.Current.Resolve <IPageService>();
            var pageVersionService = EngineContext.Current.Resolve <IPageVersionService>();

            int tenantId = WorkContext.CurrentTenant.Id;

            PageVersion currentPageVersion;

            using (var connection = pageVersionService.OpenConnection())
            {
                currentPageVersion = connection.Query()
                                     .Include(x => x.Page)
                                     .FirstOrDefault(x => x.TenantId == tenantId && x.Slug == currentUrlSlug);
            }

            var allPages = pageService.Find(x => x.TenantId == tenantId && x.IsEnabled);

            if (currentPageVersion != null)
            {
                var parentId = currentPageVersion.Page.ParentId;
                while (parentId != null)
                {
                    var parentPage = allPages.FirstOrDefault(x => x.Id == parentId);

                    if (parentPage == null)
                    {
                        break;
                    }

                    bool hasAccess = AsyncHelper.RunSync(() => PageSecurityHelper.CheckUserHasAccessToPage(parentPage, User));
                    if (hasAccess)
                    {
                        var currentVersion = pageVersionService.GetCurrentVersion(tenantId, parentPage.Id, WorkContext.CurrentCultureCode);
                        breadcrumbs.Add(new Breadcrumb
                        {
                            Text = currentVersion.Title,
                            Url  = parentPage.IsEnabled ? "/" + currentVersion.Slug : null
                        });
                    }

                    parentId = parentPage.ParentId;
                }

                breadcrumbs.Reverse();

                breadcrumbs.Add(new Breadcrumb
                {
                    Text = currentPageVersion.Title
                });
            }
            else
            {
                // This is not a CMS page, so use breadcrumbs specified in controller actions...
                breadcrumbs.AddRange(WorkContext.Breadcrumbs);
            }

            return(View(templateViewName, breadcrumbs));
        }
Exemple #9
0
        public ActionResult AutoSubMenu(string templateViewName)
        {
            // we need a better way to get slug, because it could be something like /store/categories/category-1/product-1
            // and this current way would only return product-1
            string currentUrlSlug = Request.Url.LocalPath.TrimStart('/');
            var    menuItems      = new List <MenuItem>();
            var    menuId         = Guid.NewGuid();

            var menuProviders = EngineContext.Current.ResolveAll <IAutoMenuProvider>();

            // If home page
            if (string.IsNullOrEmpty(currentUrlSlug))
            {
                bool hasAccess = AsyncHelper.RunSync(() => PageSecurityHelper.CheckUserHasAccessToBlog(User));
                if (blogSettings.Value.ShowOnMenus && hasAccess)
                {
                    menuItems.Add(new MenuItem
                    {
                        Id       = menuId,
                        Text     = blogSettings.Value.PageTitle,
                        Url      = "/blog",
                        Enabled  = true,
                        ParentId = null,
                        Position = blogSettings.Value.MenuPosition
                    });
                }

                foreach (var menuProvider in menuProviders)
                {
                    menuItems.AddRange(menuProvider.GetMainMenuItems(User).Where(x => x.ParentId == null));
                }
            }
            foreach (var menuProvider in menuProviders)
            {
                if (currentUrlSlug.StartsWith(menuProvider.RootUrlSlug))
                {
                    menuItems.AddRange(menuProvider.GetSubMenuItems(currentUrlSlug, User));
                }
            }

            var pageVersionService = EngineContext.Current.Resolve <IPageVersionService>();

            var pageVersions = Enumerable.Empty <PageVersion>();

            bool hasCmsPages = true;

            int tenantId = WorkContext.CurrentTenant.Id;

            // If on home page
            if (string.IsNullOrEmpty(currentUrlSlug))
            {
                pageVersions = pageVersionService.GetCurrentVersions(
                    tenantId,
                    WorkContext.CurrentCultureCode,
                    enabledOnly: true,
                    shownOnMenusOnly: true,
                    topLevelOnly: true);
            }
            else
            {
                // We don't care about culture here because the only thing we're interested in getting is
                //  the Page ID, which will of course be the same for all versions of a page.
                PageVersion anyVersion = null;
                using (var connection = pageVersionService.OpenConnection())
                {
                    anyVersion = connection.Query(x =>
                                                  x.TenantId == tenantId &&
                                                  x.Slug == currentUrlSlug)
                                 .Include(x => x.Page)
                                 .FirstOrDefault();
                }

                // If the current page is a CMS page
                if (anyVersion != null)
                {
                    pageVersions = pageVersionService.GetCurrentVersions(
                        tenantId,
                        WorkContext.CurrentCultureCode,
                        enabledOnly: true,
                        shownOnMenusOnly: true,
                        parentId: anyVersion.Page.Id);
                }
                else
                {
                    hasCmsPages = false;
                }
            }

            if (hasCmsPages)
            {
                var authorizedPages = pageVersions.Where(x => AsyncHelper.RunSync(() => PageSecurityHelper.CheckUserHasAccessToPage(x.Page, User)));

                var items = authorizedPages
                            .Select(x => new MenuItem
                {
                    Id       = x.Page.Id,
                    Text     = x.Title,
                    Url      = "/" + x.Slug,
                    Enabled  = true,
                    ParentId = x.Page.ParentId,
                    Position = x.Page.Order
                });

                menuItems.AddRange(items);
            }

            menuItems = menuItems
                        .OrderBy(x => x.Position)
                        .ThenBy(x => x.Text)
                        .ToList();

            ViewBag.MenuId = menuId;
            return(View(templateViewName, menuItems));
        }
Exemple #10
0
        public ActionResult AutoMenu(string templateViewName, bool includeHomePageLink = true)
        {
            var pageService        = EngineContext.Current.Resolve <IPageService>();
            var pageVersionService = EngineContext.Current.Resolve <IPageVersionService>();

            var menuItems = new List <MenuItem>();
            var menuId    = Guid.NewGuid();

            if (includeHomePageLink)
            {
                menuItems.Add(new MenuItem
                {
                    Id       = menuId,
                    Text     = T(KoreWebLocalizableStrings.General.Home),
                    Url      = "/",
                    Enabled  = true,
                    ParentId = null,
                    Position = -1 // Always first
                });
            }

            int tenantId = WorkContext.CurrentTenant.Id;

            var pageVersions = pageVersionService.GetCurrentVersions(
                tenantId,
                WorkContext.CurrentCultureCode,
                enabledOnly: true,
                shownOnMenusOnly: true);

            var authorizedPages = pageVersions.Where(x => AsyncHelper.RunSync(() => PageSecurityHelper.CheckUserHasAccessToPage(x.Page, User)));

            var items = authorizedPages
                        .Select(x => new MenuItem
            {
                Id       = x.Page.Id,
                Text     = x.Title,
                Url      = "/" + x.Slug,
                Enabled  = true,
                ParentId = x.Page.ParentId,
                Position = x.Page.Order
            });

            menuItems.AddRange(items);

            bool hasAccess = AsyncHelper.RunSync(() => PageSecurityHelper.CheckUserHasAccessToBlog(User));

            if (hasAccess && blogSettings.Value.ShowOnMenus)
            {
                menuItems.Add(new MenuItem
                {
                    Id       = menuId,
                    Text     = blogSettings.Value.PageTitle,
                    Url      = "/blog",
                    Enabled  = true,
                    ParentId = null,
                    Position = blogSettings.Value.MenuPosition
                });
            }

            var menuProviders = EngineContext.Current.ResolveAll <IAutoMenuProvider>();

            foreach (var menuProvider in menuProviders)
            {
                menuItems.AddRange(menuProvider.GetMainMenuItems(User));
            }

            menuItems = menuItems
                        .OrderBy(x => x.Position)
                        .ThenBy(x => x.Text)
                        .ToList();

            ViewBag.MenuId = menuId;
            return(View(templateViewName, menuItems));
        }
    /// <summary>
    /// Sends the given file within response.
    /// </summary>
    /// <param name="file">File to send</param>
    protected void SendFile(CMSOutputMediaFile file)
    {
        // Clear response.
        CookieHelper.ClearResponseCookies();
        Response.Clear();

        // Set the revalidation
        SetRevalidation();

        // Send the file
        if (file != null)
        {
            #region "Security"

            // Check if user is allowed to see the library file content if required
            bool checkPermissions = SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSCheckMediaFilePermissions");
            if (checkPermissions)
            {
                // Check the library access for the current user and stop file processing if not allowed
                MediaLibraryInfo mli = MediaLibraryInfoProvider.GetMediaLibraryInfo(file.MediaFile.FileLibraryID);
                if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(mli, "LibraryAccess"))
                {
                    URLHelper.Redirect(PageSecurityHelper.AccessDeniedPageURL(CurrentSiteName));
                    return;
                }
            }

            #endregion


            // Prepare etag
            string etag = "";
            if (file.MediaFile != null)
            {
                etag += file.MediaFile.FileModifiedWhen.ToUniversalTime();
            }

            // Put etag into ""
            etag = String.Format("\"{0}\"", etag);

            // Client caching - only on the live site
            if (useClientCache && AllowCache && ETagsMatch(etag, file.LastModified))
            {
                // Set correct response content type
                SetResponseContentType(file);

                // Set the file time stamps to allow client caching
                SetTimeStamps(file);

                RespondNotModified(etag, true);
                return;
            }

            // If physical file not present, try to load
            EnsurePhysicalFile(outputFile);

            // If the output data should be cached, return the output data
            bool cacheOutputData = false;
            if ((file.MediaFile != null) && (CacheMinutes > 0))
            {
                cacheOutputData = CacheHelper.CacheImageAllowed(CurrentSiteName, (int)file.MediaFile.FileSize);
            }

            // Ensure the file data if physical file not present
            if (!file.DataLoaded && (file.PhysicalFile == ""))
            {
                byte[] cachedData = GetCachedOutputData();
                if (file.EnsureData(cachedData))
                {
                    if ((cachedData == null) && cacheOutputData)
                    {
                        SaveOutputDataToCache(file.OutputData, GetOutputDataDependency(file.MediaFile));
                    }
                }
            }

            // Send the file
            if ((file.OutputData != null) || (file.PhysicalFile != ""))
            {
                // Set correct response content type
                SetResponseContentType(file);

                string extension = file.FileExtension;
                SetDisposition(file.FileName + extension, extension);

                // Setup Etag property
                ETag = etag;

                // Set if resumable downloads should be supported
                AcceptRange = !IsExtensionExcludedFromRanges(extension);

                if (useClientCache && AllowCache)
                {
                    // Set the file time stamps to allow client caching
                    SetTimeStamps(file);

                    Response.Cache.SetETag(etag);
                }

                // Add the file data
                if ((file.PhysicalFile != "") && (file.OutputData == null))
                {
                    if (!File.Exists(file.PhysicalFile))
                    {
                        // File doesn't exist
                        NotFound();
                    }
                    else
                    {
                        // Stream the file from the file system
                        file.OutputData = WriteFile(file.PhysicalFile, cacheOutputData);
                    }
                }
                else
                {
                    // Use output data of the file in memory if present
                    WriteBytes(file.OutputData);
                }
            }
            else
            {
                NotFound();
            }
        }
        else
        {
            NotFound();
        }

        CompleteRequest();
    }