MapPath() public method

public MapPath ( string virtualPath ) : string
virtualPath string
return string
Example #1
0
 public static int AddTalentDocument(HttpRequest req, ref string message, ref string  forwardurl)
 {
     if (req.Files[0].ContentLength != 0)
     {
         Model.TB_RC_TalentDocument model = new Model.TB_RC_TalentDocument();
         model.TD_CB_No = Convert.ToInt32(Common.Constants.getReqValue(req, "CB_No"));
         model.TD_TI_No = Convert.ToInt32(Common.Constants.getReqValue(req, "TI_No"));
         forwardurl = "TalentInfo/TalentDocument.aspx?CB_No=" + model.TD_CB_No + "&TI_No=" + model.TD_TI_No;
         var tmpext = Common.Constants.GetFileExt(req.Files[0].FileName);
         string filedir = req.MapPath("newImages") + "\\";
         string filename = DateTime.Now.ToString("yyyy-MM-dd_HH_mm_ss") + Common.Constants.getGuid() + "." + tmpext;
         req.Files[0].SaveAs(filedir + filename);
         model.TD_DocName = System.IO.Path.GetFileName(req.Files[0].FileName);
         model.TD_docPath = filename;
         model.TD_CreateDate = DateTime.Now;
         model.TD_CreatePer = "";
         tddb.Add(model); 
         message = "添加文档成功";
        
     }
     else
     { 
         message = "文件内容为空" ;
         return Common.Constants.ERR;
     }
     return Common.Constants.OK;
 }
Example #2
0
        public static string SaveUploadedFileCollection (HttpRequest request, string fieldName, string fileName)
        {
            
            IEnumerator enumerator = request.Files.GetEnumerator();
            StringBuilder filePathStringBuilder = new StringBuilder();
            string path = request.MapPath(fileName);

            try
            {
                if (!Directory.Exists(path))
                {
                    DirectoryInfo directory = Directory.CreateDirectory(path);
                }

                for (int i = 0; enumerator.MoveNext(); i++)
                {
                    string hash = new HashcodeGenerator(request.Files[i].InputStream).GetHashCode().ToString();
                    string filePath = String.Format("{0}/{1}{2}", path, hash, Path.GetExtension(request.Files[i].FileName));
                    request.Files[i].SaveAs(filePath);
                    filePathStringBuilder.Append(String.Format("{0}:{1},", Path.GetFileName(filePath), request.Files[fieldName].ContentType));
                }

                return filePathStringBuilder.ToString();
            }
            catch (Exception e)
            {
                return e.Message;
            }

        }
Example #3
0
        string GetNormalizedFileName(string fn)
        {
            if (String.IsNullOrEmpty(fn))
            {
                return(fn);
            }

            // On Linux we don't change \ to / since filenames with \ are valid. We also
            // don't remove drive: designator for the same reason.
            int len = fn.Length;

            if (len >= 3 && fn [1] == ':' && IsFileSystemDirSeparator(fn [2]))
            {
                return(Path.GetFullPath(fn));                 // drive-qualified absolute file path
            }
            bool startsWithDirSeparator = IsFileSystemDirSeparator(fn [0]);

            if (len >= 2 && startsWithDirSeparator && IsFileSystemDirSeparator(fn [1]))
            {
                return(Path.GetFullPath(fn));                 // UNC path
            }
            if (!startsWithDirSeparator)
            {
                HttpContext ctx = context ?? HttpContext.Current;
                HttpRequest req = ctx != null ? ctx.Request : null;

                if (req != null)
                {
                    return(req.MapPath(fn));
                }
            }

            return(fn);            // Or should we rather throw?
        }
Example #4
0
        internal void Execute(IHttpHandler handler, TextWriter writer, bool preserveForm, bool setPreviousPage)
        {
            HttpRequest request = this._context.Request;
            VirtualPath currentExecutionFilePathObject = request.CurrentExecutionFilePathObject;
            string      physPath = request.MapPath(currentExecutionFilePathObject);

            this.ExecuteInternal(handler, writer, preserveForm, setPreviousPage, null, currentExecutionFilePathObject, physPath, null, null);
        }
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            m_request = context.Request;
            m_response = context.Response;
            m_cookieCollection = context.Request.Cookies;
            m_asyncResult = new NuxleusAsyncResult(cb, extraData);
            HttpCookie sessionid = m_cookieCollection["sessionid"];
            HttpCookie userid = m_cookieCollection["userid"];
            HttpCookie username = m_cookieCollection["username"];
            HttpCookie name = m_cookieCollection["name"];
            HttpCookie uservalidated = m_cookieCollection["uservalidated"];

            string ip = m_request.UserHostAddress.ToString();

            NameValueCollection form = m_request.Form;
            m_returnLocation = form.Get("return-url");
            //string collection_id = form.Get("collection-id");
            string collection_name = form.Get("collection-name");
            string collection_id = Guid.NewGuid().ToString();
            string path = m_request.MapPath(String.Format("/member/{0}/media/{1}", userid.Value, collection_id));

            if (!Directory.Exists(path))
            {
                DirectoryInfo directory = Directory.CreateDirectory(path);
            }

            List<AwsSdbModel.Attribute> attributes = new List<AwsSdbModel.Attribute>();
            attributes.Add(new AwsSdbModel.Attribute { Name = "CollectionName", Value = collection_name });
            attributes.Add(new AwsSdbModel.Attribute { Name = "CollectionOwner", Value = userid.Value });

            PutAttributesTask task = new PutAttributesTask { 
                DomainName = new Domain {
                    Name = "collections" }, 
                    Item = new Item { 
                        ItemName = collection_id,
                        Attribute = attributes 
                    } 
            };
            IResponse response = task.Invoke();
            PutAttributesResult result = (PutAttributesResult)response.Result;
            foreach (string header in response.Headers)
            {
                m_response.Write(String.Format("ResponseHeader: {0}: {1}", header, response.Headers[header]));
            }
            //m_response.Write(result.Metadata.RequestId);
            WriteDebugXmlToOutputStream(attributes);
            m_asyncResult.CompleteCall();
            return m_asyncResult;
        }
