Exemple #1
0
 protected override void OnPreRender(EventArgs e)
 {
     base.OnPreRender(e);
     if (!IsPostBack)
     {
         if (FilePath != null)
         {
             DocumentLink.Visible     = true;
             DocumentLink.NavigateUrl = FilePath;
             DocumentLink.CssClass    = string.Format("document {0}Extension", VirtualPathUtility.GetExtension(FilePath).Substring(1));
             DocumentLink.Text        = Server.HtmlEncode(VirtualPathUtility.GetFileName(FilePath));
             DataBind();
         }
         else if (DisplayMissingMessage)
         {
             // Show the error message label and set the translated error message
             ErrorMessage.Visible = true;
             ErrorMessage.Text    = Translate("/error/document");
         }
         else
         {
             this.Visible = false;
         }
     }
 }
Exemple #2
0
        /// <summary>
        /// Gets the file changed delegate. It will call the appropriate methods of <see cref="IFileManager"/> when the file structure has changed.
        /// </summary>
        /// <param name="args">The arguments.</param>
        /// <returns></returns>
        private SystemManager.RunWithElevatedPrivilegeDelegate GetFileChangedDelegate(FileChangedDelegateArguments args)
        {
            return((p) =>
            {
                //get the resource file manager depending on its type
                IFileManager resourceFilesManager = this.GetResourceFileManager(args.ResourceFolder);

                if (resourceFilesManager != null)
                {
                    switch (args.ChangeType)
                    {
                    case FileChangeType.Created:
                        {
                            resourceFilesManager.FileAdded(args.FileName, args.FilePath, args.PackageName);
                            break;
                        }

                    case FileChangeType.Deleted:
                        {
                            resourceFilesManager.FileDeleted(args.FilePath);
                            break;
                        }

                    case FileChangeType.Renamed:
                        {
                            var oldVirtualFilePath = args.OldFilePath.Substring(this.GetApplicationPhysicalPath().Length - 1).Replace('\\', '/');
                            var oldFileName = VirtualPathUtility.GetFileName(oldVirtualFilePath);
                            resourceFilesManager.FileRenamed(args.FileName, oldFileName, args.FilePath, args.OldFilePath, args.PackageName);
                            break;
                        }
                    }
                }
            });
        }
        // Checks whether the specified virtual path represents a service that we generate(d) on the fly.
        private static bool OwnsFile(string virtualPath)
        {
            if (!virtualPath.EndsWith(ServiceUtility.ServiceFileExtension, StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            string fileName        = VirtualPathUtility.GetFileName(virtualPath);
            bool   isDomainService = domainServiceTypes.ContainsKey(fileName);

            // Make sure we avoid doing any expensive lookups if we don't need to.
            if (!isDomainService)
            {
                return(false);
            }

            // Verify this is a request to a file in the domain services directory.
            string directoryPath = VirtualPathUtility.ToAppRelative(VirtualPathUtility.GetDirectory(virtualPath));

            if (!directoryPath.Equals(DomainServiceVirtualPathProvider.DomainServicesDirectory))
            {
                return(false);
            }

            // If a physical file with this name exists, let that file get through.
            string filePath = HttpContext.Current.Server.MapPath(virtualPath);

            if (File.Exists(filePath))
            {
                return(false);
            }

            return(isDomainService);
        }
        public static string GetPhysicalFilePath(string virtualPath)
        {
            // ... resolve the virtual file and return the correct physical file path
            var fileName = VirtualPathUtility.GetFileName(virtualPath);

            return(HttpContext.Current.Server.MapPath("/reportslocal/") + fileName);
        }
        public override void Write(ContentItem item, string propertyName, TextWriter writer)
        {
            var filePath = item[propertyName] as string;

            if (string.IsNullOrEmpty(filePath))
            {
                return;
            }

            string url = Context.Current.Container.Resolve <IExternalWebLinkResolver>().GetPublicUrl(filePath);

            if (string.IsNullOrWhiteSpace(url))
            {
                return;
            }

            var extension = VirtualPathUtility.GetExtension(url);

            switch (ImagesUtility.GetExtensionGroup(extension))
            {
            case ImagesUtility.ExtensionGroups.Images:
                writer.Write("<img src=\"{0}\" alt=\"{1}\"  />", url, Alt);
                return;

            default:
                writer.Write("<a href=\"{0}\">{1}</a>", url, VirtualPathUtility.GetFileName(url));
                return;
            }
        }
Exemple #6
0
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler" /> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext" /> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        /// <exception cref="System.Web.HttpException">404;Not found</exception>
        public void ProcessRequest(HttpContext context)
        {
            if (this.FileExists(context.Request.Url.AbsolutePath))
            {
                using (var fileStream = this.OpenFile(context.Request.Url.AbsolutePath))
                {
                    var fileName = VirtualPathUtility.GetFileName(context.Request.Url.AbsolutePath);
                    var buffer   = new byte[fileStream.Length];
                    fileStream.Read(buffer, 0, (int)fileStream.Length);
                    context.Response.ContentType = ResourceHttpHandler.GetMimeMapping(fileName);

                    if (fileName.EndsWith("css", StringComparison.OrdinalIgnoreCase) ||
                        fileName.EndsWith("js", StringComparison.OrdinalIgnoreCase) ||
                        fileName.EndsWith("html", StringComparison.OrdinalIgnoreCase) ||
                        fileName.EndsWith("htm", StringComparison.OrdinalIgnoreCase))
                    {
                        var cache = context.Response.Cache;
                        cache.SetCacheability(HttpCacheability.Public);
                        cache.SetExpires(DateTime.Now + TimeSpan.FromDays(7));
                        cache.SetValidUntilExpires(true);

                        var lastWriteTime = ResourceHttpHandler.GetAssemblyLastWriteTime();
                        cache.SetLastModified(lastWriteTime);
                    }

                    this.WriteToOutput(context, buffer);
                }
            }
            else
            {
                throw new HttpException(404, "Not found");
            }
        }
 public LocalResXAssemblyResourceManager(TemplateControl templateControl, Assembly localResourceAssembly)
     : base(
         VirtualPathUtility.GetFileName(templateControl.AppRelativeVirtualPath), localResourceAssembly)
 {
     AssertUtils.ArgumentNotNull(templateControl, "templateControl");
     AssertUtils.ArgumentNotNull(localResourceAssembly, "localResourceAssembly");
 }
Exemple #8
0
        private void application_AuthenticateRequest(Object source, EventArgs e)
        {
            HttpApplication application = (HttpApplication)source;
            HttpContext     context     = application.Context;
            string          filePath    = context.Request.FilePath.ToString().ToLower();
            string          fileName    = VirtualPathUtility.GetFileName(filePath);
            string          fileExt     = VirtualPathUtility.GetExtension(filePath);
            string          rawUrl      = context.Request.RawUrl.ToLower();

            if (fileExt.CompareTo(".aspx") != 0)
            {
                if (rawUrl.Contains("/files/qr/"))
                {
                    context.Response.Redirect("/web/web_login.aspx");
                    return;
                }
                return;
            }
            if (rawUrl.Contains("/web/") && !rawUrl.Contains("/web/web_login.aspx") && !rawUrl.Contains("/web/web_ajax.aspx"))
            {
                if (!WebLoginHelper.IsLogin())
                {
                    context.Response.Redirect("/web/web_login.aspx");
                    return;
                }
                return;
            }
        }
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler" /> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext" /> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        /// <exception cref="System.Web.HttpException">404;Not found</exception>
        public void ProcessRequest(HttpContext context)
        {
            if (this.FileExists(context.Request.Url.AbsolutePath))
            {
                var fileName = VirtualPathUtility.GetFileName(context.Request.Url.AbsolutePath);

                this.SetResponseClientCache(context, fileName);

                if (!(fileName.EndsWith(".sf-cshtml", StringComparison.OrdinalIgnoreCase) && this.IsWhitelisted(context.Request.Url.AbsolutePath)))
                {
                    using (var fileStream = this.OpenFile(context.Request.Url.AbsolutePath))
                    {
                        this.SendStaticResource(context, fileStream, fileName);
                    }
                }
                else
                {
                    using (new CultureRegion(context.Request.Headers["SF_UI_CULTURE"]))
                    {
                        this.SendParsedTemplate(context);
                    }
                }
            }
            else
            {
                throw new HttpException(404, "Not found");
            }
        }
Exemple #10
0
 /// <summary>
 /// Delete_s the directory.
 /// </summary>
 //[Test]
 public void Create_And_Save_New_File_In_Directory()
 {
     // Use the special "Execute" method to run code
     // in the special AppDomain.
     this.Execute(() =>
     {
         const string virtualPath = "/assets/newFile.txt";
         var file = HostingEnvironment.VirtualPathProvider.GetFile(virtualPath) as CommonVirtualFile;
         if (file == null)
         {
             var virtualDir = VirtualPathUtility.GetDirectory(virtualPath);
             var directory  = HostingEnvironment.VirtualPathProvider.GetDirectory(virtualDir) as CommonVirtualDirectory;
             file           = directory.CreateFile(VirtualPathUtility.GetFileName(virtualPath));
         }
         // open the replacement file and read its content
         byte[] fileContent;
         using (var fileStream = new FileStream(@"c:\temp\fileToCopy.txt", FileMode.Open, FileAccess.Read)) {
             fileContent = new byte[fileStream.Length];
             fileStream.Read(fileContent, 0, fileContent.Length);
         }
         // write the content to the file (that exists in BrickPile's file system)
         using (Stream stream = file.Open(FileMode.Create)) {
             stream.Write(fileContent, 0, fileContent.Length);
         }
     });
 }
 public static void WriteError(Exception ex)
 {
     try {
         string path = "~/error/logs/" + System.DateTime.Now.ToString("dd-MM-yyyy") + ".txt";
         if ((!System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(path))))
         {
             System.IO.File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();
         }
         using (System.IO.StreamWriter w = System.IO.File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))) {
             w.WriteLine(System.Environment.NewLine + "Log Entry : {0}", System.DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantCulture));
             var page = VirtualPathUtility.GetFileName(HttpContext.Current.Request.Url.AbsolutePath);
             w.WriteLine("Error in: " + page);
             string message = "Message: " + ex.Message;
             w.WriteLine(message);
             string stack = "StackTrace: " + ex.StackTrace;
             w.WriteLine(stack);
             w.WriteLine("__________________________");
             w.Flush();
             w.Close();
         }
     } catch (Exception writeLogException) {
         try {
             WriteError(writeLogException);
         } catch (Exception innerEx) {
             //ignore
         }
     }
 }
