public async Task <IActionResult> Index(string eventId, string filename) { Event eventObj = await EventHelper.GetEventFromEventId(context, eventId); ContentFile content = await(from contentFile in context.ContentFiles where contentFile.Event == eventObj && contentFile.ShortName == filename select contentFile).SingleOrDefaultAsync(); if (content == null) { return(NotFound()); } // TODO: check whether the user is authorized to see this file. // This should be based on the FileType: // * Admins have access to all files in their event // * Authors have access to all files attached to puzzles they own // * Players can see puzzles and materials on puzzles they've unlocked // * Players can see answers after the event's AnswersAvailable time // * Players can see solve tokens on puzzles they've solved if (!await IsAuthorized(eventObj.ID, content.Puzzle, content)) { return(Unauthorized()); } return(Redirect(content.Url.ToString())); }
private HonoplayDbContext InitAndGetDbContext(out Guid tenantId, out Guid contentFileId, out int adminUserId) { var context = GetDbContext(); var salt = ByteArrayExtensions.GetRandomSalt(); var adminUser = new AdminUser { Id = 1, Email = "*****@*****.**", Password = "******".GetSHA512(salt), PasswordSalt = salt, LastPasswordChangeDateTime = DateTimeOffset.Now.AddDays(-5) }; context.AdminUsers.Add(adminUser); var tenant = new Tenant { Name = "testTenant", HostName = "localhost", CreatedBy = adminUser.Id }; context.Tenants.Add(tenant); context.TenantAdminUsers.Add(new TenantAdminUser { TenantId = tenant.Id, AdminUserId = adminUser.Id, CreatedBy = adminUser.Id }); var question = new Question { Duration = 3, Text = "testQuestion", CreatedBy = adminUser.Id, TenantId = tenant.Id }; context.Questions.Add(question); var contentFile = new ContentFile { Id = Guid.NewGuid(), CreatedBy = adminUser.Id, Data = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 }, Name = "contentFile1", ContentType = "image/jpeg", TenantId = tenant.Id }; context.ContentFiles.Add(contentFile); tenantId = tenant.Id; contentFileId = contentFile.Id; adminUserId = adminUser.Id; context.SaveChanges(); return(context); }
public ActionResult Create(ContentFileViewModel model) { if (ModelState.IsValid) { var contentFile = new ContentFile { ContentId = model.ContentId, Description = model.Description, VisitCount = 0, LikeCount = 0, FileSize = 0, Thumbnail = "", Title = model.Title, IsSelected = model.IsSelected, IsPublish = model.IsPublic, ContentText = model.ContentText != null?model.ContentText.Replace("../../content/files/editor/", "/content/files/editor/") .Replace("../content/files/editor/", "/content/files/editor/") : "", Pic = "", Type = model.Type }; _contentFileService.AddNewContentFile(contentFile, model.Photo, model.Video, model.Video2, model.Video3); return(RedirectToAction(nameof(Index), new { type = contentFile.Type })); } return(View(model)); }
public EmpresaModuleUpdateContrato(ICommandUpdateEmpresaContrato command, IFileGetter fileGetter) { Put["/enterprise/{rtn}/contract/{contract:guid}"] = parameters => { var rtn = parameters.rtn; var contractId = parameters.contract; if (fileGetter.existsFile(DirectorioContratoEmpresas, contractId.ToString(), Extension)) { var rtnEmpresa = new RTN(rtn); if (rtnEmpresa.isRTNValid()) { if (command.isExecutable(rtnEmpresa)) { var data = fileGetter.getFile(DirectorioContratoEmpresas, contractId, Extension); var contentFile = new ContentFile(data); command.execute(rtnEmpresa, contentFile); fileGetter.deleteFile(DirectorioContratoEmpresas, contractId, Extension); return(Response.AsJson(contentFile.Id) .WithStatusCode(HttpStatusCode.OK)); } } } return(new Response() .WithStatusCode(HttpStatusCode.BadRequest)); }; }
// Token: 0x0600108A RID: 4234 RVA: 0x0006CD48 File Offset: 0x0006B148 public ContentBrowserFileButton(ContentFile newFile) { this.file = newFile; Sleek2Label sleek2Label = new Sleek2Label(); sleek2Label.transform.reset(); sleek2Label.textComponent.text = this.file.name; sleek2Label.textComponent.color = Sleek2Config.darkTextColor; this.addElement(sleek2Label); Type guessedType = this.file.guessedType; if (guessedType == null) { return; } Type type = typeof(ContentReference <>).MakeGenericType(new Type[] { guessedType }); this.dragable = base.gameObject.AddComponent <DragableSystemObject>(); this.dragable.target = base.transform; this.dragable.source = Activator.CreateInstance(type, new object[] { this.file.rootDirectory.name, this.file.path }); }
/// <summary> /// Use the Gallio's plumbing to locate Files /// </summary> private XDocument OpenXDocument(string FilePath, ICodeElementInfo codeElement) { using (TextReader reader = new ContentFile(FilePath).OpenTextReader()) { return(XDocument.Load(reader)); } }
public ContentFileRepositoryModel(string path, string contentType, ContentFile file, bool ok) { Path = path; ContentType = contentType; File = file; Ok = ok; }
private static bool CheckMatch( ContentFile addonFile, IReadOnlyCollection <Regex> pathMatchers, IReadOnlyCollection <Regex> contentMatchers) { if (pathMatchers.Count == 0 && contentMatchers.Count == 0) { return(true); } if (pathMatchers.Count > 0) { var path = addonFile.Path; if (pathMatchers.Any(matcher => !matcher.IsMatch(path))) { return(false); } } if (contentMatchers.Count > 0) { var content = Encoding.UTF8.GetString(addonFile.Content); if (contentMatchers.Any(matcher => !matcher.IsMatch(content))) { return(false); } } return(true); }
private void button_Click(object sender, RoutedEventArgs e) { if (MessageBox.Show("Are you sure you want to change your login?", "Change Login", MessageBoxButton.YesNo) == MessageBoxResult.Yes) { string password; while (true) { password = Microsoft.VisualBasic.Interaction.InputBox("Please enter your password to continue", "Change Login"); if (string.IsNullOrWhiteSpace(password)) { break; } else { byte[] pass = Encoding.ASCII.GetBytes(password); HMACSHA512 hmac1 = new HMACSHA512(pass); StringBuilder sb = new StringBuilder(); byte[] passHash = hmac1.ComputeHash(pass); foreach (byte b in passHash) { sb.Append((char)b); } if (sb.ToString() == Properties.Settings.Default.Password) { break; } else { MessageBox.Show("Password was incorrect", "Change Login"); } } } if (string.IsNullOrWhiteSpace(password)) { MessageBox.Show("Login was not reset", "Change Login"); return; } //Decrypt data and prepare for re-encryption if (!ContentFile.CheckValidity()) { ContentFile.Decrypt(password); } else { ContentFile.Archive = ZipFile.Open(ContentFile.ContentPath, ZipArchiveMode.Update); } //TODO - MOVE TO CONTENT FILE Properties.Settings.Default.Password = ""; Properties.Settings.Default.Username = ""; Properties.Settings.Default.Save(); Paging.LoadPage(Pages.Register); } else { MessageBox.Show("Login was not reset"); } }
/// <summary> /// Extracts the contents of a zip file and uploads the contents into a single directory /// </summary> private async Task UploadZipAsync(IFormFile uploadedFile, ContentFileType fileType) { ZipArchive archive = new ZipArchive(uploadedFile.OpenReadStream(), ZipArchiveMode.Read); Dictionary <string, Stream> contents = new Dictionary <string, Stream>(); foreach (ZipArchiveEntry entry in archive.Entries) { string fileName = WebUtility.UrlEncode(Path.GetFileName(entry.Name)); contents[fileName] = entry.Open(); } Dictionary <string, Uri> fileUrls = await FileManager.UploadBlobsAsync(contents, Event.ID); foreach (KeyValuePair <string, Uri> fileUrl in fileUrls) { ContentFile file = new ContentFile() { ShortName = fileUrl.Key, Puzzle = Puzzle, Event = Event, FileType = fileType, Url = fileUrl.Value, }; _context.ContentFiles.Add(file); } }
public DocxParser(string fileName) { path = Path.GetTempPath() + Path.DirectorySeparatorChar + "tmp-" + DateTime.Now.Ticks.ToString(); File.Copy(fileName, path); doc = WordprocessingDocument.Open(path, true); parsedFile = new ContentFile() { contentRaw = doc.MainDocumentPart.Document.InnerXml, contentText = ParseFileContent(XElement.Parse(doc.MainDocumentPart.Document.InnerXml)) }; SetMetadata(MetadataType.Author, doc.PackageProperties.Creator); SetMetadata(MetadataType.Description, doc.PackageProperties.Description); SetMetadata(MetadataType.Language, doc.PackageProperties.Language); SetMetadata(MetadataType.Subject, doc.PackageProperties.Subject); SetMetadata(MetadataType.Title, doc.PackageProperties.Title); SetMetadata(MetadataType.Type, doc.PackageProperties.ContentType); if (doc.PackageProperties.Created.HasValue) { SetMetadata(MetadataType.PublishDate, doc.PackageProperties.Created.Value.ToString()); } LoadAllMetadata(); }
/// <summary> /// Function to save the current content. /// </summary> /// <param name="persistMetaData">[Optional] TRUE to persist the meta data for the file, FALSE to leave it.</param> public static void Save(bool persistMetaData = true) { if ((Current == null) || (ContentFile == null)) { return; } // Write the content out to the scratch file system. using (var contentStream = ContentFile.OpenStream(true)) { Current.Persist(contentStream); } // Save any metadata. if (!persistMetaData) { return; } EditorMetaDataFile.Save(); if (ContentSaved == null) { return; } ContentSaved(); }
public EmpleoModuleUpdateImagenComprobantePago(ICommandUpdateEmpleoImagenComprobantePago command, IFileGetter fileGetter) { Put["/enterprise/empleos/{id:guid}/Comprobante/{comprobante:guid}/Imagen/{imagen:guid}"] = parameters => { var empleoId = parameters.id; var comprobanteId = parameters.comprobante; var imagenId = parameters.imagen; if (fileGetter.existsFile(DirectorioArchivosVouchers, imagenId.ToString(), Extension)) { if (command.isExecutable(empleoId, comprobanteId)) { var data = fileGetter.getFile(DirectorioArchivosVouchers, imagenId.ToString(), Extension); var contentFile = new ContentFile(data); command.execute(empleoId, comprobanteId, contentFile); fileGetter.deleteFile(DirectorioArchivosVouchers, imagenId.ToString(), Extension); return(Response.AsJson(contentFile.Id) .WithStatusCode(HttpStatusCode.OK)); } } return(new Response() .WithStatusCode(HttpStatusCode.BadRequest)); }; }
private void add(string username, string password) { byte[] pass = Encoding.ASCII.GetBytes(password); HMACSHA512 hmac1 = new HMACSHA512(new byte[] { 0xBA, 0x43, 0xB7, 0x3E, 0xCB }); StringBuilder sb = new StringBuilder(); byte[] passHash = hmac1.ComputeHash(pass); foreach (byte b in passHash) { sb.Append((char)b); } Properties.Settings.Default.Password = sb.ToString(); sb.Clear(); HMACSHA384 hmac2 = new HMACSHA384(passHash); byte[] key = hmac2.ComputeHash(pass); for (int i = 0; i < username.Length; i++) { sb.Append((char)((byte)username[i] ^ key[i % key.Length])); } Properties.Settings.Default.Username = sb.ToString(); Properties.Settings.Default.Save(); ContentFile.Encrypt(password); MessageBox.Show("Registered your user!"); Paging.LoadPage(Pages.Login); }
private ContentFile CreateContentFile(string folder) { var files = Directory.GetFiles(folder); var filteredFiles = files.Where(d => GeneratorModule.SupportedFormats.ContainsKey(Path.GetExtension(d))).ToArray(); var fileWithFormatInfo = filteredFiles.Select(d => new { file = d, info = ImageHelper.GetFormatInfo(d) }); var contentFile = new ContentFile() { Info = new ContentFileInfo() { Author = "xcode", Version = 1 } }; var fileInfos = new ContentFileImage[filteredFiles.Length]; var arrIndex = 0; var scaleIndex = 0; foreach (var group in fileWithFormatInfo.GroupBy(d => d.info.Width)) { scaleIndex++; foreach (var section in group) { fileInfos[arrIndex] = new ContentFileImage(Path.GetFileName(section.file), "universal", $"{scaleIndex}x"); arrIndex++; } } contentFile.Images = fileInfos; return(contentFile); }
/// <summary> /// Gets the <see cref="BitmapImage"/> referred to by this data /// </summary> /// <returns>The image as a <see cref="BitmapImage"/></returns> public BitmapImage GetImage() { if (ContentFile.CheckValidity()) { ContentFile.SetArchiveRead(); ZipArchiveEntry entry = ContentFile.Archive.GetEntry(ID); if (entry == null) { throw new FileNotFoundException("Image was not found within the database", ID); } else { using Stream zipStream = entry.Open(); using MemoryStream ms = new MemoryStream(); zipStream.CopyTo(ms); ms.Position = 0; BitmapImage bmp = new BitmapImage(); bmp.BeginInit(); bmp.CacheOption = BitmapCacheOption.OnLoad; bmp.StreamSource = ms; bmp.EndInit(); return(bmp); } } else { throw new FileFormatException("The content file is not in a readable state"); } }
public static BlobInfo ToBlobModel(this ContentFile file) { var retVal = new BlobInfo(); retVal.InjectFrom(file); return(retVal); }
private void addEntry() { bool saved = false; try { string uID = Guid.NewGuid().ToString(); ContentFile.SetArchiveWrite(); ContentFile.Archive.CreateEntryFromFile(toImport[index], uID); Data.Media.Add(uID, (IMedia)Registry.MediaConstructors[Registry.ExtensionConstructors[Path.GetExtension(toImport[index])]].Invoke(new object[] { uID, tslEditor.GetCheckedTagsIndicies(), Path.GetExtension(toImport[index]) }));; ContentFile.SaveData(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); saved = true; Dispatcher.Invoke(() => { tslEditor.UncheckTags(); string toDelete = toImport[index]; toImport.RemoveAt(index); checkedTags.RemoveAt(index); Settings.Default.ToImport.RemoveAt(index); if (index > 0) { btnSkip_Click(null, null); } if (cbxCopy.IsChecked == false) { File.Delete(toDelete); } if (toImport.Count == 0) { frmPreview.Content = null; currentViewer = ""; Paging.LoadPreviousPage(); } bdrImporting.Visibility = Visibility.Collapsed; }); } catch (Exception ex) { Logging.Write(ex, "Import"); if (Debugger.IsAttached) { throw ex; } if (saved) { MessageBox.Show("Could not remove file from original position. Data saved"); } else { MessageBox.Show("Could not save data. The error was recorded and your media was recovered"); } } }
public void updateContratoEmpleo(Guid entityId, ContentFile contrato) { var empleo = _session.Get <Empleo>(entityId); empleo.Contrato = contrato; _session.Save(empleo.Contrato); _session.Save(empleo); }
public void updateContrato(RTN id, ContentFile nuevoContrato) { var empresa = _session.Get <Empresa>(id); empresa.Contrato = nuevoContrato; _session.Save(empresa.Contrato); _session.Update(empresa); }
private void onSaveTimerTick(object sender, ElapsedEventArgs e) { Logging.Write("Autosaving..", "Auto Save"); if (ContentFile.CheckValidity()) { ContentFile.SaveData(); } Logging.SaveLogs(); }
//PdfWriter pdfWriter; public PdfParser(string fileName) { pdfReader = new PdfReader(fileName); parsedFile = new ContentFile() { contentText = GetFileContent() }; }
private ContentFile CreateContentFile(string fileName) { var filePath = new FilePath(fileName, this.basePathProvider); var contentFile = new ContentFile(filePath); contentFile.LinkPath = filePath; // TODO: do we need this? contentFile.ContentFileProvider = this; return(contentFile); }
public static async Task <ContentData> LoadContent() { ContentData contentData = LoadCurrentConfig(); // Load the current configuration (last saved configuration) #if ENABLE_WINMD_SUPPORT var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; // Now process each zip file bool needToSave = false; var zipFiles = await localFolder.GetFilesAsync(); // Directory.GetFiles(zipFolder, "*.zip"); foreach (var file in zipFiles.Where(z => z.FileType == ".zip")) { var fileprops = await file.GetBasicPropertiesAsync(); DateTimeOffset dateModified = fileprops.DateModified; ContentFile contentFile = contentData.Files.FirstOrDefault(f => f.Filename == file.Name); if (contentFile == null) { // Add a new record contentFile = new ContentFile { Filename = file.Name }; contentData.Files.Add(contentFile); contentFile.DateModified = dateModified; contentFile.Topics = GetTopicsFromZipFile(file.Path); contentFile.Exists = true; needToSave = true; } else { contentFile.Exists = true; } if (dateModified > contentFile.DateModified) { // Update existing details. contentFile.DateModified = dateModified; contentFile.Topics = GetTopicsFromZipFile(file.Path); needToSave = true; } } needToSave = (needToSave || contentData.Files.Any(f => !f.Exists)); if (needToSave) { // Remove records for zip files that no longer exist. ContentFile[] toDelete = contentData.Files.Where(f => !f.Exists).ToArray(); foreach (var cf in toDelete) { contentData.Files.Remove(cf); } SaveContent(contentData); } #endif return(contentData); }
public void updateImagenComprobante(Guid entityId, Guid comprobantePagoId, ContentFile imagenComprobante) { var empleo = _session.Get <Empleo>(entityId); var comprobante = empleo.ComprobantesPago.FirstOrDefault(x => x.Id == comprobantePagoId); comprobante.ImagenComprobante = imagenComprobante; _session.Save(comprobante.ImagenComprobante); _session.Update(empleo); }
public void execute(Guid empleoid, Guid comprobanteId, ContentFile contentFile) { var _uow = _factory(); using (_uow) { _repositoryCommands.updateImagenComprobante(empleoid, comprobanteId, contentFile); _uow.commit(); } }
public static ContentFile ToContentModel(this BlobInfo blobInfo) { var retVal = new ContentFile(); retVal.InjectFrom(blobInfo); retVal.Name = blobInfo.FileName; retVal.MimeType = blobInfo.ContentType; retVal.Size = blobInfo.Size.ToHumanReadableSize(); retVal.ModifiedDate = blobInfo.ModifiedDate; return retVal; }
public void execute(Guid idEmpleo, ContentFile contrato) { var _uow = _factory(); using (_uow) { _repositoryCommands.updateContratoEmpleo(idEmpleo, contrato); _uow.commit(); } }
public void execute(RTN empresa, ContentFile contentFile) { var _uow = _factory(); using (_uow) { _repositoryCommands.updateContrato(empresa, contentFile); _uow.commit(); } }
public async Task <string> CreateFile(string appId, string contentId, ContentFile contentfile) { //8c2109f4-31fd-4d86-9869-a141e3c77686/microsoft.graph.windowsMobileMSI/contentVersions/1/files var postUrl = $"{BaseResource}/{appId}/microsoft.graph.windowsMobileMSI/contentVersions/1/files"; var content = _serializationHelper.Serialize(contentfile); var response = await _connector.SendPostRequest(postUrl, content); return(response); }
public void CreateContentFile() { var content = "This is a sample file."; var path = "/sample.txt"; var file = new ContentFile(path, content, null); Assert.AreEqual(file.Content, content); Assert.AreEqual(file.Path, path); Assert.AreEqual(file.Name, "sample.txt"); }
public async Task<IHttpActionResult> UploadContent(string contentType, string storeId, [FromUri] string folderUrl, [FromUri]string url = null) { if (url == null && !Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } var storageProvider = _contentStorageProviderFactory(GetContentBasePath(contentType, storeId)); if (url != null) { var fileName = HttpUtility.UrlDecode(System.IO.Path.GetFileName(url)); var fileUrl = folderUrl + "/" + fileName; using (var client = new WebClient()) using (var blobStream = storageProvider.OpenWrite(fileUrl)) using (var remoteStream = client.OpenRead(url)) { remoteStream.CopyTo(blobStream); var retVal = new ContentFile { Name = fileName, Url = _urlResolver.GetAbsoluteUrl(fileUrl) }; return Ok(retVal); } } else { var blobMultipartProvider = new BlobStorageMultipartProvider(storageProvider, _urlResolver, folderUrl); await Request.Content.ReadAsMultipartAsync(blobMultipartProvider); var retVal = new List<ContentFile>(); foreach (var blobInfo in blobMultipartProvider.BlobInfos) { retVal.Add(new ContentFile { Name = blobInfo.FileName, Url = _urlResolver.GetAbsoluteUrl(blobInfo.Key) }); } return Ok(retVal.ToArray()); } }