Example #6
0
        public static void StreamLocalFile(string filepath, string contentType, HttpResponse response, HttpRequest request)
        {
            string fullpath = HttpContext.Current.Server.MapPath(filepath);
            string fullpath2 = request.MapPath(filepath);

            if (contentType.Length > 0)
            {
                // Set content type
                response.ContentType = "application/json";
            }

            // Cheap and cheerful - not very efficient
            // Write content as text to prevent having to worry about character encoding
            string content = File.ReadAllText(fullpath);
            response.Write(content);
        }
        private bool IsLoginPage(HttpRequest request)
        {
            try
            {
                var loginUrl = _configuration.LoginUrl;
                if (!loginUrl.StartsWith("/", StringComparison.Ordinal) && !loginUrl.StartsWith("~/"))
                {
                    loginUrl = "~/" + loginUrl;
                }

                return string.Equals(request.PhysicalPath, request.MapPath(loginUrl), StringComparison.OrdinalIgnoreCase);
            }
            catch
            {
                return false; // Cannot risk it. If any exception is thrown, err on the safe side: assume it's not the login page.
            }
        }
        internal static void ProcessRequestInternal(HttpContext context, string overrideVirtualPath)
        {
            HttpRequest  request  = context.Request;
            HttpResponse response = context.Response;

            if (!ProcessRequestForNonMapPathBasedVirtualFile(request, response, overrideVirtualPath))
            {
                string path;
                string physicalPath;
                if (overrideVirtualPath == null)
                {
                    path         = request.Path;
                    physicalPath = request.PhysicalPath;
                }
                else
                {
                    path         = overrideVirtualPath;
                    physicalPath = request.MapPath(overrideVirtualPath);
                }
                FileInfo info         = GetFileInfo(path, physicalPath, response);
                DateTime lastModified = new DateTime(info.LastWriteTime.Year, info.LastWriteTime.Month, info.LastWriteTime.Day, info.LastWriteTime.Hour, info.LastWriteTime.Minute, info.LastWriteTime.Second, 0);
                DateTime now          = DateTime.Now;
                if (lastModified > now)
                {
                    lastModified = new DateTime(now.Ticks - (now.Ticks % 0x989680L));
                }
                string etag   = GenerateETag(context, lastModified, now);
                long   length = info.Length;
                string str4   = request.Headers["Range"];
                if (!StringUtil.StringStartsWithIgnoreCase(str4, "bytes") || !ProcessRangeRequest(context, physicalPath, length, str4, etag, lastModified))
                {
                    SendFile(physicalPath, 0L, length, length, context);
                    response.ContentType = MimeMapping.GetMimeMapping(physicalPath);
                    response.AppendHeader("Accept-Ranges", "bytes");
                    response.AddFileDependency(physicalPath);
                    response.Cache.SetIgnoreRangeRequests();
                    response.Cache.SetExpires(DateTime.Now.AddDays(1.0));
                    response.Cache.SetLastModified(lastModified);
                    response.Cache.SetETag(etag);
                    response.Cache.SetCacheability(HttpCacheability.Public);
                }
            }
        }