Exemple #12
0
        bool InternalCompile()
        {
            string fileName = VirtualPathUtility.GetFileName(_url);

            string fullFileName = (fileName.ToLower() == "global.asax") ? _url : _context.Request.MapPath(_url);

            Debug.WriteLine("fullFileName=" + fullFileName);
            //type not found - run aspxparser
            if (false /*File.Exists(fullFileName) || Directory.Exists(fullFileName)*/)            //dynamic compilation currently is not supported
            {
                string[] command = GetParserCmd(fileName.ToLower() == "global.asax");
                if (J2EEUtils.RunProc(command) != 0)
                {
                    throw GetCompilerError();
                }

                return(true);
            }
            else
            {
                return(false);
                //string message = "The requested resource (" + _url + ") is not available.";
                //throw new HttpException(404, message);
            }
        }
        void btnCrop_Click(object sender, EventArgs e)
        {
            if (SiteUtils.IsImageFileExtension(ext))
            {
                int x = 0;
                int y = 0;
                int w = 0;
                int h = 0;
                //TODO: validate that these are not 0
                int.TryParse(X.Value, out x);
                int.TryParse(Y.Value, out y);
                int.TryParse(W.Value, out w);
                int.TryParse(H.Value, out h);

                if (allowUserToSetFinalFileSize)
                {
                    int.TryParse(txtFinalWidth.Text, out finalMaxWidth);
                    int.TryParse(txtFinalHeight.Text, out finalMaxHeight);
                }

                if (fileSystem.FileExists(sourceImagePath))
                {
                    if ((allowUserToChooseCroppedFileName) && (txtCroppedFileName.Text.Length > 0))
                    {
                        string newFileName = (Path.GetFileNameWithoutExtension(txtCroppedFileName.Text) + ext).ToCleanFileName();
                        resultImagePath = resultImagePath.Replace(VirtualPathUtility.GetFileName(resultImagePath), newFileName);
                    }

                    mojoPortal.Web.ImageHelper.CropImage(sourceImagePath, resultImagePath, IOHelper.GetMimeType(ext), w, h, x, y, WebConfigSettings.DefaultResizeBackgroundColor);

                    targetExists       = true;
                    initialSelectionX  = x;
                    initialSelectionY  = y;
                    initialSelectionX2 = x + w;
                    initialSelectionY2 = y + h;

                    if (finalMaxWidth > 0)
                    {
                        if (aspectRatio == 1)
                        {
                            mojoPortal.Web.ImageHelper.ResizeAndSquareImage(resultImagePath, IOHelper.GetMimeType(ext), finalMaxWidth, WebConfigSettings.DefaultResizeBackgroundColor);
                        }
                        else
                        {
                            bool allowEnlargement = true;
                            mojoPortal.Web.ImageHelper.ResizeImage(resultImagePath, IOHelper.GetMimeType(ext), finalMaxWidth, finalMaxHeight, allowEnlargement, WebConfigSettings.DefaultResizeBackgroundColor);
                        }
                    }
                }
            }
            else
            {
                sourceImagePath = string.Empty;
            }

            //WebUtils.SetupRedirect(this, Request.RawUrl);

            PopulateControls();
            //updPanel.Update();
        }
