Exemple #1
0
        private static bool IsNonUpdatablePrecompiledAppNoCache()
        {
            if (HostingEnvironment.VirtualPathProvider == null)
            {
                return(false);
            }
            string virtualPath = VirtualPathUtility.ToAbsolute("~/PrecompiledApp.config");

            if (!HostingEnvironment.VirtualPathProvider.FileExists(virtualPath))
            {
                return(false);
            }
            XmlDocument document = new XmlDocument();

            document.Load(VirtualPathProvider.OpenFile(virtualPath));
            XmlNode documentElement = document.DocumentElement;

            if ((documentElement == null) || (documentElement.Name != "precompiledApp"))
            {
                return(false);
            }
            XmlNode namedItem = documentElement.Attributes.GetNamedItem("updatable");

            return((namedItem != null) && (namedItem.Value == "false"));
        }
        public void ProcessRequest(HttpContext context)
        {
            var routeDataValues = _routeData.Values;

            var folder = routeDataValues["root"].ToString();

            if (PatternProvider.FolderNameData.EndsWith(folder, StringComparison.InvariantCultureIgnoreCase))
            {
                folder = string.Concat(PatternProvider.IdentifierHidden, folder);
            }

            var filePath    = routeDataValues["path"] != null ? routeDataValues["path"].ToString() : string.Empty;
            var fileName    = Path.GetFileName(filePath);
            var virtualPath = string.Format("/{0}/{1}", folder, filePath);

            using (var stream = VirtualPathProvider.OpenFile(virtualPath))
            {
                if (stream.Length <= 0)
                {
                    return;
                }

                context.Response.Clear();
                context.Response.ContentType = MimeMapping.GetMimeMapping(fileName);

                stream.CopyTo(context.Response.OutputStream);
            }
        }
Exemple #3
0
        private static IEnumerable <string> ReadDependencies(string path)
        {
            // read dependencies for .js files only
            if (!path.ToLower().EndsWith(".js"))
            {
                return(new List <string>());
            }

            try
            {
                var deps = new List <string>();
                using (var str = VirtualPathProvider.OpenFile(path))
                    using (var r = new StreamReader(str))
                    {
                        var l = r.ReadLine();
                        var parsedDependency = ParseDependency(l);
                        while (parsedDependency != null)
                        {
                            deps.Add(parsedDependency);
                            l = r.ReadLine();
                            parsedDependency = ParseDependency(l);
                        }
                    }
                return(deps);
            }
            catch (Exception e)
            {
                SnLog.WriteException(e);
            }

            return(null);
        }
        public object Transform(object results)
        {
            string xml = results as string;

            if (xml == null)
            {
                throw new ArgumentException(PreviewWeb.XsltBridgeTransformer_StringOnly, "results");
            }
            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(xml);
            XslCompiledTransform xslt = new XslCompiledTransform();

            // REVIEW: Is passing in CurrentCulture for the StringWriter correct? Previously
            // it wasn't passing in anything, and CurrentCulture is the default anyway.
            using (StringWriter output = new StringWriter(CultureInfo.CurrentCulture)) {
                // Make it absolute to get around an ASP.NET issue
                _xsltVirtualPath = VirtualPathUtility.ToAbsolute(_xsltVirtualPath);
                using (Stream file = VirtualPathProvider.OpenFile(_xsltVirtualPath)) {
                    using (XmlReader reader = XmlReader.Create(file)) {
                        xslt.Load(reader);
                        xslt.Transform(xmlDocument, null, output);
                    }
                }
                return(output.GetStringBuilder().ToString());
            }
        }
        private void sendMail(string type, string researchName, string title, string researcherName, string surname, string workGroup, string activityName, string email)
        {
            using (StreamReader sr = new StreamReader(VirtualPathProvider.OpenFile("/Content/mailtemplate.html")))
            {
                string content = sr.ReadToEnd();
                content = content.Replace("{title}", title);
                content = content.Replace("{name}", researcherName);
                content = content.Replace("{surname}", surname);
                content = content.Replace("{workgroup}", workGroup);
                content = content.Replace("{type}", type);
                content = content.Replace("{researchname}", researchName);
                content = content.Replace("{activityname}", activityName);
                System.Diagnostics.Debug.WriteLine(content);

                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

                MailAddress from = new MailAddress("*****@*****.**", "ERIMS ODPC6 Chonburi");
                MailAddress to   = new MailAddress(email);

                MailMessage mail = new MailMessage(from, to);
                mail.To.Add("*****@*****.**");
                mail.CC.Add("*****@*****.**");
                mail.Subject    = "[ERIMS] แจ้งเตือนเข้าสู่กิจกรรมในโครงการ " + researchName;
                mail.Body       = content;
                mail.IsBodyHtml = true;

                SmtpServer.Port        = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "aca12345");
                SmtpServer.EnableSsl   = true;

                SmtpServer.Send(mail);

                System.Diagnostics.Debug.WriteLine("Mail Sent");
            }
        }