Example #9
0
        public void Execute(string path, TextWriter writer, bool preserveForm)
        {
            if (this._context == null)
            {
                throw new HttpException(System.Web.SR.GetString("Server_not_available"));
            }
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }
            string      queryStringOverride = null;
            HttpRequest request             = this._context.Request;

            path = this._context.Response.RemoveAppPathModifier(path);
            int index = path.IndexOf('?');

            if (index >= 0)
            {
                queryStringOverride = path.Substring(index + 1);
                path = path.Substring(0, index);
            }
            if (!UrlPath.IsValidVirtualPathWithoutProtocol(path))
            {
                throw new ArgumentException(System.Web.SR.GetString("Invalid_path_for_child_request", new object[] { path }));
            }
            VirtualPath  virtualPath = VirtualPath.Create(path);
            IHttpHandler handler     = null;
            string       filename    = request.MapPath(virtualPath);
            VirtualPath  path3       = request.FilePathObject.Combine(virtualPath);

            InternalSecurityPermissions.FileReadAccess(filename).Demand();
            if (HttpRuntime.IsLegacyCas)
            {
                InternalSecurityPermissions.Unrestricted.Assert();
            }
            try
            {
                if (StringUtil.StringEndsWith(virtualPath.VirtualPathString, '.'))
                {
                    throw new HttpException(0x194, string.Empty);
                }
                bool useAppConfig = !path3.IsWithinAppRoot;
                using (new DisposableHttpContextWrapper(this._context))
                {
                    try
                    {
                        this._context.ServerExecuteDepth++;
                        if (this._context.WorkerRequest is IIS7WorkerRequest)
                        {
                            handler = this._context.ApplicationInstance.MapIntegratedHttpHandler(this._context, request.RequestType, path3, filename, useAppConfig, true);
                        }
                        else
                        {
                            handler = this._context.ApplicationInstance.MapHttpHandler(this._context, request.RequestType, path3, filename, useAppConfig);
                        }
                    }
                    finally
                    {
                        this._context.ServerExecuteDepth--;
                    }
                }
            }
            catch (Exception exception)
            {
                if (exception is HttpException)
                {
                    int httpCode = ((HttpException)exception).GetHttpCode();
                    if ((httpCode != 500) && (httpCode != 0x194))
                    {
                        exception = null;
                    }
                }
                throw new HttpException(System.Web.SR.GetString("Error_executing_child_request_for_path", new object[] { path }), exception);
            }
            this.ExecuteInternal(handler, writer, preserveForm, true, virtualPath, path3, filename, null, queryStringOverride);
        }
Example #10
0
		static BuildProvider FindBuildProviderForPhysicalPath (string path, BuildProviderGroup group, HttpRequest req)
		{
			if (req == null || String.IsNullOrEmpty (path))
				return null;

			foreach (BuildProvider bp in group) {
				if (String.Compare (path, req.MapPath (bp.VirtualPath), RuntimeHelpers.StringComparison) == 0)
					return bp;
			}
			
			return null;
		}
Example #11
0
        public static int UpdateTalentInfoBasic(HttpRequest req, ref string message)
        {
            string tmp = Common.Constants.getReqValue(req, "CB_No");
            Model.TB_CG_CityBase model = cbdb.GetModel(Convert.ToInt32(tmp));


            if (req.Files[0].ContentLength != 0)
            {
                System.Drawing.Image image = null;
                System.Drawing.Image hb = null;
                System.Drawing.Graphics g = null;
                try
                {
                    var tmpext = Common.Constants.GetFileExt(req.Files[0].FileName);
                    //req.Files[0].SaveAs(req.MapPath("../newImages") + "\\" + tparfs.TP_TeamImag);
                    string filedir = req.MapPath("newImages") + "\\";
                    string filename = tmp + "." + tmpext;
                    req.Files[0].SaveAs(filedir + filename);
                    image = System.Drawing.Image.FromFile(filedir + filename, false);
                    //System.Drawing.Image newimage = image.GetThumbnailImage(700, 400, null, new IntPtr());
                    double dVal = image.Width / 139.00;
                    hb = new System.Drawing.Bitmap(139, (int)(image.Height / dVal));//创建图片对象
                    g = System.Drawing.Graphics.FromImage(hb);//创建画板并加载空白图像
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;//设置保真模式为高度保真
                    g.DrawImage(image, new Rectangle(0, 0, 139, (int)(image.Height / dVal)), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);//开始画图
                    //2013-10-15注释
                    //model.CB_Img = "sl." + filename;
                    //hb.Save(filedir + "\\" + model.CB_Img);
                }
                finally
                {
                    image.Dispose();
                    g.Dispose();
                    hb.Dispose();
                }
            }

            model.CB_X = Common.Constants.getReqValue(req, "CB_X");
            model.CB_Y = Common.Constants.getReqValue(req, "CB_Y");
            model.CB_Name = Common.Constants.getReqValue(req, "CB_Name");
            model.cb_shopnum = Common.Constants.getReqValue(req, "CB_Num");
            //tmp = Common.Constants.getReqValue(req, "CB_Num");
            //if (tmp != "") model.CB_Num = int.Parse(tmp);
            model.CB_Num = Common.Constants.getReqValue(req, "CB_Position");
            model.cb_setup = Common.Constants.getReqValue(req, "CB_SetUp");
            model.CB_Des = Common.Constants.getReqValue(req, "CB_Des");
            model.CB_Je = Common.Constants.getReqValue(req, "CB_Je");
 
            cbcrdb.Delete(model.CB_No);//删除原有的记录
            var arrstr = Common.Constants.getReqValue(req, "TC_No");
            string[] arr;
            if (arrstr != "")
            {
                arr = arrstr.Split(',');
                foreach (var cr in arr)
                {
                    if (cr.Trim() != "")
                    {
                        var tmpModel = new Model.TB_CG_SocialWelfareLink() { CT_CB_No = model.CB_No, CT_TC_No = Convert.ToInt32(cr) };
                        if (!cbcrdb.Exists(tmpModel))
                        {
                            cbcrdb.Add(tmpModel);
                        }
                    }
                }
            }

            cbdb.Update(model);

            message = "更新公司成功";
            return Common.Constants.OK;
        }