Exemple #14
0
        public override BundleResponse CacheLookup(BundleContext context)
        {
            BundleResponse bundleResponse = base.CacheLookup(context);

            if (bundleResponse == null || context.EnableInstrumentation)
            {
                bundleResponse = this.GenerateBundleResponse(context);
                if (!context.EnableInstrumentation)
                {
                    UpdateCache(context, bundleResponse);
                }
            }
            else
            {
                var contentType = bundleResponse.ContentType == "text/css" ? "text/css" : "text/javascript";
                var file        = VirtualPathUtility.GetFileName(context.BundleVirtualPath);
                var folder      = VirtualPathUtility.GetDirectory(context.BundleVirtualPath).TrimStart('~', '/').TrimEnd('/');
                var ext         = contentType == "text/css" ? ".css" : ".js";
                var azurePath   = string.Format("{0}/{1}{2}", folder, file, ext).ToLower();
                if (!_config.BlobStorage.BlobExists(_config.Container, azurePath))
                {
                    _config.BlobStorage.UploadStringBlob(_config.Container, azurePath, bundleResponse.Content, contentType, _config.BundleCacheTTL);
                }
                var AcceptEncoding = context.HttpContext.Request.Headers["Accept-Encoding"].ToLowerInvariant();
                if (!string.IsNullOrEmpty(AcceptEncoding) && AcceptEncoding.Contains("gzip") && _config.UseCompression.Value)
                {
                    azurePath = string.Format("{0}/{1}/{2}{3}", folder, "compressed", file, ext).ToLower();
                    if (!_config.BlobStorage.BlobExists(_config.Container, azurePath))
                    {
                        _config.BlobStorage.CompressBlob(_config.Container, azurePath, bundleResponse.Content, contentType, _config.BundleCacheTTL);
                    }
                }
            }
            return(bundleResponse);
        }
        public override AuthenticationSchemes GetAuthenticationSchemes(Uri baseAddress)
        {
            string str3;
            string fileName           = VirtualPathUtility.GetFileName(baseAddress.AbsolutePath);
            string currentVirtualPath = ServiceHostingEnvironment.CurrentVirtualPath;

            if ((currentVirtualPath != null) && currentVirtualPath.EndsWith("/", StringComparison.Ordinal))
            {
                str3 = currentVirtualPath + fileName;
            }
            else
            {
                str3 = string.Format(CultureInfo.InvariantCulture, "{0}/{1}", new object[] { currentVirtualPath, fileName });
            }
            AuthenticationSchemes authenticationSchemes = HostedTransportConfigurationManager.MetabaseSettings.GetAuthenticationSchemes(str3);

            if (!ServiceHostingEnvironment.IsSimpleApplicationHost || (authenticationSchemes != (AuthenticationSchemes.Anonymous | AuthenticationSchemes.Ntlm)))
            {
                return(authenticationSchemes);
            }
            if (this.IsWindowsAuthenticationConfigured())
            {
                return(AuthenticationSchemes.Ntlm);
            }
            return(AuthenticationSchemes.Anonymous);
        }
        /// <summary>
        /// When overridden in a derived class, returns a read-only stream to the virtual resource.
        /// </summary>
        /// <returns>A read-only stream to the virtual file.</returns>
        public override Stream Open()
        {
            byte[] data;

            var fileName = VirtualPathUtility.GetFileName(_path);

            try
            {
                var context = HttpContext.Current;
                if (!Settings.LocalReports)
                {
                    var container = WutStorage.GetContainer("reports");
                    var blobFile  = (CloudBlockBlob)WutStorage.GetBlob(container, fileName);
                    blobFile.FetchAttributes();
                    data = new byte[blobFile.Properties.Length];
                    blobFile.DownloadToByteArray(data, 0);
                }
                else
                {
                    var filepath = context.Server.MapPath("/reportslocal/") + fileName;
                    using (var file = File.Open(filepath, FileMode.Open))
                    {
                        data = new byte[file.Length];
                        file.Read(data, 0, (int)file.Length);
                        file.Close();
                    }
                }
                return(new MemoryStream(data));
            }
            catch (Exception ex)
            {
                var msg = String.Format("Error retrieving {0} from {1}", fileName, ((!Settings.LocalReports) ? "blob" : "local storage"));
                throw new Exception(msg, ex);
            }
        }