Exemple #6
0
 internal static string GetStringFromVirtualPath(string virtualPath)
 {
     using (Stream stream = VirtualPathProvider.OpenFile(virtualPath)) {
         using (TextReader reader = new StreamReader(stream)) {
             return(reader.ReadToEnd());
         }
     }
 }
 public ColorBlindRenderer(ChromeDriver chromeDriver)
 {
     _chromeDriver = chromeDriver;
     using (var sr = new StreamReader(VirtualPathProvider.OpenFile("/Scripts/ColorBlind.js")))
     {
         _colorBlindScript = sr.ReadToEnd();
     }
     DestroyPageTimers();
 }
Exemple #8
0
        //TODO: Add unit test for icon handler
        public void ProcessRequest(HttpContext context)
        {
            var set = context.Items["set"];
            var key = context.Items["key"];
            var ico = Url.ResolveTokens("{ManagementUrl}/Resources/icons/");

            var cssFile = ico + set + ".css";
            var sprFile = ico + set + ".png";

            // TODO consider caching this information
            var cssLines = new List <string>();

            using (var stream = VirtualPathProvider.OpenFile(cssFile))
                using (var sr = new StreamReader(stream))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        if (line.Contains("." + key + " {") || line.Contains("." + key + "{"))
                        {
                            cssLines.Add(line);
                        }
                    }
                }

            if (cssLines.Count == 0)
            {
                throw new KeyNotFoundException(String.Format("Sprite '{0}' not found in CSS at '{1}'.", key, cssFile));
            }
            if (cssLines.Count > 1)
            {
                throw new AmbiguousMatchException(String.Format("Sprite '{0}' ambiguous in CSS at '{1}'.", key, cssFile));
            }

            var css = ParseCssLine(cssLines[0]);             // and throw the rest away

            using (var bmp = new Bitmap(css.R.Width, css.R.Height))
            {
                using (var g = Graphics.FromImage(bmp))
                    using (var stream = VirtualPathProvider.OpenFile(sprFile))
                        using (var spr = Image.FromStream(stream))
                        {
                            // draw the sprite into bmp
                            var destRect = new Rectangle(0, 0, css.R.Width, css.R.Height);
                            g.DrawImage(spr, destRect, css.R, GraphicsUnit.Pixel);
                        }

                // save bmp
                using (var m = new MemoryStream())
                {
                    bmp.Save(m, ImageFormat.Png);
                    context.Response.ContentType = "image/png";
                    context.Response.BinaryWrite(m.ToArray());
                }
            }
        }
Exemple #9
0
        /// <summary>
        /// Read all the text for the path.
        /// </summary>
        /// <param name="virtualPath">The virtual path</param>
        /// <returns>The read text.</returns>
        public string ReadAllText(string virtualPath)
        {
            string path = VirtualPathUtility.IsAppRelative(virtualPath) ?
                          VirtualPathUtility.ToAbsolute(virtualPath) :
                          virtualPath;

            using (Stream stream = VirtualPathProvider.OpenFile(path))
                using (StreamReader sr = new StreamReader(stream))
                    return(sr.ReadToEnd());
        }
    // Constructor
    public ImageWebModel() : base()
    {
        //reading the details of students from file
        using (StreamReader sr = new StreamReader(VirtualPathProvider.OpenFile("/App_Data/info.txt")))
        {
            Student_Details = sr.ReadToEnd();
        }

        //updating status and photo number parameters
        UpdateParameters();
    }