Example #12
0
 public override string MapPath(string virtualPath)
 {
     return(_httpRequest.MapPath(virtualPath));
 }
Example #13
0
 public override string MapPath(string virtualPath)
 {
     return(w.MapPath(virtualPath));
 }
Example #14
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        public void Compress(HttpRequest request, HttpResponse response)
        {
            Encoding encoding = Encoding.GetEncoding("windows-1252");
            string enc, cacheFile = null, cacheKey = null, content = "";
            StringWriter writer = new StringWriter();
            byte[] buff = new byte[1024];
            GZipOutputStream gzipStream;
            bool supportsGzip;

            // Set response headers
            response.ContentType = "text/css";
            response.Charset = this.charset;
            response.Buffer = false;

            // Setup cache
            response.Cache.SetExpires(DateTime.Now.AddSeconds(this.ExpiresOffset));

            // Check if it supports gzip
            enc = Regex.Replace("" + request.Headers["Accept-Encoding"], @"\s+", "").ToLower();
            supportsGzip = enc.IndexOf("gzip") != -1 || request.Headers["---------------"] != null;
            enc = enc.IndexOf("x-gzip") != -1 ? "x-gzip" : "gzip";

            // Setup cache info
            if (this.diskCache) {
                cacheKey = "";

                foreach (CSSCompressItem item in this.items) {
                    // Get last mod
                    if (item.Type == CSSItemType.File) {
                        DateTime fileMod = File.GetLastWriteTime(request.MapPath(item.Value));

                        if (fileMod > this.lastUpdate)
                            this.lastUpdate = fileMod;
                    }

                    cacheKey += item.Value;
                }

                cacheKey = this.cacheFileName != null ? this.cacheFileName : MD5(cacheKey);

                if (this.gzipCompress)
                    cacheFile = request.MapPath(this.cacheDir + "/" + cacheKey + ".gz");
                else
                    cacheFile = request.MapPath(this.cacheDir + "/" + cacheKey + ".css");
            }

            // Use cached file disk cache
            if (this.diskCache && supportsGzip && File.Exists(cacheFile) && this.lastUpdate == File.GetLastWriteTime(cacheFile)) {
                if (this.gzipCompress)
                    response.AppendHeader("Content-Encoding", enc);

                response.WriteFile(cacheFile);
                return;
            }

            foreach (CSSCompressItem item in this.items) {
                if (item.Type == CSSItemType.File) {
                    StreamReader reader = new StreamReader(File.OpenRead(request.MapPath(item.Value)), System.Text.Encoding.UTF8);
                    string data;

                    if (item.RemoveWhiteSpace)
                        data = this.TrimWhiteSpace(reader.ReadToEnd());
                    else
                        data = reader.ReadToEnd();

                    if (this.convertUrls)
                        data = Regex.Replace(data, "url\\(['\"]?(?!\\/|http)", "$0" + PathUtils.ToUnixPath(Path.GetDirectoryName(item.Value)) + "/");

                    writer.Write(data);

                    reader.Close();
                } else {
                    if (item.RemoveWhiteSpace)
                        writer.Write(this.TrimWhiteSpace(item.Value));
                    else
                        writer.Write(item.Value);
                }
            }

            content = writer.ToString();

            // Generate GZIP'd content
            if (supportsGzip) {
                if (this.gzipCompress)
                    response.AppendHeader("Content-Encoding", enc);

                if (this.diskCache && cacheKey != null) {
                    try {
                        // Gzip compress
                        if (this.gzipCompress) {
                            gzipStream = new GZipOutputStream(File.Create(cacheFile));
                            buff = encoding.GetBytes(content.ToCharArray());
                            gzipStream.Write(buff, 0, buff.Length);
                            gzipStream.Close();

                            File.SetLastWriteTime(cacheFile, this.lastUpdate);
                        } else {
                            StreamWriter sw = File.CreateText(cacheFile);
                            sw.Write(content);
                            sw.Close();

                            File.SetLastWriteTime(cacheFile, this.lastUpdate);
                        }

                        // Write to stream
                        response.WriteFile(cacheFile);
                    } catch (Exception) {
                        content = "/* Not cached */" + content;
                        if (this.gzipCompress) {
                            gzipStream = new GZipOutputStream(response.OutputStream);
                            buff = encoding.GetBytes(content.ToCharArray());
                            gzipStream.Write(buff, 0, buff.Length);
                            gzipStream.Close();
                        } else {
                            response.Write(content);
                        }
                    }
                } else {
                    content = "/* Not cached */" + content;
                    gzipStream = new GZipOutputStream(response.OutputStream);
                    buff = encoding.GetBytes(content.ToCharArray());
                    gzipStream.Write(buff, 0, buff.Length);
                    gzipStream.Close();
                }
            } else {
                content = "/* Not cached */" + content;
                response.Write(content);
            }
        }