Exemple #17
0
        private static Stream ReadResource(string embeddedFileName)
        {
            string   resourceFileName = VirtualPathUtility.GetFileName(embeddedFileName);
            Assembly assembly         = Assembly.GetExecutingAssembly();

            return(assembly.GetManifestResourceStream(MasterPageVirtualPathProvider.VirtualPathProviderResourceLocation + "." + resourceFileName));
        }
        public static string CheckVersion()
        {
            Service service = new Service();

            service.Timeout = 3000;
            string msg = string.Empty;

            try
            {
                string url;

                if (HttpContext.Current.Request.Url.Port == 80)
                {
                    url = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Host + HttpContext.Current.Request.FilePath;
                }
                else
                {
                    url = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Host + ":" + HttpContext.Current.Request.Url.Port + HttpContext.Current.Request.FilePath;
                }

                url = url.Substring(0, url.Length - VirtualPathUtility.GetFileName(HttpContext.Current.Request.FilePath).Length);

#if SQLSERVER
                msg = service.CheckVersion(Settings.Version, "SQLServer", url);
#endif
#if SQLITE
                msg = service.CheckVersion(Settings.Version, "SQLite", url);
#endif
            }
            catch { }
            return(msg);
        }
Exemple #19
0
        public static string GetThumb(string originalPath, int width, int height, long quality)
        {
            string fileName = VirtualPathUtility.GetFileName(originalPath);

            fileName = Path.GetFileNameWithoutExtension(fileName);



            string thubPath          = string.Format(thumbnailPathPattern, width, height, fileName);
            string physicalThumbPath = DCServer.MapPath(thubPath);



            if (!File.Exists(physicalThumbPath))
            {
                string physicalOriginalPath = DCServer.MapPath(originalPath);
                if (File.Exists(physicalOriginalPath))
                {
                    //----------------------------------
                    //check does directory exists
                    //----------------------------------
                    string thumbDirectoryPath         = string.Format(thumbnailDirectoryPattern, width, height);
                    string physicalthumbDirectoryPath = DCServer.MapPath(thumbDirectoryPath);

                    if (!Directory.Exists(physicalthumbDirectoryPath))
                    {
                        Directory.CreateDirectory(physicalthumbDirectoryPath);
                    }
                    //----------------------------------

                    CreateThumb(physicalOriginalPath, physicalThumbPath, width, height, quality);
                }
            }
            return(thubPath);
        }