Exemple #11
0
        public string ReadFileContent(string path)
        {
            string targetPath = VirtualPathUtility.IsAppRelative(path) ? VirtualPathUtility.ToAbsolute(path) : path;

            using (Stream file = VirtualPathProvider.OpenFile(targetPath))
            {
                using (StreamReader reader = new StreamReader(file))
                {
                    return(reader.ReadToEnd());
                };
            };
        }
        public static List <T> ExtractMultipleJsonObjectsFromFile <T>(string path)
        {
            Argument.CheckIfNullOrEmpty(path, "path");
            string data;

            using (StreamReader sr = new StreamReader(VirtualPathProvider.OpenFile(path)))
            {
                data = sr.ReadToEnd();
            }

            return(JsonConvert.DeserializeObject <List <T> >(data));
        }
        public override void GenerateCode(AssemblyBuilder assemblyBuilder)
        {
            // look at the assembly builder to see which language we should use in the App_Code directory
            EntityCodeGenerator generator = null;

            if (assemblyBuilder.CodeDomProvider.FileExtension.ToLowerInvariant() == "cs")
            {
                generator = new EntityCodeGenerator(LanguageOption.GenerateCSharpCode);
            }
            else
            {
                generator = new EntityCodeGenerator(LanguageOption.GenerateVBCode);
            }

            // generate the code for our CSDL file
            IList <EdmSchemaError> errors = null;

            using (XmlReader input = XmlReader.Create(VirtualPathProvider.OpenFile(base.VirtualPath)))
            {
                using (StringWriter output = new StringWriter(CultureInfo.InvariantCulture))
                {
                    // Read from input and generate into output, put errors in a class member
                    var entityFrameworkVersion = GetEntityFrameworkVersion(BuildManager.TargetFramework.Version);
                    errors = generator.GenerateCode(input, output, entityFrameworkVersion);
                    if (errors.Count == 0)
                    {
                        output.Flush();
                        assemblyBuilder.AddCodeCompileUnit(this, new CodeSnippetCompileUnit(output.ToString()));
                    }
                }
            }

            // if there are errors, package this data into XmlExceptions and throw this
            // if we are in VS, the ASP .NET stack will place this information in the error pane
            // if we are in the ASP .NET runtime, it will use this information to build the error page
            if (errors != null && errors.Count > 0)
            {
                XmlException inner = null;
                XmlException outer = null;
                foreach (EdmSchemaError error in errors)
                {
                    outer = new XmlException(error.Message, inner, error.Line, error.Column);
                    inner = outer;
                }

                throw outer;
            }

            BuildProviderUtils.AddArtifactReference(assemblyBuilder, this, base.VirtualPath);
        }
Exemple #14
0
            public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
            {
                //TODO: unix like filesystem support
                string nodePath = absoluteUri.AbsolutePath.Remove(0, (absoluteUri.AbsolutePath.IndexOf(":") + 1));

                DependencyPathCollection.Add(nodePath);

                System.IO.Stream xsltStream = null;

                // 20120222: dobsonl: we may use sensenet dlls from a webapp, and yet use no virtualpathprovider
                //if (HttpContext.Current != null)
                if (RepositoryPathProvider.DiskFSSupportMode == DiskFSSupportMode.Prefer)
                {
                    xsltStream = VirtualPathProvider.OpenFile(nodePath);
                }
                else
                {
                    var xsltFile = Node.Load <File>(nodePath);
                    xsltStream = xsltFile.Binary.GetStream();
                }
                XmlDocument doc = new XmlDocument();

                doc.Load(xsltStream);
                var result = doc.DocumentElement.Attributes.Cast <XmlAttribute>()
                             .Where(attrib => attrib.InnerText.StartsWith("sn://"))
                             .Select(attrib => attrib.InnerText)
                             .ToArray();

                ImportNamespaceCollection.AddRange(result);

                var scripts = doc.SelectNodes("//sn:scriptrequest", GetNamespaceManager());

                foreach (var scripelm in scripts.Cast <XmlElement>())
                {
                    this.ImportScriptCollection.Add(scripelm.GetAttribute("path"));
                }

                var csss = doc.SelectNodes("//sn:cssrequest", GetNamespaceManager());

                foreach (var csselm in csss.Cast <XmlElement>())
                {
                    this.ImportCssCollection.Add(csselm.GetAttribute("path"));
                }


                xsltStream.Position = 0;
                return(xsltStream);
            }
