private static string ResolveRelativePath(HttpServerUtilityBase server, string physicalPath) { //C:\@Projects\Tarts\Tarts.Web\assets\images\large\1040c396-c558-473e-a3ca-f20de6ab13d2.jpg string relative = "~/assets/images"; string physical = server.MapPath(relative); return physicalPath.Replace(physical, relative).Replace("\\", "/").Replace("~",""); }
public Image SaveImage(HttpServerUtilityBase server, HttpPostedFileBase file) { string largeUploadFolder = server.MapPath("~/assets/images/large"); string mediumUploadFolder = server.MapPath("~/assets/images/medium"); string thumbUploadFolder = server.MapPath("~/assets/images/thumb"); if (!Directory.Exists(largeUploadFolder)) Directory.CreateDirectory(largeUploadFolder); if (!Directory.Exists(mediumUploadFolder)) Directory.CreateDirectory(mediumUploadFolder); if (!Directory.Exists(thumbUploadFolder)) Directory.CreateDirectory(thumbUploadFolder); //The resizing settings can specify any of 30 commands.. See http://imageresizing.net for details. ResizeSettings largeSettings = new ResizeSettings("maxwidth=800&maxheight=800"); ResizeSettings mediumSettings = new ResizeSettings("maxwidth=300&maxheight=300&scale=both"); ResizeSettings thumbSettings = new ResizeSettings("width=100&height=100&crop=auto"); //var uniqueName = System.Guid.NewGuid().ToString(); string uniqueName = PathUtils.RemoveExtension(file.FileName) + "_" + DateTime.Now.ToString("dd-MM-yyyy_HH-mm-ss"); string largeFilePath = Path.Combine(largeUploadFolder, uniqueName); string mediumFilePath = Path.Combine(mediumUploadFolder, uniqueName); string thumbFilePath = Path.Combine(thumbUploadFolder, uniqueName); //Let the image builder add the correct extension based on the output file type (which may differ). var large = ImageBuilder.Current.Build(file, largeFilePath, largeSettings, false, true); var med = ImageBuilder.Current.Build(file, mediumFilePath, mediumSettings, false, true); var thumb = ImageBuilder.Current.Build(file, thumbFilePath, thumbSettings, false, true); Image img = new Image(PathUtils.RemoveExtension(file.FileName), ResolveRelativePath(server, large), ResolveRelativePath(server, med), ResolveRelativePath(server, thumb)); Repo.Save(img); return img; }
public void Delete(HttpServerUtilityBase server, Image img) { try { System.IO.File.Delete(server.MapPath(img.Large)); } catch {} try { System.IO.File.Delete(server.MapPath(img.Medium)); } catch {} try { System.IO.File.Delete(server.MapPath(img.Thumb)); } catch {} Repo.Delete(img); }
private Album CreateAlbumWithMockFile( AlbumRepository repo, HttpServerUtilityBase server, Mock<HttpPostedFileBase> mock ) { Album album = repo.CreateAlbum( new BackOffice.Model.Album { Duration = TimeSpan.FromHours( 2 ), Title = RandomName(), Artist = new BackOffice.Model.Artist { Name = RandomName() }, ReleaseDate = DateTime.UtcNow, Type = "Hip-Hop US", Tracks = new List<Track> { new Track { Number = 1, Duration = TimeSpan.FromMinutes(4), File = mock.Object, Song = new Song { Name = RandomName(), Composed = new DateTime(2010,1,12) } } } }, server ); return album; }
public void deleteFolder(HttpRequestBase Request, HttpServerUtilityBase Server) { //dbContext = new PAWA.DAL.PAWAContext(); IEnumerable<Folder> folders = GetFolders(); int foldersIndex = 0; string selectedValue; while (foldersIndex < folders.Count()) { selectedValue = Request.Form[folders.ElementAt(foldersIndex).FolderID.ToString() + "_folder"]; int folderID = folders.ElementAt(foldersIndex).FolderID; if (selectedValue != null && selectedValue.Equals("on")) { Folder delFolder = folders.ElementAt(foldersIndex); deleteFolderChain(delFolder); } else { foldersIndex++; } } }
public ProcessResult EditRegion(int id, string nameRus, string nameEng, int countryId, HttpPostedFileBase imageUpload, bool deleteImage, HttpServerUtilityBase server) { Region region = GetRegion(id); if (String.IsNullOrEmpty(nameRus) || String.IsNullOrEmpty(nameEng)) return ProcessResults.TitleCannotBeEmpty; if (region == null) return ProcessResults.NoSuchRegion; Region r = GetRegion(nameRus, nameEng, countryId); if (r != null && r.Id != region.Id) return ProcessResults.RegionAlreadyExists; region.Translation.En = nameEng; region.Translation.Ru = nameRus; region.CountryId = countryId; if (deleteImage && imageUpload == null) { DeleteImage(region.Image, server); region.Image = null; } else if (imageUpload != null) { if (imageUpload.ContentLength <= 0 || !SecurityManager.IsImage(imageUpload)) return ProcessResults.InvalidImageFormat; region.Image = SaveImage(region.Id, StaticSettings.RegionsUploadFolderPath, imageUpload, server); } Data.SaveChanges(); ProcessResult result = ProcessResults.RegionEdited; result.AffectedObjectId = region.Id; return result; }
/// <summary> /// Prepares the excel. /// </summary> /// <param name="dataSet">The data set.</param> /// <param name="reportName">Name of the report.</param> /// <param name="reportTitle">The report title.</param> /// <param name="responseBase">The response base.</param> /// <param name="serverBase">The server base.</param> /// <param name="voyageIds">The voyage ids.</param> public void PrepareExcel(DataSet dataSet, string reportName, string reportTitle, HttpResponseBase responseBase, HttpServerUtilityBase serverBase, string voyageIds) { this.response = responseBase; this.server = serverBase; this.GenerateGuestReconciliationTable(dataSet, reportName, reportTitle, voyageIds); }
public RawFileRequestHandler(RequestContext requestContext) { routeData = requestContext.RouteData; response = requestContext.HttpContext.Response; request = requestContext.HttpContext.Request; server = requestContext.HttpContext.Server; }
public PRCImageCollection(HttpServerUtilityBase Server, string PRCRef) { this.PRCRef = PRCRef; this.ServerPath = new DirectoryInfo(Server.MapPath(@"~\")); this.CarouselImagesDirectoryPath = new DirectoryInfo(this.ServerPath + "CarouselImages\\" + PRCRef); this.PropertyImagesDirectoryPath = new DirectoryInfo(this.ServerPath + "PropertyImages\\" + PRCRef); //get all directories and files and create PRCImages GetAllImagesFromADirectoryAndPlaceInACollection(CarouselImagesDirectoryPath, CarouselImageList, this.CarouselImagesExists); GetAllImagesFromADirectoryAndPlaceInACollection(PropertyImagesDirectoryPath, PropertyImageList, this.PropertyImagesExists); if (CarouselImageList.Count > 0) { CarouselImagesExists = true; foreach (var image in CarouselImageList) { image.CapitalizeCamelCasedString(); } } if (PropertyImageList.Count > 0) { PropertyImagesExists = true; foreach (var image in PropertyImageList) { image.CapitalizeCamelCasedString(); } } }
public ProcessResult EditCountry(int id, string nameRus, string nameEng, HttpPostedFileBase imageUpload, bool deleteImage, HttpServerUtilityBase server) { Country country = GetCountry(id); if (String.IsNullOrEmpty(nameRus) || String.IsNullOrEmpty(nameEng)) return ProcessResults.TitleCannotBeEmpty; if (country == null) return ProcessResults.NoSuchCountry; country.Translation.En = nameEng; country.Translation.Ru = nameRus; if (deleteImage && imageUpload == null) { DeleteImage(country.Image, server); country.Image = null; } else if(imageUpload!=null) { if (imageUpload.ContentLength <= 0 || !SecurityManager.IsImage(imageUpload)) return ProcessResults.InvalidImageFormat; country.Image = SaveImage(country.Id, StaticSettings.CountriesUploadFolderPath, imageUpload, server); } Data.SaveChanges(); ProcessResult result = ProcessResults.CountryEdited; result.AffectedObjectId = country.Id; return result; }
/// <summary> /// Calculate a unique filename representing this request. /// </summary> public string getCacheFilename(string query, bool withGzip, HttpServerUtilityBase server) { Debug.Assert(!string.IsNullOrEmpty(cacheDir)); // // lowercase the query, and hash it // byte[] MessageBytes = Encoding.ASCII.GetBytes(query.ToLower()); SHA1Managed sha1 = new SHA1Managed(); byte[] sha1Bytes = sha1.ComputeHash(MessageBytes); StringBuilder sb = new StringBuilder(); sb.Append( Convert.ToBase64String(sha1Bytes) ); // // replace any invalid path characters // foreach(char c in Path.GetInvalidFileNameChars()) { sb.Replace(c, '_'); } // // use a distinct key for gzipped content // if (withGzip) { sb.Append(".gz"); } string relPath = Path.Combine(cacheDir, sb.ToString()); return server.MapPath(relPath); }
internal Firma SwtorzFirme(HttpServerUtilityBase server, HttpPostedFileBase uploadFile) { string url = string.Empty; if (uploadFile != null && uploadFile.FileName != string.Empty) { url = Path.Combine(server.MapPath("~/Images/firmy"), uploadFile.FileName); uploadFile.SaveAs(url); url = Path.Combine("../Images/firmy", uploadFile.FileName); } Firma firma = new Firma { nazwa = nazwa, zdjecie = url, adres = new Adres { ulica = ulica, numer_budynku = numer_budynku, numer_lokalu = numer_lokalu, }, kontakt = new Kontakt { mail = mail, numer_komurkowy = numer_komurkowy }, }; return firma; }
public Boolean delete_mvc_use_only(int id, HttpServerUtilityBase server_context) { try { HinhAnh kq = this.get_by_id(id); if (kq == null) return false; //first delete file try { String directory = "~/_Upload/HinhAnh/"; System.IO.File.Delete(server_context.MapPath(Path.Combine(directory, kq.duongdan))); System.IO.File.Delete(server_context.MapPath(Path.Combine(directory, kq.duongdan_thumb))); } catch (Exception ex) { Debug.WriteLine("qqqqqqqqqqqq"+ex.ToString()); } //delete in database _db.ds_hinhanh.Remove(kq); _db.SaveChanges(); return true; } catch (Exception ex) { Debug.WriteLine(ex.ToString()); return false; } }
private static string GetEntryPoint(HttpServerUtilityBase server, string filePath, string root) { var fileName = PathHelpers.GetExactFilePath(filePath); var folder = server.MapPath(root); return PathHelpers.GetRequireRelativePath(folder, fileName); }
public EventCategorySingleViewModel(string category, HttpServerUtilityBase server) { _server = server; category = formatCategoryString(category); //ImageList = getImageList(); using (var context = new DataContext()) { var tomorrow = DateTime.Now.Date; TheCategory = context.EventCategories.FirstOrDefault(x => x.CategoryName == category); EventRoll = context.Events.Where(x => x.MainCategory == category && x.IsActive == true && DateTime.Compare(x.EndDate.Value, tomorrow) >= 0).ToList(); // Set a random picture on the eventRoll if none is currently set //foreach (var event in EventRoll) //{ // if (String.IsNullOrEmpty(event.ImageUrl)) // { // event.ImageUrl = getRandomImage(); // } //} } }
public FakeHttpContext( IPrincipal principal, IFormParamsProvider formParams, IQueryStringParamsProvider queryStringParams, ICookieProvider cookies, IServerVariablesParamsProvider serverVariablesParams, IHeadersParamsProvider headersParams, SessionStateItemCollection sessionItems, HttpServerUtilityBase server, FakeHttpRequest request, IHttpContextBehavior contextBehavior) { User = principal; _sessionItems = sessionItems ?? new SessionStateItemCollection(); _request = request ?? new FakeHttpRequest(formParams, queryStringParams, cookies, serverVariablesParams, headersParams); _request.SetIsAuthenticated(User.Identity != null ? User.Identity.IsAuthenticated : false); _server = server ?? new Mock<HttpServerUtilityBase>().Object; var httpResponse = new Mock<HttpResponseBase>(); httpResponse.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(s => s); _response = httpResponse.Object; _behavior = contextBehavior; _items = new Hashtable(); }
public ProcessResult AddPlace(Place place, HttpPostedFileBase imageUpload, HttpServerUtilityBase server) { if (Translation.IsInValid(place.Translation) || Translation.IsInValid(place.Translation1)) return ProcessResults.InvalidTranslations; if (GetPlace(place.Translation, place.RegionId) != null) return ProcessResults.PlaceAlreadyExists; var t = Data.Translations.Add(place.Translation); Data.SaveChanges(); place.Name = t.Id; t = Data.Translations.Add(t); Data.SaveChanges(); place.Description = t.Id; place = Data.Places.Add(place); try { Data.SaveChanges(); } catch (Exception) { Data.Places.Remove(place); Data.SaveChanges(); return ProcessResults.Error; } if (imageUpload != null) { if (imageUpload.ContentLength <= 0 || !SecurityManager.IsImage(imageUpload)) return ProcessResults.InvalidImageFormat; place.Image = SaveImage(place.Id, StaticSettings.PlacesUploadFolderPath, imageUpload, server); Data.SaveChanges(); } ProcessResult result = ProcessResults.PlaceAdded; result.AffectedObjectId = place.Id; return result; }
public static ActionResult GetFile(HttpResponseBase Response, HttpRequestBase Request, HttpServerUtilityBase Server, string filePath, string fileName, string contentType, string userFileName) { byte[] value; using (FileStream stream = System.IO.File.Open(filePath, FileMode.Open)) { value = new byte[stream.Length]; stream.Read(value, 0, (int)stream.Length); } //const string userFileName = "MissionOrder.pdf"; //const string contentType = "application/pdf"; Response.Clear(); if (Request.Browser.Browser == "IE") { string attachment = String.Format("attachment; filename=\"{0}\"", Server.UrlPathEncode(userFileName)); Response.AddHeader("Content-Disposition", attachment); } else Response.AddHeader("Content-Disposition", "attachment; filename=\"" + userFileName + "\""); Response.ContentType = contentType; Response.Charset = "utf-8"; Response.HeaderEncoding = Encoding.UTF8; Response.ContentEncoding = Encoding.UTF8; Response.BinaryWrite(value); Response.End(); return null; }
private static string SetCleanExtractFolder(HttpServerUtilityBase server, string mapPath, string cleanFileNameNoExtension) { var extractFolder = server.MapPath(mapPath + cleanFileNameNoExtension); MakeOrResetDirectory(extractFolder); return extractFolder; }
/// <summary> /// Prepares the excel. /// </summary> /// <param name="dataTable">The data table.</param> /// <param name="reportName">Name of the report.</param> /// <param name="reportTitle">The report title.</param> /// <param name="responseBase">The response base.</param> /// <param name="serverBase">The server base.</param> public void PrepareExcel(DataTable dataTable, string reportName, string reportTitle, HttpResponseBase responseBase, HttpServerUtilityBase serverBase) { this.response = responseBase; this.server = serverBase; this.GenerateTable(dataTable, reportName, reportTitle); }
public FileCertificateService(HttpServerUtilityBase serverBase, IFileSystem fileSystem, string path, string password) { _serverBase = serverBase; _fileSystem = fileSystem; _path = path; _password = password; }
public DeleteGalleryCommand(ObjectRepository repository, HttpServerUtilityBase server, string galleryDirectoryPath, int galleryId, string galleryTitle) { _server = server; _targetID = galleryId; itemTitle = galleryTitle; GalleryDirectoryPath = galleryDirectoryPath; Repository = repository; }
/// <summary> /// Elimina un album e tutto il suo contenuto /// </summary> /// <param name="Server">Server object per MapPath</param> /// <param name="name">Nome dell'album (e nome cartella)</param> public static void Del(HttpServerUtilityBase Server, string name) { string path = Server.MapPath(BASE_PATH + "/" + name); if (Directory.Exists(path)) { Directory.Delete(path, true); } }
// Methods public HttpServerUtilityBaseWrapper(HttpServerUtilityBase httpServerUtility) { if (httpServerUtility == null) { throw new ArgumentNullException("httpServerUtility"); } this._httpServerUtility = httpServerUtility; }
public HttpListenerContextAdapter(HttpListenerContext context, string virtualPath, string physicalPath) { this.request = new HttpListenerRequestAdapter(context.Request, virtualPath, MakeRelativeUriFunc(context.Request.Url, virtualPath)); this.response = new HttpListenerResponseAdapter(context.Response); this.server = new ConcoctHttpServerUtility(physicalPath); this.cache = new Cache(); this.session = new HttpListenerSessionState(); }
public Artist EditArtist( Artist artist, HttpServerUtilityBase server ) { if( artist == null ) throw new ArgumentException( "Artist can't be null" ); if( server == null ) throw new ArgumentException( "Server can't be null" ); if( !ArtistExists( artist ) ) return null; return artist; }
public static ImageMetadata GetImageMetadata(HttpServerUtilityBase server, string imageUrl) { string path = server.MapPath(imageUrl + ".meta"); using (var reader = new StreamReader(path)) { return new ImageMetadata(imageUrl, reader); } }
public static void Init(HttpServerUtilityBase server) { if (Current == null) { _filePath = server.MapPath("~/App_Data/Settings.xml"); Current = GetConnexion(); } }
public string Save(HttpServerUtilityBase server, HttpPostedFileBase file) { string path = "/Images/" + file.FileName; string fullPath = server.MapPath(path); file.SaveAs(fullPath); return path; }
public static MvcHtmlString Menu_Ver2(this HtmlHelper helper) { server = helper.ViewContext.RequestContext.HttpContext.Server; request = helper.ViewContext.RequestContext.HttpContext.Request; urlHelper = new UrlHelper(helper.ViewContext.RequestContext); routeDictionary = helper.ViewContext.RequestContext.RouteData.Values; HtmlHelper htmlHelper = new HtmlHelper(helper.ViewContext, helper.ViewDataContainer); //获取当前用户信息 //TalentMISDbContext db = new TalentMISDbContext(); //string current_account = helper.ViewContext.RequestContext.HttpContext.User.Identity.Name; //Account account = db.Accounts.FirstOrDefault(x => x.UserName.Trim().ToUpper() == current_account.Trim().ToUpper()); //string roleCode = account.RoleCode; //if() //注释(无用户登录,备用) //if (HttpContext.Current.Session["CurrentUser"] == null) return new MvcHtmlString(""); //string roleCode = ((CurrentUser)HttpContext.Current.Session["CurrentUser"]).RoleCode; string roleCode = ""; //加载菜单xml文件 //string xmlPath = server.MapPath(url.Content("~/Menu.xml"));//当禁用Cookie时会话标识会嵌入URL中,此时该行代码结果就不正确了!(夏春涛) string webRootPath = server.MapPath("/"); string xmlPath = webRootPath.TrimEnd('\\') + "\\Menu_Ver2.xml"; XDocument doc = XDocument.Load(xmlPath); var xmlNav = doc.Root; //获取所有符合条件的一级菜单(其中包括所有二级菜单) var nav1Items = xmlNav .Elements("NavItem") .Where(p => p.Attribute("roles").Value.Trim() == "" || p.Attribute("roles").Value.Trim().ToUpper().Contains(roleCode.ToUpper())); foreach (var nav1 in nav1Items) { //删除一级菜单下不符合条件的二级菜单 var nav2List = nav1.Elements("NavItem").ToList(); foreach (var nav2 in nav2List) { if (nav2.Attribute("roles").Value.Trim() == "")//任意角色均可访问的二级菜单 { continue; } bool isPermitted = nav2.Attribute("roles").Value.ToUpper().Contains(roleCode.Trim().ToUpper()); if (!isPermitted)//用户角色不再许可范围内 { nav1.Elements("NavItem") .Where(p => p.Attribute("code").Value.Trim().ToUpper() == nav2.Attribute("code").Value.Trim().ToUpper()) .Remove(); } } } //如果一级菜单下面没有二级菜单,则删除该一级菜单 nav1Items.Where(p => p.Elements().Count() == 0).Remove(); //---- MvcHtmlString result = htmlHelper.Partial("Menu_Ver2", nav1Items); return result; }
/// <summary> /// 得到上传文件目录 /// </summary> /// <param name="applicationPath">应用程序路径</param> /// <param name="server">web请求服务</param> /// <param name="isOpen">是否需要对外开放,默认true</param> /// <returns>上传文件目录</returns> public static string CheckFileUpLoadDirectory(string applicationPath, System.Web.HttpServerUtilityBase server, UploadFileType type = UploadFileType.File) { string dic = server.MapPath(applicationPath + "/UploadFile/" + GetFileUpLoadPath(type)); if (!Directory.Exists(dic)) { Directory.CreateDirectory(dic); } return(dic); }
public string CreateUserFolder(System.Web.HttpServerUtilityBase server) { var virtualPath = Path.Combine(rootFolder, Path.Combine("Upload", UserID), prettyName); var path = server.MapPath(virtualPath); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); foreach (var sourceFolder in foldersToCopy) { CopyFolder(server.MapPath(sourceFolder), path); } } return(virtualPath); }
/// <summary> /// 得到照片上传文件目录 /// </summary> /// <param name="applicationPath">应用程序路径</param> /// <param name="server">web请求服务</param> /// <param name="uploadPath">要上传的目录 </param> /// <returns>返回值 照片上传文件目录</returns> public static string CheckPicUpLoadDirectory(string applicationPath, System.Web.HttpServerUtilityBase server, string uploadPath) { string dic = server.MapPath(applicationPath + uploadPath); return(CreateFilePath(dic)); }