Exemple #20
0
 public FileSiteMapNode(SiteMapProvider provider, string url)
     : base(provider, url)
 {
     Url           = url;
     Title         = VirtualPathUtility.GetFileName(url);
     FileExtension = VirtualPathUtility.GetExtension(url).TrimStart('.');
 }
Exemple #21
0
        private void UploadSitePicture(HttpContext context, string funType)
        {
            HttpFileCollection files = context.Request.Files;

            if (files.Count == 0)
            {
                context.Response.Write("{\"success\": false,\"message\": \"未找到任何可上传的文件,请检查!\"}");
                return;
            }

            var          userId = WebCommon.GetUserId();
            int          effect = 0;
            ImagesHelper ih     = new ImagesHelper();

            using (TransactionScope scope = new TransactionScope())
            {
                foreach (string item in files.AllKeys)
                {
                    HttpPostedFile file = files[item];
                    if (file == null || file.ContentLength == 0)
                    {
                        continue;
                    }

                    int fileSize       = file.ContentLength;
                    int uploadFileSize = int.Parse(WebConfigurationManager.AppSettings["UploadFileSize"]);
                    if (fileSize > uploadFileSize)
                    {
                        throw new ArgumentException("文件【" + file.FileName + "】大小超出字节" + uploadFileSize + ",无法上传,请正确操作!");
                    }
                    if (!UploadFilesHelper.IsFileValidated(file.InputStream, fileSize))
                    {
                        throw new ArgumentException("文件【" + file.FileName + "】为受限制的文件,请正确操作!");
                    }

                    //string fileName = file.FileName;
                    var bll = new SitePicture();
                    //if (bll.IsExist(userId, file.FileName, fileSize)) throw new ArgumentException("文件【" + file.FileName + "】已存在,请勿重复上传!");

                    string originalUrl = UploadFilesHelper.UploadOriginalFile(file, "SitePicture");

                    var model = new SitePictureInfo(Guid.Empty, userId, VirtualPathUtility.GetFileName(originalUrl), fileSize, VirtualPathUtility.GetExtension(originalUrl).ToLower(), VirtualPathUtility.GetDirectory(originalUrl.Replace("~", "")), Path.GetFileNameWithoutExtension(context.Server.MapPath(originalUrl)), funType, DateTime.Now);
                    CreateThumbnailImage(context, ih, context.Server.MapPath(originalUrl));

                    bll.Insert(model);
                    effect++;
                }

                scope.Complete();
            }

            if (effect > 0)
            {
                context.Response.Write("{\"success\": true,\"message\": \"已成功上传文件数:" + effect + "个\"}");
            }
            else
            {
                context.Response.Write("{\"success\": false,\"message\": \"上传失败,请检查!\"}");
            }
        }