Exemple #15
0
            public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
            {
                string nodePath = absoluteUri.AbsolutePath.Remove(0, (absoluteUri.AbsolutePath.IndexOf(":") + 1));

                DependencyPathCollection.Add(nodePath);

                System.IO.Stream xsltStream = null;

                if (WebApplication.DiskFSSupportMode == DiskFSSupportMode.Prefer)
                {
                    xsltStream = VirtualPathProvider.OpenFile(nodePath);
                }
                else
                {
                    var xsltFile = (IFile)Node.LoadNode(nodePath);
                    xsltStream = xsltFile.Binary.GetStream();
                }
                var doc = new XmlDocument();

                doc.Load(xsltStream);
                var result = doc.DocumentElement.Attributes.Cast <XmlAttribute>()
                             .Where(attrib => attrib.InnerText.StartsWith("sn://"))
                             .Select(attrib => attrib.InnerText)
                             .ToArray();

                ImportNamespaceCollection.AddRange(result);

                var scripts = doc.SelectNodes("//sn:scriptrequest", GetNamespaceManager());

                foreach (var scripelm in scripts.Cast <XmlElement>())
                {
                    this.ImportScriptCollection.Add(scripelm.GetAttribute("path"));
                }

                var csss = doc.SelectNodes("//sn:cssrequest", GetNamespaceManager());

                foreach (var csselm in csss.Cast <XmlElement>())
                {
                    this.ImportCssCollection.Add(csselm.GetAttribute("path"));
                }


                xsltStream.Position = 0;
                return(xsltStream);
            }
Exemple #16
0
        internal static void AddArtifactReference(AssemblyBuilder assemblyBuilder, BuildProvider prov, string virtualPath)
        {
            // add the artifact as a resource to the DLL
            using (Stream input = VirtualPathProvider.OpenFile(virtualPath))
            {
                // derive the resource name
                string name = BuildProviderUtils.GetResourceNameForVirtualPath(virtualPath);

                using (Stream resStream = assemblyBuilder.CreateEmbeddedResource(prov, name))
                {
                    int byteRead = input.ReadByte();
                    while (byteRead != -1)
                    {
                        resStream.WriteByte((byte)byteRead);
                        byteRead = input.ReadByte();
                    }
                }
            }
        }
        public override void GenerateCode(AssemblyBuilder assemblyBuilder)
        {
#if !FEATURE_PAL // FEATURE_PAL does not support System.Configuration.Design
            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();

            // Process the .settings file and generate a CodeCompileUnit from it
            using (Stream stream = VirtualPathProvider.OpenFile(VirtualPath)) {
                using (TextReader reader = new StreamReader(stream)) {
                    SettingsSingleFileGenerator.Generate(
                        reader, codeCompileUnit, assemblyBuilder.CodeDomProvider, TypeAttributes.Public);
                }
            }

            // Add the CodeCompileUnit to the compilation
            assemblyBuilder.AddCodeCompileUnit(this, codeCompileUnit);
#else   // !FEATURE_PAL
            throw new NotImplementedException("System.Configuration.Design - ROTORTODO");
#endif  // !FEATURE_PAL
        }