Example #15
0
        public override void Saved(HttpRequest request, string actualPath, string vpath)
        {
            #region arguments

            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            #endregion

            // once the template has been uploaded.
            // unzip the files and delete the uploaded file
            string templateName = request["uploadtemplatename"];
            string templateUrlPath = request["uploadtemplateurlPath"];
            if (string.IsNullOrEmpty(templateName))
            {
                templateName = Constants.DefaultTemplateName;
            }

            if (string.IsNullOrEmpty(templateUrlPath))
            {
                templateUrlPath = Constants.RootUrl;
            }

            //get the virtual path of the template extraction
            string templateVirtualPath = TemplatePlugin.GetTemplateVirtualPath(templateName);

            //convert virtual path to real path
            string templateExtractPath = request.MapPath(templateVirtualPath);
            logger.Log(LogLevel.Debug, "Template file uploaded at : {0}.", actualPath);

            try
            {

                string master = null;

                using (ZipFile zip = ZipFile.Read(actualPath))
                {
                    master = GetMasterFileName(zip);

                    if (Directory.Exists(templateExtractPath))
                    {
                        logger.Log(LogLevel.Info, "Cleaning folder {0}.", templateExtractPath);
                        Directory.Delete(templateExtractPath, true);
                    }

                    // create or empty the existing template data
                    if (!Directory.Exists(templateExtractPath))
                    {
                        logger.Log(LogLevel.Info, "Creating folder {0}.", templateExtractPath);
                        Directory.CreateDirectory(templateExtractPath);
                    }

                    logger.Log(LogLevel.Info, "Extracting template at folder {0}.", templateExtractPath);

                    foreach (ZipEntry entry in zip)
                    {
                        entry.Extract(templateExtractPath, ExtractExistingFileAction.OverwriteSilently);
                    }
                }

                // save the template.
                Template template = TemplatePlugin.Instance.GetTemplateUrlPath(templateUrlPath);
                Template newTemplate = new Template()
                {
                    Name = templateName,
                    TemplatePath = templateName,
                    MasterFileName = master,
                    UrlPath = templateUrlPath
                };

                if (template != null)
                {
                    //delete the existing template.
                    TemplatePlugin.Instance.Delete(template.UId);
                }

                TemplatePlugin.Instance.Add(newTemplate);
                Dictionary<string, object> properties = new Dictionary<string, object>(1);
                properties["Id"] = newTemplate.Id;
                this.Properties = properties;
                this.Success = true;
            }
            finally
            {
                //delete the uploaded zip file
                this.DeleteUploaded = true;
            }
        }
Example #16
0
 public override string MapPath(string overridePath)
 {
     return(w.MapPath(overridePath));
 }