Exemple #22
0
        private static void WriteUrl(ContentItem item, string propertyName, string cssClass, TextWriter writer, string url)
        {
            cssClass = item[propertyName + "_CssClass"] as string ?? cssClass;
            string fileName = "";

            try
            {
                if (!url.Contains("//"))
                {
                    fileName = VirtualPathUtility.GetFileName(url);
                }
            }
            catch (Exception)
            {
            }

            if (string.IsNullOrEmpty(cssClass))
            {
                writer.Write(string.Format("<a href=\"{0}\">{1}</a>", url, fileName));
            }
            else
            {
                writer.Write(string.Format("<a href=\"{0}\" class=\"{1}\">{2}</a>", url, cssClass, fileName));
            }
        }
Exemple #23
0
    void context_BeginRequest(object sender, EventArgs e)
    {
        if (_Extenstions.Count() > 0)
        {
            string ext = VirtualPathUtility.GetExtension(_context.Request.FilePath).
                         Substring(1).ToLower();
            if (_Extenstions.Contains(ext))
            {
                _IsMatch = true;
            }
        }
        if (_Files.Count() > 0)
        {
            string fileName = VirtualPathUtility.GetFileName(_context.Request.FilePath).ToLower();
            if (_Files.Contains(fileName))
            {
                _IsMatch = true;
            }
        }

        if (_LogAlwaysRequest || _IsMatch)
        {
            StreamReader reader      = new StreamReader(_context.Request.InputStream);
            string       requestText = reader.ReadToEnd();
            _context.Request.InputStream.Position = 0;
            //LOG requestText
        }
    }