Exemple #18
0
        public sUtenteNormale UtentiNormali()
        {
            sUtenteNormale sa = new sUtenteNormale();

            try
            {
                //C:\Users\yoravas\documents\visual studio 2015\Projects\NewISE\NewISE\Models\Config\s_admin\s_admin.json
                using (StreamReader sr = new StreamReader(VirtualPathProvider.OpenFile("/Models/Config/s_admin/s_utente.json")))
                {
                    string content = sr.ReadToEnd();
                    sa = JsonConvert.DeserializeObject <sUtenteNormale>(content);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(sa);
        }
 /// <summary>
 /// Loads this instance.
 /// </summary>
 void Load()
 {
     if (_content == null)
     {
         if (_isVirtual)
         {
             using (Stream inFile = VirtualPathProvider.OpenFile(_filePath)) {
                 _doc.Load(inFile);
             }
         }
         else
         {
             using (Stream inFile = File.Open(_filePath, FileMode.Open)) {
                 _doc.Load(inFile);
             }
         }
     }
     else
     {
         _doc.LoadXml(_content);
     }
 }
Exemple #20
0
        public sAdmin SuperAmministratore(string username)
        {
            sAdmin sa = new sAdmin();

            try
            {
                //C:\Users\yoravas\documents\visual studio 2015\Projects\NewISE\NewISE\Models\Config\s_admin\s_admin.json
                using (StreamReader sr = new StreamReader(VirtualPathProvider.OpenFile("/Models/Config/s_admin/s_admin.json")))
                {
                    string content = sr.ReadToEnd();
                    sa = JsonConvert.DeserializeObject <sAdmin>(content);

                    sa.s_admin = sa.s_admin.Where(a => a.username == username).ToList();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(sa);
        }
Exemple #21
0
        public static string ReadStaticFile(string virtualPath)
        {
            if (FileRepositoryManager.FileExists(virtualPath))
            {
                ActionResult        result       = FileRepositoryManager.GetFile(virtualPath);
                StaticContentResult staticResult = result as StaticContentResult;

                using (MemoryStream ms = new MemoryStream(staticResult.Uncompressed))
                    using (StreamReader reader = new StreamReader(ms))
                        return(reader.ReadToEnd());
            }
            else
            {
                if (virtualPath.StartsWith("~"))
                {
                    virtualPath = VirtualPathUtility.ToAbsolute(virtualPath);
                }

                using (Stream str = VirtualPathProvider.OpenFile(virtualPath))
                    using (StreamReader reader = new StreamReader(str))
                        return(reader.ReadToEnd());
            }
        }
Exemple #22
0
        /// <summary>
        /// Extract the CSDL, SSDL and MSL nodes from the EDMX file and store them
        /// as embedded resources
        /// </summary>
        /// <param name="assemblyBuilder"></param>
        public override void GenerateCode(AssemblyBuilder assemblyBuilder)
        {
            using (StreamReader edmxInputStream = new StreamReader(VirtualPathProvider.OpenFile(base.VirtualPath)))
            {
                // load up an XML document representing the edmx file
                XmlElement conceptualSchemaElement;
                XmlElement mappingElement;
                XmlElement storageSchemaElement;
                string     embedAsResourcePropertyValue;
                EntityDesignerUtils.ExtractConceptualMappingAndStorageNodes(edmxInputStream, out conceptualSchemaElement, out mappingElement, out storageSchemaElement, out embedAsResourcePropertyValue);

                if (null == conceptualSchemaElement)
                {
                    throw new XmlException("No Conceptual Schema node to embed as a resource", null, 0, 0);
                }

                if (null == storageSchemaElement)
                {
                    throw new XmlException("No Storage Schema node to embed as a resource", null, 0, 0);
                }

                if (null == mappingElement)
                {
                    throw new XmlException("No Mapping node to embed as a resource", null, 0, 0);
                }

                // construct output paths where the CSDL/MSL/SSDL resources will be placed
                string virtualPathPrefix = base.VirtualPath.Replace(EntityDesignerUtils._edmxFileExtension, String.Empty);
                string csdlResourceName  = BuildProviderUtils.GetResourceNameForVirtualPath(virtualPathPrefix + XmlConstants.CSpaceSchemaExtension);
                string ssdlResourceName  = BuildProviderUtils.GetResourceNameForVirtualPath(virtualPathPrefix + XmlConstants.SSpaceSchemaExtension);
                string mslResourceName   = BuildProviderUtils.GetResourceNameForVirtualPath(virtualPathPrefix + XmlConstants.CSSpaceSchemaExtension);

                SetupEmbeddedResource(assemblyBuilder, this, conceptualSchemaElement, csdlResourceName);
                SetupEmbeddedResource(assemblyBuilder, this, storageSchemaElement, ssdlResourceName);
                SetupEmbeddedResource(assemblyBuilder, this, mappingElement, mslResourceName);
            }
        }
 /// <devdoc>
 ///     Opens a stream for a virtual file
 /// </devdoc>
 protected Stream OpenStream(string virtualPath)
 {
     return(VirtualPathProvider.OpenFile(virtualPath));
 }
Exemple #24
0
 protected Stream OpenStream(string virtualPath)
 {
     // MS also throws a NullReferenceException here when not hosted.
     return(VirtualPathProvider.OpenFile(virtualPath));
 }
Exemple #25
0
        internal static string GetSourceFileLines(string fileName, Encoding encoding, string sourceCode, int lineNumber)
        {
            if ((fileName != null) && !HttpRuntime.HasFilePermission(fileName))
            {
                return(System.Web.SR.GetString("WithFile_No_Relevant_Line"));
            }
            StringBuilder builder = new StringBuilder();

            if (lineNumber <= 0)
            {
                return(System.Web.SR.GetString("WithFile_No_Relevant_Line"));
            }
            TextReader reader = null;
            string     virtualPathFromHttpLinePragma = ErrorFormatter.GetVirtualPathFromHttpLinePragma(fileName);

            if (virtualPathFromHttpLinePragma != null)
            {
                Stream stream = VirtualPathProvider.OpenFile(virtualPathFromHttpLinePragma);
                if (stream != null)
                {
                    reader = Util.ReaderFromStream(stream, System.Web.VirtualPath.Create(virtualPathFromHttpLinePragma));
                }
            }
            try
            {
                if ((reader == null) && (fileName != null))
                {
                    reader = new StreamReader(fileName, encoding, true, 0x1000);
                }
            }
            catch
            {
            }
            if (reader == null)
            {
                if (sourceCode == null)
                {
                    return(System.Web.SR.GetString("WithFile_No_Relevant_Line"));
                }
                reader = new StringReader(sourceCode);
            }
            try
            {
                string str2;
                bool   flag = false;
                if (ErrorFormatter.IsTextRightToLeft)
                {
                    builder.Append("<div dir=\"ltr\">");
                }
                int num = 1;
Label_0098:
                str2 = reader.ReadLine();
                if (str2 != null)
                {
                    if (num == lineNumber)
                    {
                        builder.Append("<font color=red>");
                    }
                    if ((num >= (lineNumber - 2)) && (num <= (lineNumber + 2)))
                    {
                        flag = true;
                        string str3 = num.ToString("G", CultureInfo.CurrentCulture);
                        builder.Append(System.Web.SR.GetString("WithFile_Line_Num", new object[] { str3 }));
                        if (str3.Length < 3)
                        {
                            builder.Append(' ', 3 - str3.Length);
                        }
                        builder.Append(HttpUtility.HtmlEncode(str2));
                        if (num != (lineNumber + 2))
                        {
                            builder.Append("\r\n");
                        }
                    }
                    if (num == lineNumber)
                    {
                        builder.Append("</font>");
                    }
                    if (num <= (lineNumber + 2))
                    {
                        num++;
                        goto Label_0098;
                    }
                }
                if (ErrorFormatter.IsTextRightToLeft)
                {
                    builder.Append("</div>");
                }
                if (!flag)
                {
                    return(System.Web.SR.GetString("WithFile_No_Relevant_Line"));
                }
            }
            finally
            {
                reader.Close();
            }
            return(builder.ToString());
        }
Exemple #26
0
 public Stream OpenFile(string path)
 {
     return(VirtualPathProvider.OpenFile(path));
 }
Exemple #27
0
        /// <summary>
        /// Collects all of the data that needs to be indexed as defined in the index set.
        /// </summary>
        /// <param name="node">Media item XML being indexed</param>
        /// <param name="type">Type of index (should only ever be media)</param>
        /// <returns>Fields containing the data for the index</returns>
        protected override Dictionary <string, string> GetDataToIndex(XElement node, string type)
        {
            var fields = base.GetDataToIndex(node, type);

            //find the field which contains the file
            var filePath = node.Elements().FirstOrDefault(x =>
            {
                if (x.Attribute("alias") != null)
                {
                    return((string)x.Attribute("alias") == this.UmbracoFileProperty);
                }
                else
                {
                    return(x.Name == this.UmbracoFileProperty);
                }
            });


            if (FileExists(filePath))
            {
                //get the file path from the data service
                var fullPath = this.DataService.MapPath((string)filePath);
                var fi       = new FileInfo(fullPath);
                if (fi.Exists)
                {
                    try
                    {
                        fields.Add(TextContentFieldName, ExtractTextFromFile(fi));

                        //add any addtional meta data extracted via tika from MediaParser.ParseMediaText
                        fields.AddRange(_extractedMetaFromTika);
                    }
                    catch (NotSupportedException)
                    {
                        //log that we couldn't index the file found
                        DataService.LogService.AddErrorLog((int)node.Attribute("id"), _loggerEntryName + ": Extension '" + fi.Extension + "' is not supported at this time");
                    }
                }
                else
                {
                    // perhaps it's available via the VirtualPathProvider ?

                    if (HostingEnvironment.VirtualPathProvider.FileExists((string)filePath))
                    {
                        var stream = VirtualPathProvider.OpenFile((string)filePath);

                        if (stream.CanRead)
                        {
                            var extractionResult = ExtractContentFromStream(stream);

                            if (!string.IsNullOrWhiteSpace(extractionResult.ExtractedText))
                            {
                                fields.Add(TextContentFieldName, extractionResult.ExtractedText);
                                fields.AddRange(extractionResult.MetaData);
                            }
                        }
                        else
                        {
                            DataService.LogService.AddInfoLog((int)node.Attribute("id"), _loggerEntryName + ": Can't read steam at path " + filePath);
                        }
                    }
                    else
                    {
                        DataService.LogService.AddInfoLog((int)node.Attribute("id"), _loggerEntryName + ": No file found at path " + filePath);
                    }
                }
            }

            return(fields);
        }
Exemple #28
0
 public void OpenFile1()
 {
     VirtualPathProvider.OpenFile("index.aspx");
 }
Exemple #29
0
        /*
         * Return the text of the error line in the source file, with a few
         * lines around it.  It is returned in HTML format.
         */
        public static string GetSourceFileLines(string fileName, Encoding encoding, string sourceCode, int lineNumber)
        {
            // Don't show any source file if the user doesn't have access to it (ASURT 122430)
            //if (fileName != null) // todo review this
            //{
            //    return "No relevante source code"; //todo add resource
            //}

            if (lineNumber <= 0)
            {
                return("No relevante source code"); //todo add resource
            }

            StringBuilder sb     = new StringBuilder();
            TextReader    reader = null;

            // Check if it's an http line pragma, from which we can get a VirtualPath
            string virtualPath = GetVirtualPathFromHttpLinePragma(fileName);

            // If we got a virtual path, open a TextReader from it
            if (virtualPath != null)
            {
                Stream stream = VirtualPathProvider.OpenFile(virtualPath);
                if (stream != null)
                {
                    reader = ReaderFromStream(stream, System.Web.VirtualPath.Create(virtualPath));
                }
            }

            try
            {
                // Otherwise, open the physical file
                if (reader == null && fileName != null)
                {
                    reader = new StreamReader(fileName, encoding, true, 4096);
                }
            }
            catch { }

            if (reader == null)
            {
                if (sourceCode == null)
                {
                    return("SR.GetString(SR.WithFile_No_Relevant_Line)"); //todo;
                }
                // Can't open the file?  Use the dynamically generated content...
                reader = new StringReader(sourceCode);
            }

            try
            {
                bool fFoundLine = false;

                for (int i = 1; ; i++)
                {
                    // Get the current line from the source file
                    string sourceLine = reader.ReadLine();
                    if (sourceLine == null)
                    {
                        break;
                    }

                    // If it's the error line, make it red
                    if (i == lineNumber)
                    {
                        sb.Append("<font color=red>");
                    }

                    // Is it in the range we want to display
                    if (i >= lineNumber - errorRange && i <= lineNumber + errorRange)
                    {
                        fFoundLine = true;
                        String linestr = i.ToString("G", CultureInfo.CurrentCulture);

                        sb.Append(linestr); //todo
                        if (linestr.Length < 3)
                        {
                            sb.Append(' ', 3 - linestr.Length);
                        }
                        sb.Append(HttpUtility.HtmlEncode(sourceLine));

                        if (i != lineNumber + errorRange)
                        {
                            sb.Append("\r\n");
                        }
                    }

                    if (i == lineNumber)
                    {
                        sb.Append("</font>");
                    }

                    if (i > lineNumber + errorRange)
                    {
                        break;
                    }
                }

                if (!fFoundLine)
                {
                    return("SR.GetString(SR.WithFile_No_Relevant_Line)"); //todo
                }
            }
            finally
            {
                // Make sure we always close the reader
                reader.Close();
            }

            return(sb.ToString());
        }
        /// <summary>
        ///     Build an ASPX or HTML file to be used as our error page.
        /// </summary>
        /// <param name="virtualPath">path to directory where error pages are located</param>
        /// <param name="context">Context for OneTrueError</param>
        /// <returns>Complete string</returns>
        public static string Build(string virtualPath, HttpErrorReporterContext context)
        {
            var url =
                new Uri(string.Format("{0}://{1}{2}", HttpContext.Current.Request.Url.Scheme,
                                      HttpContext.Current.Request.Url.Authority,
                                      HttpContext.Current.Request.Url.AbsolutePath));

            if (!virtualPath.EndsWith("/"))
            {
                virtualPath += "/";
            }

            var locations = new[]
            {
                virtualPath + context.HttpStatusCodeName + ".aspx",
                virtualPath + context.HttpStatusCodeName + ".html",
                virtualPath + "error.aspx",
                virtualPath + "error.html"
            };

            var virtualFilePath = "";

            foreach (var location in locations)
            {
                if (HostingEnvironment.VirtualPathProvider.FileExists(location))
                {
                    virtualFilePath = location;
                    break;
                }
            }

            if (virtualFilePath == "")
            {
                throw new ConfigurationErrorsException("Failed to find an error page in " + virtualPath);
            }

            var sb = new StringBuilder();
            var sw = new StringWriter(sb);

            if (virtualFilePath.EndsWith(".aspx"))
            {
                var request     = new HttpRequest(null, url.ToString(), "");
                var response    = new HttpResponse(sw);
                var httpContext = new HttpContext(request, response);
                httpContext.Items["ErrorReportContext"] = context;
                httpContext.Items["ErrorContext"]       = context;
                httpContext.Items["Exception"]          = context.Exception;

                var pageType = BuildManager.GetCompiledType(virtualFilePath);
                var pageObj  = Activator.CreateInstance(pageType);

                var exceptionProperty = pageObj.GetType().GetProperty("Exception");
                if (exceptionProperty != null && exceptionProperty.PropertyType == typeof(Exception))
                {
                    exceptionProperty.SetValue(pageObj, context.Exception, null);
                }

                var contextProperty = pageObj.GetType().GetProperty("ExceptionContext");
                if (contextProperty != null && contextProperty.PropertyType == typeof(HttpErrorReporterContext))
                {
                    contextProperty.SetValue(pageObj, context, null);
                }

                contextProperty = pageObj.GetType().GetProperty("ErrorContext");
                if (contextProperty != null && contextProperty.PropertyType == typeof(HttpErrorReporterContext))
                {
                    contextProperty.SetValue(pageObj, context, null);
                }


                var executeMethod = pageType.GetMethod("Execute", new Type[0]);

                // support for web pages in the future?
                if (executeMethod != null && false)
                {
                    executeMethod.Invoke(pageObj, new object[0]);
                }
                var page = (Page)pageObj;
                page.ProcessRequest(httpContext);
            }
            else if (virtualFilePath.EndsWith(".html"))
            {
                //VirtualPathUtility.ToAbsolute is really required if you do not want ASP.NET to complain about the path.
                using (
                    var stream =
                        VirtualPathProvider.OpenFile(
                            VirtualPathUtility.ToAbsolute(virtualFilePath)))
                {
                    var reader = new StreamReader(stream);
                    return(reader.ReadToEnd());
                }
            }

            return(sb.ToString());
        }