public async Task<string> UploadImage(Stream fileStream, string fileName, FileCategory category) { if (fileStream != null && fileStream.Length > 0) { var url = await _storageClient.UploadFile(BlobContainer.Images, fileName, category.ToString().ToLower(), fileStream); return url; } return String.Empty; }
public void Create() { FileCategory cat = ctx.PostValue <FileCategory>(); if (ctx.HasErrors) { run(Add, ctx.PostInt("fileCategory.ParentId")); return; } cat.IsThumbView = ctx.PostIsCheck("fileCategory.IsThumbView"); cat.insert(); echoRedirect(lang("opok"), List); }
public void Add() { target(Create); dropList("categoryId", getRootList(), "Name=Id", ""); dropList("fileItem.LicenseTypeId", LicenseType.GetAll(), "Name=Id", ""); dropList("fileItem.Lang", FileLang.GetAll(), "Name=Name", ""); set("subCategoriesJson", FileCategory.GetSubCatsJson()); checkboxList("fileItem.PlatformIds", Platform.GetAll(), "Name=Id", ""); editor("fileItem.Description", "", "200px"); set("authInfo", AdminSecurityUtils.GetAuthCookieJson(ctx)); set("uploadLink", to(SaveUpload)); set("jsPath", sys.Path.DiskJs); }
/// <summary> /// Creates a delete action for a file. /// </summary> /// <param name="scanResults">The current scan action list to add action to.</param> /// <param name="file">The file to be deleted</param> /// <param name="fileCat">The category of the file</param> private OrgItem BuildDeleteAction(OrgPath file, FileCategory fileCat) { OrgItem newItem; if (file.AllowDelete) { newItem = new OrgItem(OrgAction.Delete, file.Path, fileCat, file.OrgFolder); newItem.Enable = true; } else { newItem = new OrgItem(OrgAction.None, file.Path, fileCat, file.OrgFolder); } return(newItem); }
protected void btnsubmit_ServerClick(object sender, EventArgs e) { try { if (btnsubmit.InnerText == "Submit") { FileCategory fileCategory = new FileCategory { FileCategoryName = txtCategoryName.Value, FileCategoryDescription = txtCategoryNamedesc.Value, CreatedDate = DateTime.Now, CreatedBy = 1 }; FileTrackingContainer entities = new FileTrackingContainer(); entities.FileCategories.Add(fileCategory); entities.SaveChanges(); resetcontrols(); Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "toastr.success('FileCategory Added sucessfully');", true); BindData(); } else if (btnsubmit.InnerText == "Update") { using (FileTrackingContainer container = new FileTrackingContainer()) { var id = int.Parse(hdnFCId.Value); var resultToUpdate = container.FileCategories.SingleOrDefault(item => item.FileCategoryId == id); if (resultToUpdate != null) { resultToUpdate.FileCategoryDescription = txtCategoryNamedesc.Value; resultToUpdate.FileCategoryName = txtCategoryName.Value; resultToUpdate.ModifiedBy = 1; resultToUpdate.ModifiedDate = DateTime.Now; } container.SaveChanges(); resetcontrols(); BindData(); } } } catch (Exception exception) { } }
public IActionResult Get(int id) { if (id < 0) { return(BadRequest()); } FileCategory item = db.FileCategories.GetItemById(id); if (item == null) { return(NotFound()); } return(Ok(item)); }
/********* ** Private methods *********/ /// <summary>Get the filter name for a category.</summary> /// <param name="category">The file category.</param> private string GetCategoryFilter(FileCategory category) { if (category == FileCategory.Deleted) { throw new NotSupportedException($"Can't use the {category} category as a filter."); } EnumMemberAttribute attribute = typeof(FileCategory).GetRuntimeField(category.ToString()).GetCustomAttribute <EnumMemberAttribute>(); if (attribute == null) { throw new NotSupportedException($"Invalid category filter '{category}'."); } return(attribute.Value.ToLower()); }
//------------------------------------------------------------------------------------------------------ public void Files() { List <FileCategory> cats = FileCategory.GetRootList(); IBlock block = getBlock("cat"); foreach (FileCategory cat in cats) { block.Set("cat.ThumbIcon", cat.ThumbIcon); block.Set("cat.Name", cat.Name); block.Set("cat.Link", to(new FileController().Category, cat.Id)); bindSubCatsFiles(block, cat); block.Next(); } }
public void Create() { FileCategory cat = ctx.PostValue <FileCategory>(); if (strUtil.IsNullOrEmpty(cat.Name)) { echoError("请填写名称"); return; } cat.IsThumbView = ctx.PostIsCheck("fileCategory.IsThumbView"); cat.insert(); echoToParentPart(lang("opok")); }
public IEnumerable <FileCategory> GetAll() { var categoryDataTable = db.GetDataTable("GetCategories", CommandType.StoredProcedure); var categories = new List <FileCategory>(); foreach (DataRow row in categoryDataTable.Rows) { var category = new FileCategory { Id = Convert.ToInt32(row["Id"]), Name = row["Name"].ToString() }; categories.Add(category); } return(categories); }
public virtual void Edit(long id) { target(Update, id); FileCategory cat = FileCategory.GetById(id); set("Name", cat.Name); String chkstr = ""; if (cat.IsThumbView == 1) { chkstr = "checked=\"checked\""; } set("checked", chkstr); }
public void Update(int id) { FileCategory c = FileCategory.GetById(id); FileCategory cat = ctx.PostValue(c) as FileCategory; if (ctx.HasErrors) { run(Edit, id); return; } cat.IsThumbView = ctx.PostIsCheck("fileCategory.IsThumbView"); cat.update(); echoRedirect(lang("opok"), List); }
public void Update(int id) { FileCategory c = FileCategory.GetById(id); FileCategory cat = ctx.PostValue(c) as FileCategory; if (strUtil.IsNullOrEmpty(cat.Name)) { echoError("请填写名称"); return; } cat.IsThumbView = ctx.PostIsCheck("fileCategory.IsThumbView"); cat.update(); echoToParentPart(lang("opok")); }
public ActionResult Upload(FileCategory FileCategory) { var file = Request.Files[0]; try { var tmp = new FileModel(); if (file.ContentLength > 0) { tmp.ID = Guid.NewGuid(); tmp.Time = DateTime.Now; tmp.Filename = System.IO.Path.GetFileNameWithoutExtension(file.FileName); tmp.Extension = System.IO.Path.GetExtension(file.FileName); tmp.ContentType = file.ContentType; tmp.UserID = CurrentUser.ID; var timestamp = Helpers.String.ToTimeStamp(DateTime.Now); var filename = timestamp + tmp.Extension; var dir = Server.MapPath("~") + @"\Temp\"; if (!System.IO.Directory.Exists(dir)) { System.IO.Directory.CreateDirectory(dir); } file.SaveAs(dir + filename); tmp.FileBlob = System.IO.File.ReadAllBytes(dir + filename); DB.Files.Add(tmp); DB.SaveChanges(); } } catch (DbEntityValidationException ex) { string msg = string.Format("ContentType:{0}\r\n", file.ContentType); foreach (var item in ex.EntityValidationErrors) { foreach (var item2 in item.ValidationErrors) { msg += string.Format("{0}:{1}\r\n", item2.PropertyName, item2.ErrorMessage); } } return(RedirectToAction("Message", "Shared", new { msg = msg })); } catch (Exception e) { return(RedirectToAction("Message", "Shared", new { msg = e.ToString() })); } return(RedirectToAction("Index", "File")); }
public virtual void Update(long id) { string name = ctx.Post("Name"); if (strUtil.IsNullOrEmpty(name)) { echoError("请填写名称"); return; } FileCategory cat = FileCategory.GetById(id); cat.Name = name; cat.IsThumbView = ctx.PostIsCheck("IsThumbView"); cat.update(); echoToParentPart(lang("opok")); }
public virtual void Create() { string name = ctx.Post("Name"); if (strUtil.IsNullOrEmpty(name)) { echoError("请填写名称"); return; } FileCategory cat = new FileCategory(); cat.Name = name; cat.IsThumbView = ctx.PostIsCheck("IsThumbView"); cat.insert(); echoToParentPart(lang("opok")); }
public FileCategory GetFileCategory() { FileCategory category = FileCategory.L; if (lines.Length >= 0 && lines.Length < 5) { category = FileCategory.XS; } else if (lines.Length >= 5 && lines.Length < 10) { category = FileCategory.S; } else if (lines.Length >= 10 && lines.Length < 15) { category = FileCategory.M; } return(category); }
public void Create() { string name = ctx.Post("Name"); if (strUtil.IsNullOrEmpty(name)) { errors.Add("ÇëÌîдÃû³Æ"); run(Add); return; } FileCategory cat = new FileCategory(); cat.Name = name; cat.IsThumbView = ctx.PostIsCheck("IsThumbView"); cat.insert(); echoRedirect(lang("opok"), List); }
public void Edit(int id) { FileCategory cat = FileCategory.GetById(id); bind(cat); List <FileCategory> cats = FileCategory.GetRootList(); dropList("fileCategory.ParentId", cats, "Name=Id", cat.ParentId); target(Update, id); String chkstr = ""; if (cat.IsThumbView == 1) { chkstr = "checked=\"checked\""; } set("checked", chkstr); }
private string GetQAEffectiveTo(string protyName, FileCategory category) { if (!category.Equals(FileCategory.RIGHTS)) { return(string.Empty); } if ((configObj.EffectiveTo + "").Trim().Length == 0) { return(string.Empty); } if ((protyName + "").Trim().Length == 0 || (protyName + "").Trim().Equals("RIC")) { return(configObj.EffectiveTo); } return(string.Empty); }
public void Category(int id) { FileCategory cat = FileCategory.GetById(id); if (cat.IsThumbView == 1) { view("ThumbList"); } else { view("List"); } set("addLink", to(Add)); DataPage <FileItem> pages = FileItem.GetPage(ctx.app.Id, id); bindList("list", "data", pages.Results, bindLink); set("page", pages.PageBar); }
public void Update(int id) { string name = ctx.Post("Name"); if (strUtil.IsNullOrEmpty(name)) { errors.Add("ÇëÌîдÃû³Æ"); run(Edit, id); return; } FileCategory cat = FileCategory.GetById(id); cat.Name = name; cat.IsThumbView = ctx.PostIsCheck("IsThumbView"); cat.update(); echoRedirect(lang("opok"), List); }
/// <summary> /// Get a file given its name /// </summary> /// <param name="name">filename to get. if it has no filename extension, one will be guessed at, ".ks" usually.</param> /// <param name="ksmDefault">true if a filename of .ksm is preferred in contexts where the extension was left off. The default is to prefer .ks</param> /// <returns>the file</returns> public override ProgramFile GetByName(string name, bool ksmDefault = false) { try { SafeHouse.Logger.Log("Archive: Getting File By Name: " + name); var fileInfo = FileSearch(name, ksmDefault); if (fileInfo == null) { return(null); } using (var infile = new BinaryReader(File.Open(fileInfo.FullName, FileMode.Open))) { byte[] fileBody = ProcessBinaryReader(infile); var retFile = new ProgramFile(fileInfo.Name); FileCategory whatKind = PersistenceUtilities.IdentifyCategory(fileBody); if (whatKind == FileCategory.KSM) { retFile.BinaryContent = fileBody; } else { retFile.StringContent = System.Text.Encoding.UTF8.GetString(fileBody); } if (retFile.Category == FileCategory.ASCII || retFile.Category == FileCategory.KERBOSCRIPT) { retFile.StringContent = retFile.StringContent.Replace("\r\n", "\n"); } base.Add(retFile, true); return(retFile); } } catch (Exception e) { SafeHouse.Logger.Log(e); return(null); } }
/// <summary> /// /// </summary> /// <param name="user"></param> /// <param name="file"></param> /// <param name="fileCategory"></param> /// <param name="recipientCount"></param> /// <param name="isOverloaded"></param> /// <returns></returns> public static bool Save(NeeoUser user, File file, FileCategory fileCategory, ushort recipientCount = 0, bool isOverloaded = true) { bool isOperationCompleted = false; file.Info.Name = NeeoUtility.IsNullOrEmpty(file.Info.Name) ? Guid.NewGuid().ToString("N") : file.Info.Name; var server = FileServerManager.GetInstance().SelectServer(); DbManager dbManager = new DbManager(); file.Info.FullPath = server.GetServerNetworkPath(); try { //file.Info.CreationTimeUtc = DateTime.UtcNow; FileManager.Save(file, FileCategory.Shared); if (dbManager.StartTransaction()) { if (dbManager.InsertSharedFileInformation(file.Info.Name, file.Info.Creator, Convert.ToUInt16(file.Info.MediaType), Convert.ToUInt16(file.Info.MimeType), Path.Combine(file.Info.FullPath, file.Info.FullName), file.Info.CreationTimeUtc, recipientCount, file.Info.Length, file.Info.Hash)) { file.Info.Url = NeeoUrlBuilder.BuildFileUrl(server.LiveDomain, file.Info.Name, FileCategory.Shared, file.Info.MediaType); dbManager.CommitTransaction(); isOperationCompleted = true; } else { dbManager.RollbackTransaction(); } } } catch (ApplicationException appException) { dbManager.RollbackTransaction(); throw; } catch (Exception exception) { dbManager.RollbackTransaction(); LogManager.CurrentInstance.ErrorLogger.LogError(MethodBase.GetCurrentMethod().DeclaringType, exception.Message, exception); throw new ApplicationException(CustomHttpStatusCode.ServerInternalError.ToString("D")); } return(isOperationCompleted); }
internal void EditFile(FileCategory fileCategory) { string path = @"C:\Users\Georg\OneDrive\OutlookHelper\"; if (fileCategory == FileCategory.Role) { path += "Roles.txt"; } else if (fileCategory == FileCategory.City) { path += "Cities.txt"; } else if (fileCategory == FileCategory.OutGoingMessage) { path += "OutGoingMessage.txt"; } System.Diagnostics.Process.Start(path); // }
public virtual void Category(long id) { FileCategory cat = FileCategory.GetById(id); if (cat.IsThumbView == 1) { view("ThumbList"); } else { view("List"); } set("addLink", to(Add)); set("lnkCateShow", to(new Admin.SubCategoryController().Files)); DataPage <FileItem> pages = FileItem.GetPage(ctx.app.Id, id); bindList("list", "data", pages.Results, bindLink); set("page", pages.PageBar); }
private void UpdateScanDirPaths() { this.ScanDirPaths.Clear(); List <OrgItem> autoMoves; List <OrgPath> paths = scan.GetFolderFiles(Settings.ScanDirectories.ToList(), true, true, out autoMoves); foreach (OrgPath path in paths) { FileCategory fileCat = FileHelper.CategorizeFile(path, path.Path); if (fileCat == FileCategory.TvVideo || fileCat == FileCategory.MovieVideo) { this.ScanDirPaths.Add(path); } } if (this.ScanDirPaths.Count > 0) { this.SelectedScanDirPath = this.ScanDirPaths[0]; } }
private LibNeeo.IO.File GetRequestedFile(string fileID, FileCategory fileCategory, MediaType mediaType) { string filePath = null; switch (fileCategory) { case FileCategory.Shared: return(SharedMedia.GetMedia(fileID, mediaType)); break; case FileCategory.Group: return(NeeoGroup.GetGroupIcon(fileID)); break; default: return(null); } }
public static String GetSubCategories(MvcContext ctx, FileCategory c) { long rootId = c.Id; if (c.ParentId > 0) { rootId = c.ParentId; } StringBuilder sb = new StringBuilder(); List <FileCategory> subs = FileCategory.GetByParentId(rootId); foreach (FileCategory sub in subs) { sb.AppendFormat("<a href=\"{0}\">{1}</a> ", ctx.link.To(new CategoryController().Show, sub.Id), sub.Name); } return(sb.ToString()); }
public static string Preprocess(this string content, FileCategory category, Config config) { // 特殊符号(元素名称等)替换 foreach (var mapping in config.CharatcerReplacement) { if (content.Contains(mapping.Key)) { Log.Information("正在进行特殊符号替换:{0} -> {1}", mapping.Key, mapping.Value); } if ((category & FileCategory.JsonAlike) == FileCategory.JsonAlike) { // 替换为 unicode 转义码 content = content.Replace(mapping.Key, mapping.Value); } else { // 替换为 unicode 字符 content = content.Replace(mapping.Key, Regex.Unescape(mapping.Value)); } } return(content); }
/// <summary> /// /// </summary> /// <param name="fileName"></param> /// <param name="fileCategory"></param> /// <returns></returns> public static bool Delete(string fileName, FileCategory fileCategory) { string path = ""; bool isDeleted = false; switch (fileCategory) { case FileCategory.Profile: path = Path.Combine(Profile.GetDirectoryPath(fileName), MediaUtility.AddFileExtension(fileName, MediaType.Image)); if (File.Exists(path)) { isDeleted = File.Delete(path); } else { isDeleted = true; } break; case FileCategory.Shared: throw new NotImplementedException(); break; case FileCategory.Group: path = Path.Combine(Group.GetDirectoryPath(fileName), MediaUtility.AddFileExtension(fileName, MediaType.Image)); if (File.Exists(path)) { isDeleted = File.Delete(path); } else { isDeleted = true; } break; } return(isDeleted); }
/// <summary> /// Creates a delete action for a file. /// </summary> /// <param name="scanResults">The current scan action list to add action to.</param> /// <param name="file">The file to be deleted</param> /// <param name="fileCat">The category of the file</param> private OrgItem BuildDeleteAction(OrgPath file, FileCategory fileCat) { OrgItem newItem; if (file.AllowDelete) { newItem = new OrgItem(OrgAction.Delete, file.Path, fileCat, file.OrgFolder); newItem.Enable = true; } else { newItem = new OrgItem(OrgAction.None, file.Path, fileCat, file.OrgFolder); } return newItem; }
/// <summary> /// Constructor for TV rename/missing check where file was found. /// </summary> /// <param name="status">Status of rename/missing</param> /// <param name="action">action to be performed</param> /// <param name="file">source path</param> /// <param name="destination">destination path</param> /// <param name="episode">TV episode for file</param> /// <param name="episode2">2nd Tv epsidoe for file</param> /// <param name="category">file category</param> public OrgItem(OrgStatus status, OrgAction action, string file, string destination, TvEpisode episode, TvEpisode episode2, FileCategory category, OrgFolder scanDir) : this(action, file, destination, episode, episode2, category, scanDir) { this.Status = status; this.Progress = 0; }
/// <summary> /// Constructor for TV rename/missing check where file was not found. /// </summary> /// <param name="status">Status of rename/missing</param> /// <param name="action">action to be performed</param> /// <param name="episode">TV episode for file</param> /// <param name="episode2">2nd Tv epsidoe for file</param> /// <param name="category">file category</param> public OrgItem(OrgStatus status, OrgAction action, TvEpisode episode, TvEpisode episode2, FileCategory category, OrgFolder scanDir, TvEpisodeTorrent torrentEp) : this() { this.Status = status; this.Progress = 0; this.Action = action; this.SourcePath = string.Empty; if (action == OrgAction.Delete) this.DestinationPath = FileHelper.DELETE_DIRECTORY; else this.DestinationPath = string.Empty; this.TvEpisode = new TvEpisode(episode); if (episode2 != null) this.TvEpisode2 = new TvEpisode(episode2); this.TorrentTvEpisode = torrentEp; this.Category = category; this.Enable = action == OrgAction.Torrent; this.ScanDirectory = scanDir; this.Number = 0; }
/// <summary> /// Constructor for directory scan for file that is unknown. /// </summary> /// <param name="action">action to be performed</param> /// <param name="file">source path</param> /// <param name="category">file category</param> public OrgItem(OrgAction action, string file, FileCategory category, OrgFolder scanDir) : this() { this.Progress = 0; this.Action = action; this.SourcePath = file; if (action == OrgAction.Delete) this.DestinationPath = FileHelper.DELETE_DIRECTORY; else this.DestinationPath = string.Empty; this.Category = category; this.Enable = false; this.ScanDirectory = scanDir; this.Number = 0; }
/// <summary> /// Constructor for movie item. /// </summary> /// <param name="action">action to be performed</param> /// <param name="sourceFile">the source path</param> /// <param name="category">file's category</param> /// <param name="movie">Movie object related to file</param> /// <param name="destination">destination path</param> /// <param name="scanDir">path to content folder of movie</param> public OrgItem(OrgAction action, string sourceFile, FileCategory category, Movie movie, string destination, OrgFolder scanDir) : this() { this.Progress = 0; this.Action = action; this.SourcePath = sourceFile; this.Movie = movie; this.ScanDirectory = scanDir; this.DestinationPath = destination; this.Category = category; this.Enable = false; this.Number = 0; }
/// <summary> /// Constructor for directory scan for file matched to TV episode. /// </summary> /// <param name="action">action to be performed</param> /// <param name="file">source path</param> /// <param name="destination">destination path</param> /// <param name="episode">TV episode for file</param> /// <param name="episode2">2nd Tv epsidoe for file</param> /// <param name="category">file category</param> public OrgItem(OrgAction action, string file, string destination, TvEpisode episode, TvEpisode episode2, FileCategory category, OrgFolder scanDir) : this() { this.Action = action; this.SourcePath = file; this.DestinationPath = destination; this.TvEpisode = new TvEpisode(episode); this.Category = category; if (episode2 != null) this.TvEpisode2 = new TvEpisode(episode2); this.Enable = false; this.ScanDirectory = scanDir; this.Number = 0; }
/// <summary> /// Tell if there is previously saved values from a file in the user setting. /// </summary> /// <param name="category">e.g. "image", "document"</param> static public bool HaveStoredExemplar(FileCategory category) { return File.Exists(GetExemplarPath(category)); }
/// <summary> /// Uploads a file to the specified mod. /// </summary> /// <param name="p_intModKey">The key of the mod to manage.</param> /// <param name="p_strFileTitle">The title of the file.</param> /// <param name="p_fctCategory">The category to which to upload the file.</param> /// <param name="p_strDescription">The file description.</param> /// <param name="p_strFilePath">The path of the file to upload.</param> /// <param name="p_booOverwrite">Whether or not to overwrite any existing file with the given title.</param> /// <returns><lang cref="true"/> if the file uploaded; <lang cref="false"/> otherwise.</returns> /// <exception cref="FileNotFoundException">If the specified file does not exist.</exception> /// <exception cref="InvalidOperationException">Thrown if the API can't log in to the site.</exception> public bool UploadFile(Int32 p_intModKey, string p_strFileTitle, FileCategory p_fctCategory, string p_strDescription, string p_strFilePath, bool p_booOverwrite) { return false; // @fixme AssertLoggedIn(); if (!isFileTitleValid(p_strFileTitle)) throw new ArgumentException("The file title can only contain letters, numbers, spaces, hypens and underscores.", "p_strFileTitle"); if (!File.Exists(p_strFilePath)) throw new FileNotFoundException("The file to upload does not exist.", p_strFilePath); if (p_booOverwrite) DeleteFile(p_intModKey, p_strFileTitle); NameValueCollection nvc = new NameValueCollection(); nvc.Add("filename", p_strFileTitle); nvc.Add("category", ((Int32)p_fctCategory).ToString()); nvc.Add("desc", p_strDescription); string strKey = GetUploadProgressKey(p_intModKey); string strURL = String.Format("http://{0}/members/do_addfile.php?fid={1}&prog_key={2}", m_strSite, p_intModKey, strKey); nvc.Add("APC_UPLOAD_PROGRESS", strKey); string strBoundary = Guid.NewGuid().ToString().Replace("-", ""); HttpWebRequest hwrUpload = (HttpWebRequest)WebRequest.Create(strURL); hwrUpload.ContentType = "multipart/form-data; boundary=" + strBoundary; hwrUpload.Method = "POST"; hwrUpload.KeepAlive = true; hwrUpload.Credentials = System.Net.CredentialCache.DefaultCredentials; hwrUpload.CookieContainer = m_ckcCookies; hwrUpload.Timeout = System.Threading.Timeout.Infinite; hwrUpload.ReadWriteTimeout = System.Threading.Timeout.Infinite; byte[] bteBoundary = System.Text.Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n"); string strFormDataTemplate = "\r\n--" + strBoundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; using (Stream stmRequestContent = new MemoryStream()) { foreach (string strFormField in nvc.Keys) { string strFormItem = String.Format(strFormDataTemplate, strFormField, nvc[strFormField]); byte[] bteFormItem = System.Text.Encoding.UTF8.GetBytes(strFormItem); stmRequestContent.Write(bteFormItem, 0, bteFormItem.Length); } stmRequestContent.Write(bteBoundary, 0, bteBoundary.Length); string strFileHeaderTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n"; string strHeader = string.Format(strFileHeaderTemplate, "fileupload", Path.GetFileName(p_strFilePath)); byte[] bteHeader = System.Text.Encoding.UTF8.GetBytes(strHeader); stmRequestContent.Write(bteHeader, 0, bteHeader.Length); using (FileStream fstFile = new FileStream(p_strFilePath, FileMode.Open, FileAccess.Read)) { byte[] bteBuffer = new byte[1024]; Int32 intBytesRead = 0; while ((intBytesRead = fstFile.Read(bteBuffer, 0, bteBuffer.Length)) != 0) stmRequestContent.Write(bteBuffer, 0, intBytesRead); stmRequestContent.Write(bteBoundary, 0, bteBoundary.Length); fstFile.Close(); } hwrUpload.ContentLength = stmRequestContent.Length; try { stmRequestContent.Position = 0; Int32 intTotalBytesRead = 0; using (Stream stmRequest = hwrUpload.GetRequestStream()) { byte[] bteBuffer = new byte[1024]; Int32 intBytesRead = 0; while ((intBytesRead = stmRequestContent.Read(bteBuffer, 0, bteBuffer.Length)) != 0) { stmRequest.Write(bteBuffer, 0, intBytesRead); intTotalBytesRead += intBytesRead; OnUploadProgress((Int32)(intTotalBytesRead * 100 / stmRequestContent.Length)); } stmRequest.Close(); } } catch (Exception e) { throw e; } stmRequestContent.Close(); } string strReponse = null; using (WebResponse wrpUpload = hwrUpload.GetResponse()) { using (Stream stmResponse = wrpUpload.GetResponseStream()) { using (StreamReader srdResponse = new StreamReader(stmResponse)) { strReponse = srdResponse.ReadToEnd(); srdResponse.Close(); } stmResponse.Close(); } wrpUpload.Close(); } return strReponse.Contains("File added successfully to"); }
/// <summary> /// Edits a file's info. /// </summary> /// <param name="p_intModKey">The key of the mod to manage.</param> /// <param name="p_strOldFileTitle">The old title of the file.</param> /// <param name="p_strNewFileTitle">The new title of the file.</param> /// <param name="p_fctCategory">The category to which to upload the file.</param> /// <param name="p_strDescription">The file description.</param> /// <returns><lang cref="true"/> if the file info was edited; <lang cref="false"/> otherwise.</returns> /// <exception cref="FileNotFoundException">If the specified file does not exist on hte Nexus.</exception> public bool EditFile(Int32 p_intModKey, string p_strOldFileTitle, string p_strNewFileTitle, FileCategory p_fctCategory, string p_strDescription) { return false; // @fixme AssertLoggedIn(); if (!isFileTitleValid(p_strNewFileTitle)) throw new ArgumentException("The file title can only contain letters, numbers, spaces, hypens and underscores.", "p_strNewFileTitle"); string strFileKey = GetFileKey(p_intModKey, p_strOldFileTitle); if (strFileKey == null) throw new FileNotFoundException("The file does not exist."); NameValueCollection nvc = new NameValueCollection(); nvc.Add("filename", p_strNewFileTitle); nvc.Add("category", ((Int32)p_fctCategory).ToString()); nvc.Add("desc", p_strDescription); string strBoundary = Guid.NewGuid().ToString().Replace("-", ""); HttpWebRequest hwrFileEditPage = (HttpWebRequest)WebRequest.Create(String.Format("http://{0}/members/do_editfilename.php?id={1}", m_strSite, strFileKey)); hwrFileEditPage.ContentType = "multipart/form-data; boundary=" + strBoundary; hwrFileEditPage.Method = "POST"; hwrFileEditPage.KeepAlive = true; hwrFileEditPage.Credentials = System.Net.CredentialCache.DefaultCredentials; hwrFileEditPage.CookieContainer = m_ckcCookies; hwrFileEditPage.Timeout = System.Threading.Timeout.Infinite; hwrFileEditPage.ReadWriteTimeout = System.Threading.Timeout.Infinite; byte[] bteBoundary = System.Text.Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n"); string strFormDataTemplate = "\r\n--" + strBoundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; using (Stream stmRequestContent = new MemoryStream()) { foreach (string strFormField in nvc.Keys) { string strFormItem = String.Format(strFormDataTemplate, strFormField, nvc[strFormField]); byte[] bteFormItem = System.Text.Encoding.UTF8.GetBytes(strFormItem); stmRequestContent.Write(bteFormItem, 0, bteFormItem.Length); } stmRequestContent.Write(bteBoundary, 0, bteBoundary.Length); hwrFileEditPage.ContentLength = stmRequestContent.Length; try { stmRequestContent.Position = 0; Int32 intTotalBytesRead = 0; Int64 intRequestContentLength = stmRequestContent.Length; using (Stream stmRequest = hwrFileEditPage.GetRequestStream()) { byte[] bteBuffer = new byte[1024]; Int32 intBytesRead = 0; while ((intBytesRead = stmRequestContent.Read(bteBuffer, 0, bteBuffer.Length)) != 0) { stmRequest.Write(bteBuffer, 0, intBytesRead); intTotalBytesRead += intBytesRead; OnUploadProgress((Int32)(intTotalBytesRead * 100 / intRequestContentLength)); } stmRequest.Close(); } } catch (Exception e) { throw e; } stmRequestContent.Close(); } string strReponse = null; using (WebResponse wrpUpload = hwrFileEditPage.GetResponse()) { using (Stream stmResponse = wrpUpload.GetResponseStream()) { using (StreamReader srdResponse = new StreamReader(stmResponse)) { strReponse = srdResponse.ReadToEnd(); srdResponse.Close(); } stmResponse.Close(); } wrpUpload.Close(); } return strReponse.Contains("File details changed"); }
private void ProcessPath(FileCategory cat, IEnumerable<FileInfo> fileInfo, ObservableCollection<FileReport> filereport, string fileExclusions, string folderExclusions) { cat.Code = 0; cat.Comments = 0; cat.Empty = 0; cat.ExcludedFiles = 0; cat.IncludedFiles = 0; cat.TotalFiles = 0; cat.TotalLines = 0; if (!cat.Include) { return; } foreach (FileInfo f in cat.FileTypes.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).SelectMany(type => fileInfo.Where(f => f.Extension.ToLower(CultureInfo.CurrentCulture) == type.TrimStart().ToLower(CultureInfo.CurrentCulture)))) { cat.TotalFiles++; this.CountLines(f, cat, filereport, fileExclusions, folderExclusions); } cat.Code = cat.TotalLines - cat.Empty - cat.Comments; }
private static string GetExemplarPath(FileCategory category) { String appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); var path = appData.CombineForPath("palaso"); if(!Directory.Exists(path)) { Directory.CreateDirectory(path); } path = path.CombineForPath("rememberedMetadata-" + Enum.GetName(typeof(FileCategory), category) + ".xmp"); return path; }
/// <summary> /// For use on a hyperlink/button /// </summary> /// <returns></returns> static public string GetStoredExemplarSummaryString(FileCategory category) { try { var m = new Metadata(); m.LoadFromStoredExemplar(category); return string.Format("{0}/{1}/{2}", m.Creator, m.CopyrightNotice, m.License.ToString()); } catch (Exception) { return string.Empty; } }
/// <summary> /// Deletes the stored exemplar (if it exists). This can be useful if a program /// wants to establish CC-BY as the default license for a new product. /// </summary> static public void DeleteStoredExemplar(FileCategory category) { var path = GetExemplarPath(category); if (File.Exists(path)) File.Delete(path); }
/// <summary> /// Builds list of file contained in a set of organization folders. /// File search is done recursively on sub-folders if folder recursive /// property is checked. /// </summary> /// <param name="folders">Set of organization folders to get files from</param> /// <returns>List of files contained in folders</returns> public List<OrgPath> GetFolderFiles(List<OrgFolder> folders, bool fast, bool skipDatabaseMatching, out List<OrgItem> autoMoves) { autoMoves = new List<OrgItem>(); List<OrgPath> files = new List<OrgPath>(); foreach (OrgFolder folder in folders) GetFolderFiles(folder, folder.FolderPath, files, autoMoves); // Similarity checks if (!skipDatabaseMatching) { FileCategory[] fileCats = new FileCategory[files.Count]; for (int i = 1; i < files.Count; i++) { fileCats[i] = FileHelper.CategorizeFile(files[i], files[i].Path); if (fileCats[i] != FileCategory.MovieVideo && fileCats[i] != FileCategory.TvVideo) continue; for (int j = i - 1; j >= Math.Max(0, j - 50); j--) { if (scanCanceled) return files; if (fileCats[j] != FileCategory.MovieVideo && fileCats[j] != FileCategory.TvVideo) continue; if (FileHelper.PathsVerySimilar(files[i].Path, files[j].Path) || (fileCats[i] == FileCategory.TvVideo && FileHelper.TrimFromEpisodeInfo(files[i].Path) == FileHelper.TrimFromEpisodeInfo(files[j].Path))) { if (files[j].SimilarTo > 0) files[i].SimilarTo = files[j].SimilarTo; else files[i].SimilarTo = j; break; } } } } return files; }
public static bool IsBinary(FileCategory category) { return category == FileCategory.BINARY || category == FileCategory.KSM; }
/// <summary> /// Get previously saved values from a file in the user setting. /// This is used to quickly populate metadata with the values used in the past (e.g. many images will have the same illustruator, license, etc.) /// </summary> /// <param name="category">e.g. "image", "document"</param> public void LoadFromStoredExemplar(FileCategory category) { LoadXmpFile(GetExemplarPath(category)); HasChanges = true; }
private void CountLines(FileSystemInfo i, FileCategory cat, ObservableCollection<FileReport> filereport, string fileExclusions, string folderExclusions) { FileInfo thisFile = new FileInfo(i.FullName); if (!string.IsNullOrEmpty(fileExclusions)) { if (fileExclusions.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Any(s => thisFile.Name.ToLower(CultureInfo.CurrentCulture).Contains(s.ToLower(CultureInfo.CurrentCulture)))) { filereport.Add(new FileReport { File = thisFile.FullName, Extension = thisFile.Extension, Reason = "Global File Name", Status = "Excluded", Lines = 0, Category = cat.Category }); this.csvFiles.Add(new CsvFile { File = thisFile.FullName, Extension = thisFile.Extension, Reason = "Global File Name", Status = "Excluded", Lines = 0, Category = cat.Category, CreatedDateTime = thisFile.CreationTime, LastWriteTime = thisFile.LastWriteTime, Length = thisFile.Length, Parent = thisFile.Directory.Parent.Name, Directory = thisFile.Directory.Name }); cat.ExcludedFiles++; return; } } if (!string.IsNullOrEmpty(folderExclusions)) { if (folderExclusions.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Any(s => thisFile.DirectoryName.ToLower(CultureInfo.CurrentCulture).Contains(s.ToLower(CultureInfo.CurrentCulture)))) { filereport.Add(new FileReport { File = thisFile.FullName, Extension = thisFile.Extension, Reason = "Global Folder Name", Status = "Excluded", Lines = 0, Category = cat.Category }); this.csvFiles.Add(new CsvFile { File = thisFile.FullName, Extension = thisFile.Extension, Reason = "Global Folder Name", Status = "Excluded", Lines = 0, Category = cat.Category, CreatedDateTime = thisFile.CreationTime, LastWriteTime = thisFile.LastWriteTime, Length = thisFile.Length, Parent = thisFile.Directory.Parent.Name, Directory = thisFile.Directory.Name }); cat.ExcludedFiles++; return; } } if (!string.IsNullOrEmpty(cat.NameExclusions)) { if (cat.NameExclusions.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Any(s => thisFile.Name.ToLower(CultureInfo.CurrentCulture).Contains(s.ToLower(CultureInfo.CurrentCulture)))) { filereport.Add(new FileReport { File = thisFile.FullName, Extension = thisFile.Extension, Reason = "Category File Name", Status = "Excluded", Lines = 0, Category = cat.Category }); this.csvFiles.Add(new CsvFile { File = thisFile.FullName, Extension = thisFile.Extension, Reason = "Category File Name", Status = "Excluded", Lines = 0, Category = cat.Category, CreatedDateTime = thisFile.CreationTime, LastWriteTime = thisFile.LastWriteTime, Length = thisFile.Length, Parent = thisFile.Directory.Parent.Name, Directory = thisFile.Directory.Name }); cat.ExcludedFiles++; return; } } if (Math.Abs(this.largerThan) > 0 && (thisFile.Length > this.largerThan * 1024 * 1024)) { filereport.Add(new FileReport { File = thisFile.FullName, Extension = thisFile.Extension, Reason = "Large Size", Status = "Excluded", Lines = 0, Category = cat.Category }); this.csvFiles.Add(new CsvFile { File = thisFile.FullName, Extension = thisFile.Extension, Reason = "Large Size", Status = "Excluded", Lines = 0, Category = cat.Category, CreatedDateTime = thisFile.CreationTime, LastWriteTime = thisFile.LastWriteTime, Length = thisFile.Length, Parent = thisFile.Directory.Parent.Name, Directory = thisFile.Directory.Name }); cat.ExcludedFiles++; return; } if (Math.Abs(this.smallerThan) > 0 && (thisFile.Length < this.smallerThan * 1024)) { filereport.Add(new FileReport { File = thisFile.FullName, Extension = thisFile.Extension, Reason = "Small Size", Status = "Excluded", Lines = 0, Category = cat.Category }); this.csvFiles.Add(new CsvFile { File = thisFile.FullName, Extension = thisFile.Extension, Reason = "Small Size", Status = "Excluded", Lines = 0, Category = cat.Category, CreatedDateTime = thisFile.CreationTime, LastWriteTime = thisFile.LastWriteTime, Length = thisFile.Length, Parent = thisFile.Directory.Parent.Name, Directory = thisFile.Directory.Name }); cat.ExcludedFiles++; return; } bool incomment = false; bool handlemulti = !string.IsNullOrWhiteSpace(cat.MultilineCommentStart); int filelinecount = 0; foreach (string line in File.ReadLines(i.FullName)) { filelinecount++; string line1 = line; if (string.IsNullOrWhiteSpace(line)) { cat.Empty++; } else { if (handlemulti) { if (incomment) { cat.Comments++; if (line1.TrimEnd(' ').EndsWith(cat.MultilineCommentEnd, StringComparison.OrdinalIgnoreCase)) { incomment = false; } } else { if (line1.TrimStart(' ').StartsWith(cat.MultilineCommentStart, StringComparison.OrdinalIgnoreCase)) { incomment = true; cat.Comments++; if (line1.TrimEnd(' ').EndsWith(cat.MultilineCommentEnd, StringComparison.OrdinalIgnoreCase)) { incomment = false; } } else { foreach (string s in cat.SingleLineComment.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Where(s => line1.TrimStart(' ').StartsWith(s, StringComparison.OrdinalIgnoreCase))) { cat.Comments++; } } } } else { foreach (string s in cat.SingleLineComment.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Where(s => line1.TrimStart(' ').StartsWith(s, StringComparison.OrdinalIgnoreCase))) { cat.Comments++; } } } cat.TotalLines++; } filereport.Add(new FileReport { File = thisFile.FullName, Extension = thisFile.Extension, Reason = "Match", Status = "Included", Lines = filelinecount, Category = cat.Category }); this.csvFiles.Add(new CsvFile { File = thisFile.FullName, Extension = thisFile.Extension, Reason = "Match", Status = "Included", Lines = filelinecount, Category = cat.Category, CreatedDateTime = thisFile.CreationTime, LastWriteTime = thisFile.LastWriteTime, Length = thisFile.Length, Parent = thisFile.Directory.Parent.Name, Directory = thisFile.Directory.Name }); cat.IncludedFiles++; }
/// <summary> /// Save the current metadata in the user settings, so that in the future, a call to LoadFromStoredExamplar() will retrieve them. /// This is used to quickly populate metadata with the values used in the past (e.g. many images will have the same illustruator, license, etc.) /// </summary> /// <param name="category">e.g. "image", "document"</param> public void StoreAsExemplar(FileCategory category) { SaveXmpFile(GetExemplarPath(category)); }