// kontrollerar att filen existerar och återskapar de public void FilesExistt(string path, Filetype filetype) { if (filetype == Filetype.Folder) { if (!Directory.Exists(@path)) { Directory.CreateDirectory(@path); } } else if (filetype == Filetype.Txt) { if (!File.Exists(@path)) { File.CreateText(@path); } } else if (filetype == Filetype.Picture) { if (!File.Exists(path)) { Bitmap bmp = new Bitmap(20, 20); Graphics g = Graphics.FromImage(bmp); g.FillRectangle(Brushes.Green, 0, 0, 50, 50); g.Dispose(); bmp.Save(path, System.Drawing.Imaging.ImageFormat.Png); bmp.Dispose(); } } }
/// <summary> /// Get the appropriate extension for the given filetype (includes the ".") /// </summary> /// <param name="ft">The FileType to get the extension for</param> /// <returns>The extension corresponding to that filetype</returns> public static string Extension(Filetype ft) { switch (ft) { case Filetype.XML: return(".xml"); case Filetype.JOURNAL: return(".jnt"); case Filetype.MATRIX: return(".amat"); // Do we want .amat or .imat? case Filetype.PREPROCESSED_DATA: return(".xtd"); case Filetype.CONGEALER_TRAINING_DATA: return(".m4a"); case Filetype.CANONICAL_EXAMPLE: return(".cxtd"); case Filetype.FEATURESKETCH: return(".fsxml"); default: throw new Exception("File type not recognized"); } }
private void InitFile() { this.FilenameTextBlock.Width = 180; var Mime = new MimeSharp.Mime(); try { if (!File.Exists(file.RealFilePath)) { throw new Exception("Non-existant file"); } Filetype = Mime.Lookup(file.RealFilePath); foreach (KeyValuePair <string, string> pair in MimeTo) { if (Filetype.StartsWith(pair.Key)) { this.Image.Source = ((Image)this.FindResource(pair.Value)).Source; if (pair.Key == "image") { Panel.MouseMove += ImageMouseMove; } return; } } } catch (Exception) { this.Image.Source = ((Image)this.FindResource("UnknownFileImage")).Source; } }
private Filetype GetFileType(string file) { string ext = System.IO.Path.GetExtension(file); Filetype ret = ExtensionList.ExtensionToFiletype(ext, true); return(ret); }
public static async Task ShowPreview(Filetype type, string filePath, string defaultDir) { var previewData = PreviewMap[type]; string selPath; if (File.Exists(filePath)) { selPath = filePath; } else { selPath = GetFile($"Open a Kindle {previewData.Name} file...", null, "ASC files|*.asc", defaultDir); if (!selPath.Contains(previewData.Validator)) { Logger.Log($"Invalid {previewData.Name} file."); return; } } try { IPreviewForm previewForm = (IPreviewForm)Activator.CreateInstance(previewData.Form); await previewForm.Populate(selPath); //.Location = new Point(Left, Top); previewForm.ShowDialog(); } catch (Exception ex) { MessageBox.Show("Error:\r\n" + ex.Message + "\r\n" + ex.StackTrace); } }
private void Generate() { List <string> files = GetFilesToGenerate(); foreach (string file in files) { Filetype ft = GetFileType(file); if (ft == Filetype.Java) { string to_write = Indent(GetJavaSource()); WriteSourceFile(file, to_write); } else if (ft == Filetype.CPP_Class) { WriteSourceFile(file, Indent(getHeaderCommentBlock() + getHeaderBody())); WriteSourceFile(file, Indent(GetCPPSource())); } else if (ft == Filetype.CPP_Header) { WriteSourceFile(file, Indent(getHeaderCommentBlock() + getHeaderBody())); } else if (ft == Filetype.CPP_Source) { WriteSourceFile(file, Indent(GetCPPSource())); } } if (_chkOpenContainingFoldersAfterGenerating.IsChecked == true) { OpenGeneratedFileFolders(); } _lstGeneratedFiles.Clear(); }
/// <summary> /// Make sure that the given filename ends with the appropriate extension for the given filetype /// </summary> /// <param name="filename">The filename</param> /// <param name="filetype">The filetype of that file</param> /// <returns>The corrected file extension</returns> public static string EnsureExtension(string filename, Filetype filetype) { if (filename.EndsWith(Extension(filetype))) { return(filename); } return(filename + Extension(filetype)); }
/// <summary> /// Get a list of all files in a directory /// </summary> /// <param name="path"></param> /// <param name="filetype"></param> /// <param name="recursive">whether or not to search subfolders as well (default = false)</param> /// <returns>a list of filenames</returns> public static string[] AllFiles(string path, Filetype filetype, bool recursive = false) { System.IO.SearchOption options = recursive ? System.IO.SearchOption.AllDirectories : System.IO.SearchOption.TopDirectoryOnly; string pattern = "*" + Extension(filetype); return(System.IO.Directory.GetFiles(path, pattern, options)); }
public void Delete(string filename) { Filetype type = GetFileType(filename); IFileStore store; if (_files.TryGetValue(type, out store)) { store.Remove(filename); _isSandboxDirty = true; } }
/// <summary> /// Create a new problem via TeacherNewProblemViewModel /// </summary> public int CreateNewProblem(TeacherNewProblemViewModel problem) { var courseId = _courseService.GetCourseIdByCourseName(problem.CourseName); // Filetype check if (_db.Filetypes.SingleOrDefault(x => x.Type == problem.Filetype) == null) { var fileType = new Filetype { Type = problem.Filetype }; _db.Filetypes.Add(fileType); } // Language check if (_db.ProgrammingLanguages.SingleOrDefault(x => x.Language == problem.Language) == null) { var language = new ProgrammingLanguage { Language = problem.Filetype }; _db.ProgrammingLanguages.Add(language); } // Add the new problem var newProblem = new Problem { CourseId = courseId, Name = problem.Name, Description = problem.Description, Filetype = problem.Filetype, Language = problem.Language }; _db.Problems.Add(newProblem); try { _db.SaveChanges(); return(newProblem.Id); } catch (Exception e) { return(0); } }
/// <summary> /// liefert die Dateierweiterung zum Typ /// </summary> /// <param name="typ"></param> /// <returns></returns> public string GetFileExtension(Filetype typ) { switch (typ) { case Filetype.TRE: return(".TRE"); case Filetype.RGN: return(".RGN"); case Filetype.LBL: return(".LBL"); case Filetype.NET: return(".NET"); case Filetype.NOD: return(".NOD"); case Filetype.DEM: return(".DEM"); case Filetype.MAR: return(".MAR"); } return(""); }
public ioObject(String iName, ioObject.Filetype iKind) { pName = iName; pKind = iKind; }
public ActionResult SignFile(HttpPostedFileBase file) { if (file == null) { return(RedirectToAction("Index", new { mesg = $"Chọn tệp cần ký để tiếp tục" })); } var accessToken = Session["access_token"] as string; if (string.IsNullOrEmpty(accessToken)) { return(RedirectToAction("Index", new { mesg = $"Get access_token để tiếp tục" })); } #region Bước 1: Lấy danh sách chữ ký số trên hệ thống VNPT Ký số var userCert = _getAccoutCert(accessToken); if (userCert == null) { return(RedirectToAction("Index", new { mesg = $"Lỗi: {GetLastError()}" })); } // TODO: Bổ sung chức năng chọn chữ ký số cho người dùng string certID = userCert.ID; #endregion #region Bước 2: Lấy thông tin thanh toán giao dịch var servicePack = _getAccoutServicePack(accessToken); if (servicePack == null) { return(RedirectToAction("Index", new { mesg = $"Lỗi: {GetLastError()}" })); } string servicePackID = servicePack.ID; #endregion #region Đọc dữ liệu cần ký file upload Filetype fileType = null; byte[] unsignData; string signedFile = ""; using (Stream inputStream = file.InputStream) { try { if (!(inputStream is MemoryStream memoryStream)) { memoryStream = new MemoryStream(); inputStream.CopyTo(memoryStream); } unsignData = memoryStream.ToArray(); fileType = GetFileType(unsignData, file); if (fileType == null) { return(RedirectToAction("Index", new { mesg = "Định dạng chưa được hỗ trợ" })); } signedFile = file.FileName.Replace($".{fileType.Extension}", $"_signed.{fileType.Extension}"); } catch (Exception ex) { return(RedirectToAction("Index", new { mesg = $"Không thể phân tích dữ liệu cần ký: {ex.Message}" })); } } #endregion #region Bước 4: Ký dữ liệu byte[] signedBytes = null; switch (fileType.Extension) { case "pdf": signedBytes = SignHash.SignHashPdf(unsignData, servicePackID, certID, _parseCert(userCert.CertBase64), accessToken); break; case "xml": signedBytes = SignHash.SignHashXml(unsignData, servicePackID, certID, _parseCert(userCert.CertBase64), accessToken); break; case "docx": case "xlsx": case "pptx": signedBytes = SignHash.SignHashOffice(unsignData, servicePackID, certID, _parseCert(userCert.CertBase64), accessToken); break; } if (signedBytes == null) { return(RedirectToAction("Index", new { mesg = $"Lỗi ký số: {GetLastError()}" })); } #endregion return(File(signedBytes, System.Net.Mime.MediaTypeNames.Application.Octet, signedFile)); }
void ParseInto(string text, ref List <Node> nodes) { Filetype filetype = Filetype.XML; if (text.IndexOf("(dp0") == 0) { filetype = Filetype.Twine; } else if (text.IndexOf("[") == 0) { filetype = Filetype.JSON; } nodes.Clear(); switch (filetype) { case Filetype.JSON: var N = JSON.Parse(text); int c = 0; while (N[c] != null) { if (N[c]["title"] != null && N[c]["body"] != null) { nodes.Add(new Node(((string)N[c]["title"]).Trim(), ((string)(N[c]["body"])).Replace('\r', '\n'))); } c++; } break; case Filetype.XML: //var xmlParser = new XMLParser(text); //var xmlElement = xmlParser.Parse(); /* * XDocument xDoc = XDocument.Load("XMLFile1.xml"); * * var query = (from x in xDoc.Descendants("quiz").Elements("problem") * select new Question * { * question = x.Element("question").Value, * answerA = x.Element("answerA").Value, * answerB = x.Element("answerB").Value, * answerC = x.Element("answerC").Value, * answerD = x.Element("answerD").Value, * correct = x.Element("correct").Value * }).ToList(); */ break; case Filetype.Twine: string[] lines = text.Split('\n'); // get rid of tabs! for (int i = 0; i < lines.Length; i++) { lines[i] = Regex.Replace(lines[i], @"\t", ""); } ParseMode parseMode = ParseMode.None; string nodeTitle = ""; string nodeText = ""; foreach (string line in lines) { if (line.IndexOf("Tiddler") != -1) { parseMode = ParseMode.Text; } if (parseMode != ParseMode.None) { if (line[0] == 'V') { if (parseMode == ParseMode.Text) { nodeText = line.Substring(1, line.Length - 1); nodeText = nodeText.Replace("\\u000a", "\n"); nodeText = nodeText.Replace("\\u2013", "-"); parseMode = ParseMode.Title; } else if (parseMode == ParseMode.Title) { nodeTitle = line.Substring(1, line.Length - 1); } if (nodeTitle != "" && nodeText != "") { nodes.Add(new Node(nodeTitle, nodeText)); nodeText = ""; nodeTitle = ""; parseMode = ParseMode.Text; } } } } break; } }
public StdFile GetFile(Filetype typ) { return(stdfiles[(int)typ]); }
/// <summary> /// Update problem information via TeacherProblemUpdateViewModel /// </summary> public bool UpdateProblem(TeacherProblemUpdateViewModel problem) { var dbProblem = _db.Problems.SingleOrDefault(x => x.Id == problem.Id); if (dbProblem != null) { dbProblem.Description = problem.Description; dbProblem.Name = problem.Name; // Filetype check if (_db.Filetypes.SingleOrDefault(x => x.Type == problem.Filetype) == null) { var fileType = new Filetype { Type = problem.Filetype }; _db.Filetypes.Add(fileType); } dbProblem.Filetype = problem.Filetype; // Language check if (_db.ProgrammingLanguages.SingleOrDefault(x => x.Language == problem.Language) == null) { var language = new ProgrammingLanguage { Language = problem.Filetype }; _db.ProgrammingLanguages.Add(language); } dbProblem.Language = problem.Language; var dbTestCases = _db.TestCases.Where(x => x.ProblemId == problem.Id); // Delete removed test cases foreach (var dbTestCase in dbTestCases) { var found = problem.TestCases.Any(x => x.Id == dbTestCase.Id); if (!found) { _db.TestCases.Remove(dbTestCase); } } // Add new test cases foreach (var testCase in problem.TestCases.Where(x => x.Id == 0)) { _db.TestCases.Add(new TestCase { ExpectedOutput = testCase.Output, Input = testCase.Input, ProblemId = problem.Id }); } try { _db.SaveChanges(); return(true); } catch (Exception e) { return(false); } } return(false); }
public ActionResult SignPdfAdvance(HttpPostedFileBase file, HttpPostedFileBase logo) { if (file == null) { return(RedirectToAction("Index", new { mesg = $"Chọn tệp cần ký để tiếp tục" })); } var accessToken = Session["access_token"] as string; if (string.IsNullOrEmpty(accessToken)) { return(RedirectToAction("Index", new { mesg = $"Get access_token để tiếp tục" })); } #region Bước 1: Lấy danh sách chữ ký số trên hệ thống VNPT Ký số var userCert = _getAccoutCert(accessToken); if (userCert == null) { return(RedirectToAction("Index", new { mesg = $"Lỗi: {GetLastError()}" })); } // TODO: Bổ sung chức năng chọn chữ ký số cho người dùng string certID = userCert.ID; #endregion #region Bước 2: Lấy thông tin thanh toán giao dịch var servicePack = _getAccoutServicePack(accessToken); if (servicePack == null) { return(RedirectToAction("Index", new { mesg = $"Lỗi: {GetLastError()}" })); } string servicePackID = servicePack.ID; #endregion #region Đọc dữ liệu cần ký file upload Filetype fileType = null; byte[] unsignData; string signedFile = ""; using (Stream inputStream = file.InputStream) { try { if (!(inputStream is MemoryStream memoryStream)) { memoryStream = new MemoryStream(); inputStream.CopyTo(memoryStream); } unsignData = memoryStream.ToArray(); fileType = GetFileType(unsignData, file); if (fileType == null) { return(RedirectToAction("Index", new { mesg = "Định dạng chưa được hỗ trợ" })); } signedFile = file.FileName.Replace($".{fileType.Extension}", $"_signed.{fileType.Extension}"); } catch (Exception ex) { return(RedirectToAction("Index", new { mesg = $"Không thể phân tích dữ liệu cần ký: {ex.Message}" })); } } #endregion #region Bước 4: Ký dữ liệu if (fileType.Extension != "pdf") { return(RedirectToAction("Index", new { mesg = "File không đúng định dạng" })); } ; byte[] signedBytes = null; string dataBase64 = Convert.ToBase64String(unsignData); var response = CoreServiceClient.Query(new RequestMessage { RequestID = Guid.NewGuid().ToString(), ServiceID = "SignServer", FunctionName = "SignPdfAdvance", Parameter = new SignPdfAdvanceParameter { ServiceGroupID = servicePackID, CertID = certID, FileName = "sample.pdf", DataBase64 = dataBase64, VisibleType = "5", FontSize = "13", Signatures = "W3sicmVjdGFuZ2xlIjoiMzQ5LDQ4OCw1NjksNTU0IiwicGFnZSI6MX0seyJyZWN0YW5nbGUiOiI0OSw0ODgsMjY5LDU1NCIsInBhZ2UiOjF9XQ==", FontName = "Time", Comment = "W3sidGV4dCI6IkfEkC9RxJAtMDEyNyIsInJlY3RhbmdsZSI6IjkzLDcwMCwyOTMsNzIwIiwicGFnZSI6MSwiZm9udE5hbWUiOiJUaW1lIiwiZm9udFN0eWxlIjoyLCJmb250U2l6ZSI6MTMsImZvbnRDb2xvciI6IkZGMDAwMCJ9LHsidGV4dCI6IjE0IiwicmVjdGFuZ2xlIjoiMzk2LDY4MCw0MTcsNzIwIiwicGFnZSI6MSwiZm9udE5hbWUiOiJUaW1lIiwiZm9udFN0eWxlIjozLCJmb250U2l6ZSI6MTMsImZvbnRDb2xvciI6IjA2MDlGRiJ9LHsidGV4dCI6IjA1IiwicmVjdGFuZ2xlIjoiNDU1LDY4NCw0NzUsNzE5IiwicGFnZSI6MSwiZm9udE5hbWUiOiJSb2JvdG8iLCJmb250U3R5bGUiOjEsImZvbnRTaXplIjoxMCwiZm9udENvbG9yIjoiIn1d", FontStyle = "0", FontColor = "FF0000", SignatureText = "Ký bởi: Bùi Sĩ Tuấn\nChức vụ: Giám Đốc", IsDebug = "false" } }, accessToken); if (response == null) { return(RedirectToAction("Index", new { mesg = "Sign error" })); } if (response.ResponseCode == 1) { var str = JsonConvert.SerializeObject(response.Content); SignResponse acc = JsonConvert.DeserializeObject <SignResponse>(str); if (acc != null) { signedBytes = Convert.FromBase64String(acc.SignedData); } } else { return(RedirectToAction("Index", new { mesg = $"Lỗi ký số: {response.ResponseContent}" })); } if (signedBytes == null) { return(RedirectToAction("Index", new { mesg = $"Lỗi ký số: {GetLastError()}" })); } #endregion return(File(signedBytes, System.Net.Mime.MediaTypeNames.Application.Octet, signedFile)); }
public VTTTranslate(string filename, string langcode = "Detect", Filetype filetype = Filetype.vtt) { this.filename = filename; this.langcode = langcode; this.filetype = filetype; }