Example #17
0
 /// <summary>
 /// Gets the absolute server path.
 /// </summary>
 /// <param name="Request">The request.</param>
 /// <returns>absolute server path</returns>
 public static string GetAbsoluteServerPath(HttpRequest Request)
 {
     string strServerPath;
     strServerPath = Request.MapPath(Request.ApplicationPath);
     if (!strServerPath.EndsWith("\\"))
     {
         strServerPath += "\\";
     }
     return strServerPath;
 }
        protected override void Process(HttpRequest request, HttpResponse response)
        {
          

            var narnoo_video_shortcode_count = request.Form["narnoo_video_shortcode_count"];
            var id = request.Form["video_id"];
            var width = request.Form["width"];
            var height = request.Form["height"];
            var operator_id = request.Form["operator_id"];
            Video video = null;

            // request video details from API

            if (operator_id.HasValue())
            {
                try
                {
                    video = this.NarnooOperatorMediaRequest.GetVideoDetails(operator_id,id);
                }
                catch (Exception ex)
                {
                    response.Write(serializer.Serialize(new { response = ex.Message }));
                    return;
                }
            }
            else
            {
                try
                {
                    video = this.NarnooMediaRequest.GetVideoDetails(id);
                }
                catch (Exception ex)
                {
                    response.Write(serializer.Serialize(new { response = ex.Message }));
                    return;
                }

            }


            var pause_image_dir = request.MapPath("/umbraco/narnoo/temp/tmp_pause_img/");   // relative directory containing temporary pause images


            if (Directory.Exists(pause_image_dir) == false)
            {
                Directory.CreateDirectory(pause_image_dir);
            }

            // need to download pause image to local server, in order to pass to flashvars
            // first we delete all previously downloaded pause image files older than 5 minutes

            foreach (var file in Directory.GetFiles(pause_image_dir))
            {
                var info = new FileInfo(file);
                if (info.LastWriteTime.AddMinutes(5) < DateTime.Now)
                {
                    File.Delete(file);
                }
            }

            Uri uri = new Uri(video.video_pause_image_path);
            string pause_image_filename = System.IO.Path.GetFileName(uri.LocalPath);

            var pause_image_fileurl = "/umbarco/narnoo/temp/tmp_pause_img/" + pause_image_filename;
            var pause_image_filepath = request.MapPath(pause_image_fileurl);


            var client = new WebClient();
            // Response.AddHeader("content-disposition", "attachment; filename=" + vide);
            client.DownloadFile(video.video_pause_image_path, pause_image_filepath);


            var content = "<script type='text/javascript'>"
            + "narnoo_video.flashvars[" + narnoo_video_shortcode_count + "].swfMovie = encodeURIComponent('" + HttpUtility.HtmlDecode(Utilities.DecodeCData(video.video_stream_path)) + "');"
            + "narnoo_video.flashvars[" + narnoo_video_shortcode_count + "].swfMovieHQ = encodeURIComponent('" + HttpUtility.HtmlDecode(Utilities.DecodeCData(video.video_hqstream_path)) + "');"
            + "narnoo_video.flashvars[" + narnoo_video_shortcode_count + "].swfThumb = encodeURIComponent('" + pause_image_fileurl + "');"
            + "</script>"
            + "<video width='" + width + "' height='" + height + "' controls='controls' poster='" + pause_image_fileurl + "'>"
            + "	<source src='" + HttpUtility.HtmlDecode(Utilities.DecodeCData(video.video_stream_path)) + "' type='video/mp4' />"
            + "  <source src='" + HttpUtility.HtmlDecode(Utilities.DecodeCData(video.video_webm_path)) + "' type='video/webm' />"
            + "	Your browser does not support the html5 video tag."
            + "</video>";

       
            response.Write(serializer.Serialize(new { response = content }));

        }
Example #19
0
        internal static void ProcessRequestInternal(HttpContext context, string overrideVirtualPath)
        {
            HttpRequest  request  = context.Request;
            HttpResponse response = context.Response;
            string       virtualPathWithPathInfo;
            string       physicalPath;
            FileInfo     fileInfo;
            long         fileLength;
            DateTime     lastModifiedInUtc;
            string       etag;
            string       rangeHeader;

            // custom virtual path providers that don't yeild a MapPathBasedVirtualFile
            // are a special case, and do not support TransmitFile, WriteFile, Range requests,
            // or the cache policy that we apply below
            if (ProcessRequestForNonMapPathBasedVirtualFile(request, response, overrideVirtualPath))
            {
                return;
            }

            if (overrideVirtualPath == null)
            {
                virtualPathWithPathInfo = request.Path;
                physicalPath            = request.PhysicalPath;
            }
            else
            {
                virtualPathWithPathInfo = overrideVirtualPath;
                physicalPath            = request.MapPath(overrideVirtualPath);
            }

            Debug.Trace("StaticFileHandler", "Path= " + virtualPathWithPathInfo + ", PhysicalPath= " + physicalPath);

            fileInfo = GetFileInfo(virtualPathWithPathInfo, physicalPath, response);

            // Determine Last Modified Time.  We might need it soon
            // if we encounter a Range: and If-Range header
            // Using UTC time to avoid daylight savings time
            lastModifiedInUtc = new DateTime(fileInfo.LastWriteTimeUtc.Year,
                                             fileInfo.LastWriteTimeUtc.Month,
                                             fileInfo.LastWriteTimeUtc.Day,
                                             fileInfo.LastWriteTimeUtc.Hour,
                                             fileInfo.LastWriteTimeUtc.Minute,
                                             fileInfo.LastWriteTimeUtc.Second,
                                             0,
                                             DateTimeKind.Utc);

            // Because we can't set a "Last-Modified" header to any time
            // in the future, check the last modified time and set it to
            // DateTime.Now if it's in the future.
            // This is to fix VSWhidbey #402323
            DateTime utcNow = DateTime.UtcNow;

            if (lastModifiedInUtc > utcNow)
            {
                // use 1 second resolution
                lastModifiedInUtc = new DateTime(utcNow.Ticks - (utcNow.Ticks % TimeSpan.TicksPerSecond), DateTimeKind.Utc);
            }

            etag       = GenerateETag(context, lastModifiedInUtc, utcNow);
            fileLength = fileInfo.Length;

            // is this a Range request?
            rangeHeader = request.Headers["Range"];
            if (StringUtil.StringStartsWithIgnoreCase(rangeHeader, "bytes") &&
                ProcessRangeRequest(context,
                                    physicalPath,
                                    fileLength,
                                    rangeHeader,
                                    etag,
                                    lastModifiedInUtc))
            {
                return;
            }

            // if we get this far, we're sending the entire file
            SendFile(physicalPath, 0, fileLength, fileLength, context);

            // Specify content type. Use extension to do the mapping
            response.ContentType = MimeMapping.GetMimeMapping(physicalPath);
            // Static file handler supports byte ranges
            response.AppendHeader("Accept-Ranges", "bytes");
            // We want to flush cache entry when static file has changed
            response.AddFileDependency(physicalPath);
            // Set IgnoreRangeRequests to avoid serving Range requests from the output cache.
            // Note that the kernel cache always ignores Range requests.
            response.Cache.SetIgnoreRangeRequests();
            // Set an expires in the future.
            response.Cache.SetExpires(utcNow.AddDays(1));
            // always set Last-Modified
            response.Cache.SetLastModified(lastModifiedInUtc);
            // always set ETag
            response.Cache.SetETag(etag);
            // always set Cache-Control to public
            response.Cache.SetCacheability(HttpCacheability.Public);
        }