Exemple #24
0
        public virtual void Process(BundleContext context, BundleResponse response)
        {
            var file = VirtualPathUtility.GetFileName(context.BundleVirtualPath);

            if (!context.BundleCollection.UseCdn)
            {
                return;
            }
            if (string.IsNullOrWhiteSpace(ContainerName))
            {
                throw new Exception("ContainerName Not Set");
            }

            var connectionString = CloudConfigurationManager.GetSetting("StorageConnectionString");

            var conn = CloudStorageAccount.Parse(connectionString);
            var cont = conn.CreateCloudBlobClient().GetContainerReference(ContainerName);

            cont.CreateIfNotExists(BlobContainerPublicAccessType.Blob);
            var blob = cont.GetBlockBlobReference(file);

            blob.Properties.ContentType = response.ContentType;
            blob.UploadText(response.Content);

            var uri = string.IsNullOrWhiteSpace(CdnHost) ? blob.Uri.AbsoluteUri.Replace("http:", "").Replace("https:", "") : string.Format("{0}/{1}/{2}", CdnHost, ContainerName, file);

            using (var hashAlgorithm = CreateHashAlgorithm())
            {
                var hash = HttpServerUtility.UrlTokenEncode(hashAlgorithm.ComputeHash(Encoding.Unicode.GetBytes(response.Content)));
                context.BundleCollection.GetBundleFor(context.BundleVirtualPath).CdnPath = string.Format("{0}?v={1}", uri, hash);
            }
        }
Exemple #25
0
        private void LoadSizes()
        {
            var    imageConfig = Engine.Resolve <EditSection>().Images;
            string baseImagePath, imageSize;

            ImagesUtility.SplitImageAndSize(Selection.SelectedItem.Url, imageConfig.Sizes.GetSizeNames(), out baseImagePath, out imageSize);
            foreach (var size in imageConfig.Sizes.AllElements.Where(s => s.Announced))
            {
                var hl = new HyperLink();
                hl.ID = size.Name + "Size";
                bool exists;
                var  path = ImagesUtility.GetExistingImagePath(Engine.Resolve <IFileSystem>(), baseImagePath, size.Name, out exists);
                if (exists)
                {
                    var file = (SelectedFile.Parent as File) ?? SelectedFile;

                    hl.NavigateUrl = "File.aspx?selected=" + file.GetChild(VirtualPathUtility.GetFileName(path)).Path;
                    hl.Text        = Utility.GetResourceString("ImageSizes", size.Name + ".Text") ?? (string.IsNullOrEmpty(size.Description) ? size.Name : size.Description);
                    hl.Text       += GetSizeText(size.Width, size.Height);
                    hl.CssClass    = "command";
                    if (path == Selection.SelectedItem.Url)
                    {
                        omSizes.Controls.AddAt(0, hl);
                    }
                    else
                    {
                        omSizes.Controls.Add(hl);
                    }
                }
            }
            omSizes.Visible = omSizes.Controls.Count > 1;
        }