Example #20
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        public void Compress(HttpRequest request, HttpResponse response)
        {
            Encoding encoding = Encoding.GetEncoding("windows-1252");
            string enc, cacheFile = null, cacheKey = null, content = "";
            StringWriter writer = new StringWriter();
            byte[] buff = new byte[1024];
            GZipOutputStream gzipStream;
            bool supportsGzip;

            // Set response headers
            response.ContentType = "text/javascript";
            response.Charset = this.charset;
            response.Buffer = false;

            // Setup cache
            response.Cache.SetExpires(DateTime.Now.AddSeconds(this.ExpiresOffset));

            // Check if it supports gzip
            enc = Regex.Replace("" + request.Headers["Accept-Encoding"], @"\s+", "").ToLower();
            supportsGzip = enc.IndexOf("gzip") != -1 || request.Headers["---------------"] != null;
            enc = enc.IndexOf("x-gzip") != -1 ? "x-gzip" : "gzip";

            // Setup cache info
            if (this.diskCache) {
                cacheKey = "";

                foreach (JSCompressItem item in this.items) {
                    // Get last mod
                    if (item.Type == JSItemType.File) {
                        DateTime fileMod = File.GetLastWriteTime(request.MapPath(item.Value));

                        if (fileMod > this.lastUpdate)
                            this.lastUpdate = fileMod;
                    }

                    cacheKey += item.Value;
                }

                cacheKey = this.cacheFileName != null ? this.cacheFileName : MD5(cacheKey);

                if (this.gzipCompress)
                    cacheFile = request.MapPath(this.cacheDir + "/" + cacheKey + ".gz");
                else
                    cacheFile = request.MapPath(this.cacheDir + "/" + cacheKey + ".js");
            }

            // Use cached file disk cache
            if (this.diskCache && supportsGzip && File.Exists(cacheFile) && this.lastUpdate == File.GetLastWriteTime(cacheFile)) {
                if (this.gzipCompress)
                    response.AppendHeader("Content-Encoding", enc);

                response.WriteFile(cacheFile);
                return;
            }

            foreach (JSCompressItem item in this.items) {
                if (item.Type == JSItemType.File) {
                    if (!File.Exists(request.MapPath(item.Value))) {
                        writer.WriteLine("alert('Could not load file: " + StringUtils.Escape(item.Value) + "');");
                        continue;
                    }

                    StreamReader reader = new StreamReader(File.OpenRead(request.MapPath(item.Value)), System.Text.Encoding.UTF8);

                    if (item.RemoveWhiteSpace) {
                        JavaScriptMinifier jsMin = new JavaScriptMinifier(reader, writer);
                        jsMin.Compress();
                    } else {
                        writer.Write('\n');
                        writer.Write(reader.ReadToEnd());
                        writer.Write(";\n");
                    }

                    reader.Close();
                } else {
                    if (item.RemoveWhiteSpace) {
                        JavaScriptMinifier jsMin = new JavaScriptMinifier(new StringReader(item.Value), writer);
                        jsMin.Compress();
                    } else {
                        writer.Write('\n');
                        writer.Write(item.Value);
                        writer.Write('\n');
                    }
                }
            }

            content = writer.ToString();

            // Generate GZIP'd content
            if (supportsGzip) {
                if (this.gzipCompress)
                    response.AppendHeader("Content-Encoding", enc);

                if (this.diskCache && cacheKey != null) {
                    try {
                        // Gzip compress
                        if (this.gzipCompress) {
                            gzipStream = new GZipOutputStream(File.Create(cacheFile));
                            buff = encoding.GetBytes(content.ToCharArray());
                            gzipStream.Write(buff, 0, buff.Length);
                            gzipStream.Close();

                            File.SetLastWriteTime(cacheFile, this.lastUpdate);
                        } else {
                            StreamWriter sw = File.CreateText(cacheFile);
                            sw.Write(content);
                            sw.Close();

                            File.SetLastWriteTime(cacheFile, this.lastUpdate);
                        }

                        // Write to stream
                        response.WriteFile(cacheFile);
                    } catch (Exception) {
                        content = "/* Not cached */" + content;
                        if (this.gzipCompress) {
                            gzipStream = new GZipOutputStream(response.OutputStream);
                            buff = encoding.GetBytes(content.ToCharArray());
                            gzipStream.Write(buff, 0, buff.Length);
                            gzipStream.Close();
                        } else {
                            response.Write(content);
                        }
                    }
                } else {
                    content = "/* Not cached */" + content;
                    gzipStream = new GZipOutputStream(response.OutputStream);
                    buff = encoding.GetBytes(content.ToCharArray());
                    gzipStream.Write(buff, 0, buff.Length);
                    gzipStream.Close();
                }
            } else {
                content = "/* Not cached */" + content;
                response.Write(content);
            }
        }
 private static string GetRealLocation(HttpRequest request, string virtualPath)
 {
     return request.MapPath(virtualPath);
 }
Example #22
0
 /// <summary>
 /// Determines if a virtual path exists physically.
 /// </summary>
 /// <param name="virtualPath">A virtual path. For example "~/hello/world/foo.aspx".</param>
 /// <param name="request">The <see cref="HttpRequest"/> used to verify the virtual path's 
 /// existance.</param>
 /// <returns>True if the virtual path has a corresponding physical path that exists.</returns>
 public static bool VirtualPathExistsPhysically(string virtualPath, HttpRequest request)
 {
     string physicalPath = request.MapPath(virtualPath);
     return File.Exists(physicalPath);
 }
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            m_request = context.Request;
            m_response = context.Response;
            m_cookieCollection = context.Request.Cookies;
            m_asyncResult = new NuxleusAsyncResult(cb, extraData);
            HttpCookie sessionid = m_cookieCollection["sessionid"];
            HttpCookie userid = m_cookieCollection["userid"];
            HttpCookie username = m_cookieCollection["username"];
            HttpCookie name = m_cookieCollection["name"];
            HttpCookie uservalidated = m_cookieCollection["uservalidated"];

            string ip = m_request.UserHostAddress.ToString();

            NameValueCollection form = m_request.Form;
            HttpFileCollection files = m_request.Files;
            m_response.Write(files.Count);

            m_returnLocation = form.Get("return-url");
            string medianame = form.Get("name");
            string description = form.Get("description");
            string collection_name = form.Get("collection-name");
            string collection_id = form.Get("collection-id");
            string tags = form.Get("tags");
            string mediaid = Guid.NewGuid().ToString();
            string virtualPath = String.Format("/member/{0}/media/{1}", userid.Value, collection_id);
            string path = m_request.MapPath(virtualPath);

            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFile postedFile = files[i];
                string localFilePath = String.Empty;
                try
                {
                    if (!Directory.Exists(path))
                    {
                        DirectoryInfo directory = Directory.CreateDirectory(path);
                    }

                    Stream fileStream = postedFile.InputStream;
                    string hash = new HashcodeGenerator(fileStream).GetHashCode().ToString();
                    string fileName = String.Format("{0}{1}", hash, Path.GetExtension(postedFile.FileName));
                    localFilePath = String.Format("{0}\\{1}", path, fileName);
                    postedFile.SaveAs(localFilePath);

                    string uri = String.Format("{0}{1}/{2}", m_baseMediaDomain, virtualPath, fileName);

                    List<AwsSdbModel.Attribute> attributes = new List<AwsSdbModel.Attribute>();
                    attributes.Add(new AwsSdbModel.Attribute { Name = "medianame", Value = medianame });
                    attributes.Add(new AwsSdbModel.Attribute { Name = "description", Value = description });
                    attributes.Add(new AwsSdbModel.Attribute { Name = "tags", Value = tags });
                    attributes.Add(new AwsSdbModel.Attribute { Name = "CollectionName", Value = collection_name });
                    attributes.Add(new AwsSdbModel.Attribute { Name = "CollectionId", Value = collection_id });
                    attributes.Add(new AwsSdbModel.Attribute { Name = "mediaid", Value = mediaid });
                    attributes.Add(new AwsSdbModel.Attribute { Name = "uri", Value = uri });
                    attributes.Add(new AwsSdbModel.Attribute { Name = "mediacreator", Value = userid.Value });

                    PutAttributesTask task = new PutAttributesTask { 
                        DomainName = new Domain { 
                            Name = "media" }, 
                            Item = new Item { 
                                ItemName = mediaid, 
                                Attribute = attributes 
                            } 
                    };

                    IResponse response = task.Invoke();
                    PutAttributesResult result = (PutAttributesResult)response.Result;
                    foreach (string header in response.Headers)
                    {
                        m_response.Write(String.Format("ResponseHeader: {0}: {1}", header, response.Headers[header]));
                    }

                    WriteDebugXmlToOutputStream(attributes);
                }
                catch (Exception e)
                {
                    m_response.Write(e.Message);
                }
            }

            m_asyncResult.CompleteCall();
            return m_asyncResult;
        }