Exemple #26
0
        public string[] ResolveResourceFilePaths(string virtualPath)
        {
            string fileName = VirtualPathUtility.GetFileName(virtualPath);
            string path     = VirtualPathUtility.GetDirectory(virtualPath);

            path += "App_LocalResources/";
            return(Directory.GetFiles(HostingEnvironment.MapPath(path), String.Concat(fileName, "*.resx")));
        }
        public override IResourceProvider CreateLocalResourceProvider(string virtualPath)
        {
            string directory = HttpContext.Current.Server.MapPath(VirtualPathUtility.GetDirectory(virtualPath) + "\\App_LocalResources");

            string baseName = VirtualPathUtility.GetFileName(virtualPath);

            return(new XmlResourceProvider(directory, baseName));
        }
Exemple #28
0
        protected override void OnPreLoad(EventArgs e)
        {
            //base.OnPreLoad(e);

            if (RecentPages == null)
            {
                RecentPages = new List <PageContext>();
            }


            var currentPageContext = new PageContext();

            currentPageContext.Path = AppRelativeVirtualPath;

            if (string.IsNullOrEmpty(CurrentPageTitle))
            {
                currentPageContext.Title = this.Title;
            }
            else
            {
                currentPageContext.Title = CurrentPageTitle;
            }
            currentPageContext.AbsoluteUri = Request.Url.AbsoluteUri;

            var currentPageName = System.IO.Path.GetFileNameWithoutExtension(VirtualPathUtility.GetFileName(Request.Path));

            currentPageContext.Name = currentPageName;

            var currentPageUrlParameters = new List <string>();

            foreach (string key in Request.QueryString.Keys)
            {
                currentPageUrlParameters.Add(key + "=" + Request.QueryString[key]);
            }

            currentPageContext.UrlParamaters = currentPageUrlParameters;

            var index = RecentPages.FindIndex(recPageContext => MatchesContext(recPageContext, currentPageName, currentPageUrlParameters));

            if (index == -1)
            {
                //Костылек
                var recentPageContext = RecentPages.FirstOrDefault(item => item.Name == "EntityListAttributeView");
                if (recentPageContext != null && currentPageName == "EntityListAttributeView")
                {
                    RecentPages.Remove(recentPageContext);
                    RecentPages.Add(currentPageContext);
                }
                else
                {
                    RecentPages.Add(currentPageContext);
                }
            }
            else
            {
                RecentPages.RemoveRange(index + 1);
            }
        }
Exemple #29
0
        public LibraryVirtualFile(string virtualPath) : base(virtualPath)
        {
            m_virtualPath = virtualPath;
            m_extension   = VirtualPathUtility.GetExtension(virtualPath).ToLower();
            m_fileName    = VirtualPathUtility.GetFileName(m_virtualPath).ToLower();

            // If no extension exists, set Exists to false.
            m_exists = !String.IsNullOrEmpty(m_extension);
        }
Exemple #30
0
        public bool IsVirtualFile(string virtualPath)
        {
            /*
             * Se o path n�o possir extension, ignora.
             * Se a extens�o n�o for permitida, ignora.
             * Se o path for reservado, ignora.
             * Se o diretório pai possuir extension, ignora
             */
            try
            {
                var extension = VirtualPathUtility.GetExtension(virtualPath);
                if (string.IsNullOrEmpty(extension))
                {
                    return(false);
                }

                var directory = VirtualPathUtility.ToAbsolute(VirtualPathUtility.GetDirectory(virtualPath));

                var dirHasExtension = !string.IsNullOrEmpty(VirtualPathUtility.GetExtension(directory));
                if (dirHasExtension)
                {
                    return(false);
                }

                var fileName = VirtualPathUtility.GetFileName(virtualPath);

                if (string.IsNullOrEmpty(fileName))
                {
                    return(false);
                }

                if (_ignoredFiles.Any(x => x.Equals(fileName, StringComparison.InvariantCultureIgnoreCase)))
                {
                    return(false);
                }

                if (!_allowedExtensions.Any(x => x.Equals(extension, StringComparison.InvariantCultureIgnoreCase)))
                {
                    return(false);
                }

                if (_ignoredDirectories.Any(directory.Contains))
                {
                    return(false);
                }

                return(true);
            }
            catch (Exception ex)
            {
                Trace.TraceInformation("IsVirtualFile", ex);
            }

            return(false);
            //return virtualPath.StartsWith(_virtualRootPath);
        }