public static File CreateByBinary(IFolder parent, BinaryData binaryData) { if (parent == null) throw new ArgumentNullException("parent"); if (binaryData == null) return new File(parent as Node); File file; // Resolve filetype by binary-config matching BinaryTypeResolver resolver = new BinaryTypeResolver(); if (!resolver.ParseBinary(binaryData)) { // Unknown file type file = new File(parent as Node); } else { // Specific File subtype has been found file = TypeHandler.CreateInstance<File>(resolver.NodeType.ClassName, parent); var fname = binaryData.FileName.FileNameWithoutExtension; if (string.IsNullOrEmpty(fname)) fname = file.Name; else if (fname.Contains("\\")) fname = System.IO.Path.GetFileNameWithoutExtension(fname); binaryData.FileName = new BinaryFileName(fname, resolver.FileNameExtension); binaryData.ContentType = resolver.ContentType; } file.Binary = binaryData; return file; }
public void OD_MBO_BuiltIn_TakeOwnership() { ODataTest(() => { File file; using (new CurrentUserBlock(User.Administrator)) { file = new File(CreateTestRoot("TestFiles")) { Name = Guid.NewGuid().ToString() }; file.Save(); Assert.AreEqual(Identifiers.AdministratorUserId, file.OwnerId); } var user = CreateUser("*****@*****.**"); var url = ODataTools.GetODataUrl(Content.Create(file)); var response = ODataPostAsync($"{url}/TakeOwnership", "", $"models=[{{'userOrGroup':'{user.Path}'}}]") .ConfigureAwait(false).GetAwaiter().GetResult(); Assert.AreEqual(204, response.StatusCode); file = Node.Load <File>(file.Id); Assert.AreEqual(user.Id, file.OwnerId); }); }
void btnExport_Click(object sender, EventArgs e) { if (CurrentForm != null) { string fileName = string.Concat("_", CurrentForm.Name, DateTime.UtcNow.ToString("yyyy_MM_dd___HH_mm_ss"), ".csv"); var csv = new SNC.File(CurrentForm); csv.Name = fileName; csv.Binary = new BinaryData(); csv.Binary.FileName = fileName; csv.Binary.ContentType = "application/vnd.ms-excel"; string text = GetCSV(CurrentForm); MemoryStream stream = new MemoryStream(); StreamWriter writer = new StreamWriter(stream, Encoding.GetEncoding("windows-1250")); writer.Write(text); writer.Flush(); csv.Binary.SetStream(stream); csv.Save(); //HttpContext.Current.Response.ClearHeaders(); //HttpContext.Current.Response.Clear(); //HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + csv.Name); //HttpContext.Current.Response.AddHeader("Content-Length", csv.Binary.Size.ToString()); //HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; //HttpContext.Current.Response.Write(new BinaryReader(csv.Binary.GetStream()).ReadString()); //HttpContext.Current.Response.End(); (this.Parent as SingleContentView).OnUserAction(sender, "cancel", "Click"); } }
public void OD_MBO_BuiltIn_TakeLockOver() { ODataTest(() => { var systemFolderCtdId = ContentType.GetByName("SystemFolder").Id; var user = CreateUser("*****@*****.**"); SecurityHandler.CreateAclEditor() .Allow(2, user.Id, false, PermissionType.PermissionTypes) .Allow(systemFolderCtdId, user.Id, false, PermissionType.See) .Apply(); File file; using (new CurrentUserBlock(user)) { file = new File(CreateTestRoot("TestFiles")) { Name = "File-1" }; file.Save(); file.CheckOut(); } Assert.AreEqual(user.Id, file.LockedById); var url = ODataTools.GetODataUrl(Content.Create(file)); var response = ODataPostAsync($"{url}/TakeLockOver", "", "models=[{'user':'******'}]") .ConfigureAwait(false).GetAwaiter().GetResult(); Assert.AreEqual(200, response.StatusCode); Assert.AreEqual("Ok", response.Result); file = Node.Load <File>(file.Id); Assert.AreEqual(Identifiers.AdministratorUserId, file.LockedById); }); }
private void importFromFile() { string error = String.Empty; string fileName = "portlets.xml"; var portletContentPath = RepositoryPath.Combine(pageNode.Path, fileName); snc.File xmlFile = Node.LoadNode(portletContentPath) as SenseNet.ContentRepository.File; if (xmlFile != null) { try { Stream binstream = xmlFile.Binary.GetStream(); XmlDocument newXml = new XmlDocument(); using (XmlReader reader = XmlReader.Create(binstream)) { newXml.Load(reader); } pageNode.SetPersonalizationFromXml(HttpContext.Current, newXml, out error); } catch (Exception e) { Logger.WriteException(e); } } }
private void CreateOrModifyCacheFile(BinaryData cacheBinary, bool compress) { SN.File f = null; MemoryStream cacheStream = new MemoryStream(); if (compress) { GZipOutputStream gzipStream = new GZipOutputStream(cacheStream); byte[] buff = Encoding.ASCII.GetBytes(this._content.ToCharArray()); gzipStream.Write(buff, 0, buff.Length); gzipStream.Flush(); gzipStream.Close(); // set compressed binary byte[] compressedData = cacheStream.ToArray(); cacheBinary.SetStream(new MemoryStream(compressedData)); } else { cacheBinary.SetStream(Tools.GetStreamFromString(_content)); } // gets cache file or creates a new one, the new stream will be saved in both cases if (!Node.Exists(FullCacheFilePath)) { f = SN.File.CreateByBinary(this.CacheFolder, cacheBinary); f.Name = _cacheFile; } else { f = Node.Load <SN.File>(this.FullCacheFilePath); f.Binary = cacheBinary; } f.Save(); }
/// <summary> /// Processes the request. /// </summary> public async Task ProcessRequestCore() { if (!CheckPermissions()) { _context.Response.StatusCode = 404; return; } var httpHeaderTools = new HttpHeaderTools(_context); var endResponse = HandleResponseForClientCache(httpHeaderTools); if (endResponse) { return; } //TODO: CheckExecutableType feature is not ported yet from .net framework Services // It was designed to handle executable files like aspx or cshtml. // See the Repository.ExecutableExtensions property for the full list. //TODO: the ImgResizeApplication feature is not ported yet from .net framework Services await InitializeRequestedNodeAsync(); if (RequestedNode == null) { _context.Response.StatusCode = 404; return; } using (var binaryStream = GetConvertedStream(out var contentType, out var fileName)) { if (binaryStream == null) { return; } _context.Response.ContentType = contentType; _context.Response.Headers.Append(HeaderNames.ContentLength, binaryStream.Length.ToString()); httpHeaderTools.SetContentDispositionHeader(fileName); httpHeaderTools.SetCacheControlHeaders(lastModified: RequestedNode.ModificationDate, maxAge: MaxAge); _context.Response.StatusCode = 200; binaryStream.Position = 0; // Let ASP.NET handle sending bytes to the client. ResponseLimiter.AssertFileLength(binaryStream.Length); await binaryStream.CopyToAsync(_context.Response.Body); } // Let the client code log file downloads if (RequestedNode is File file) { File.Downloaded(file.Id); } }
public void InMemDb_Core_ChunkUpload_NewFile() { Test(async() => { var blobStorage = Providers.Instance.BlobStorage; var root = CreateTestRoot(); var file = new File(root) { Name = "File1.txt" }; file.Binary.ContentType = "application/octet-stream"; //file.Binary.FileName = "File1.txt"; file.Save(); var chunks = new[] { new byte[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, new byte[] { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }, new byte[] { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 }, new byte[] { 4, 4 } }; var chunkSize = chunks[0].Length; // START CHUNK var versionId = file.VersionId; var propertyTypeId = PropertyType.GetByName("Binary").Id; var fullSize = 50L; var token = await blobStorage.StartChunkAsync(versionId, propertyTypeId, fullSize, CancellationToken.None) .ConfigureAwait(false); // WRITE CHUNKS for (int i = 0; i < chunks.Length; i++) { var offset = i * chunkSize; var chunk = chunks[i]; await blobStorage.WriteChunkAsync(versionId, token, chunk, offset, fullSize, CancellationToken.None).ConfigureAwait(false); } // COMMIT CHUNK await blobStorage.CommitChunkAsync(versionId, propertyTypeId, token, fullSize, null, CancellationToken.None) .ConfigureAwait(false); // ASSERT Cache.Reset(); file = Node.Load <File>(file.Id); var length = Convert.ToInt32(file.Binary.Size); var buffer = new byte[length]; using (var stream = file.Binary.GetStream()) stream.Read(buffer, 0, length); Assert.AreEqual( "11111111111111112222222222222222333333333333333344", new string(buffer.Select(b => (char)(b + '0')).ToArray())); }).GetAwaiter().GetResult(); }
private File CreateTestFile(Node parent, string fileContent) { var file = new File(parent) { Name = Guid.NewGuid().ToString() }; file.Binary.SetStream(RepositoryTools.GetStreamFromString(fileContent)); file.Save(); return(file); }
/// <summary> /// Creates new Node of specified Content Type /// </summary> /// <param name="contentTypeName"></param> /// <param name="parent"></param> /// <param name="fileName"></param> /// <param name="stream"></param> public static void CreateNodeOfType(string contentTypeName, Node parent, string fileName, Stream stream) { var node = new SenseNet.ContentRepository.File(parent, contentTypeName); if (CheckAllowedContentType(parent as GenericContent, node)) { node.Name = fileName; node.SetBinary("Binary", UploadHelper.CreateBinaryData(fileName, stream)); node.Save(); } }
private static string GetFileContent(File file) { if (IsTextFile(file.Name)) { using (var reader = new StreamReader(file.Binary.GetStream())) return("[text]:" + Environment.NewLine + reader.ReadToEnd().Replace("\"", "\"\"")); } return("[bytes]:" + Environment.NewLine + InitialData.GetHexDump(file.Binary.GetStream())); }
private static void SaveFile(File file, string lockValue) { file.SetCachedData(WopiService.ExpectedSharedLock, lockValue); try { file.Save(); } finally { file.ResetCachedData(WopiService.ExpectedSharedLock); } }
public static void SetAttachment(SenseNet.ContentRepository.File file, FileAttachment fileAttachment) { using (var stream = new MemoryStream()) { fileAttachment.Load(stream); stream.Seek(0, SeekOrigin.Begin); var binaryData = new BinaryData(); binaryData.SetStream(stream); file.Binary = binaryData; file.Save(); } }
public File LoadTestFile() { if (_testFileId == 0) { var folder = CreateFolder(); var file = new File(folder) { Name = Guid.NewGuid().ToString() }; file.Binary.SetStream(RepositoryTools.GetStreamFromString(OriginalFileContent)); file.Save(); _testFileId = file.Id; } return(Node.Load <File>(_testFileId)); }
private UserPermissions GetUserPermissions(File file, IUser user) { using (new SystemAccount()) { var entries = file.Security.GetEffectiveEntries(); var identities = new List <int> { user.Id }; // get all groups of the user, including Owners if necessary identities.AddRange(Providers.Instance.SecurityHandler.GetGroupsWithOwnership(file.Id, user)); var allowBits = 0UL; var denyBits = 0UL; foreach (var entry in entries) { if (identities.Contains(entry.IdentityId)) { allowBits |= entry.AllowBits; denyBits |= entry.DenyBits; } } allowBits = allowBits & ~denyBits; if (IsReadOnlyMode) { return(new UserPermissions { Write = false, RestrictedViewOnly = 0 == (allowBits & PermissionType.Open.Mask) && 0 != (allowBits & (PermissionType.Preview.Mask + PermissionType.PreviewWithoutWatermark.Mask + PermissionType.PreviewWithoutRedaction.Mask)), Create = false, }); } return(new UserPermissions { Write = (allowBits & PermissionType.Save.Mask) > 0, RestrictedViewOnly = 0 == (allowBits & PermissionType.Open.Mask) && 0 != (allowBits & (PermissionType.Preview.Mask + PermissionType.PreviewWithoutWatermark.Mask + PermissionType.PreviewWithoutRedaction.Mask)), Create = false }); } }
private bool IsPreconditionOk(GetFileRequest wopiRequest, File file) { if (wopiRequest.MaxExpectedSize == null) { return(true); } var bigLength = file.Binary.Size; if (bigLength > int.MaxValue) { return(false); } var length = Convert.ToInt32(bigLength); return(wopiRequest.MaxExpectedSize.Value >= length); }
public FileOperation(string fileName = null) { var fileContainer = Node.Load <SystemFolder>("/Root/TestFiles"); if (fileContainer == null) { fileContainer = new SystemFolder(Repository.Root) { Name = "TestFiles" }; fileContainer.Save(); } TheFile = new File(fileContainer) { Name = fileName ?? Guid.NewGuid().ToString() }; TheFile.Binary.SetStream(RepositoryTools.GetStreamFromString("Lorem ipsum...")); TheFile.Save(); }
private UserPermissions GetUserPermissions(File file, IUser user) { using (new SystemAccount()) { var entries = file.Security.GetEffectiveEntries(); var userId = user.Id; var allowBits = 0UL; var denyBits = 0UL; foreach (var entry in entries) { if (userId == entry.IdentityId) { allowBits |= entry.AllowBits; denyBits |= entry.DenyBits; } } allowBits = allowBits & ~denyBits; //UNDONE: Uncomment this instruction to allow document editing //return new UserPermissions //{ // Write = (allowBits & PermissionType.Save.Mask) > 0, // RestrictedViewOnly = 0 == (allowBits & PermissionType.Open.Mask) && // 0 != (allowBits & (PermissionType.Preview.Mask + // PermissionType.PreviewWithoutWatermark.Mask + // PermissionType.PreviewWithoutRedaction.Mask)), // Create = !file.Parent?.Security.HasPermission(user, PermissionType.AddNew) ?? false, //}; //UNDONE: Delete this instruction to allow document editing return(new UserPermissions { Write = false, RestrictedViewOnly = 0 == (allowBits & PermissionType.Open.Mask) && 0 != (allowBits & (PermissionType.Preview.Mask + PermissionType.PreviewWithoutWatermark.Mask + PermissionType.PreviewWithoutRedaction.Mask)), Create = false, }); } }
private void exportToFile() { string fileName = "portlets.xml"; snc.File newPortletInfoFile = null; BinaryData newPortletInfoBinary = null; var portletContentPath = RepositoryPath.Combine(pageNode.Path, fileName); if (NodeHead.Get(portletContentPath) == null) { newPortletInfoFile = new snc.File(pageNode); newPortletInfoBinary = new BinaryData(); } else { newPortletInfoFile = Node.Load <snc.File>(portletContentPath); newPortletInfoBinary = newPortletInfoFile.Binary; } newPortletInfoFile.Name = fileName; newPortletInfoFile.Hidden = true; MemoryStream stream = new MemoryStream(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; using (XmlWriter writer = XmlWriter.Create(stream, settings)) { if (pageXml == null) { loadXml(); } pageXml.WriteTo(writer); writer.Flush(); newPortletInfoBinary.SetStream(stream); newPortletInfoFile.Binary = newPortletInfoBinary; newPortletInfoFile.Save(); } }
/// <summary>Method for tests</summary> internal static WopiResponse ProcessPutFileRequest(File file, string lockValue, Stream stream) { var existingLock = SharedLock.GetLock(file.Id, CancellationToken.None); if (existingLock == null) { if (file.Binary.Size != 0) { return new WopiResponse { StatusCode = HttpStatusCode.Conflict } } ; } if (existingLock != lockValue) { return(new WopiResponse { StatusCode = HttpStatusCode.Conflict, Headers = new Dictionary <string, string> { { WopiHeader.Lock, existingLock }, { WopiHeader.LockFailureReason, "LockedByAnother" } } }); } var binaryData = file.Binary; binaryData.SetStream(stream); file.Binary = binaryData; SaveFile(file, existingLock); //TODO:WOPI Set X-WOPI-ItemVersion header if needed. return(new WopiResponse { StatusCode = HttpStatusCode.OK }); }
internal static void SavePortletDefinition(WebPart webPart, string contentString) { if (webPart == null) { throw new ArgumentNullException("webPart"); } if (String.IsNullOrEmpty(contentString)) { throw new ArgumentException("contentString"); } var currentPage = SenseNet.Portal.Page.Current; var newPortletInfoFileName = String.Concat(webPart.ID, "$", webPart.Zone.ID, PortletInfoFileNameExtension); SNC.File newPortletInfoFile = null; BinaryData newPortletInfoBinary = null; var portletContentPath = RepositoryPath.Combine(currentPage.Path, newPortletInfoFileName); if (NodeHead.Get(portletContentPath) == null) { newPortletInfoFile = new SNC.File(currentPage); newPortletInfoBinary = new BinaryData(); } else { newPortletInfoFile = Node.Load <SNC.File>(portletContentPath); newPortletInfoBinary = newPortletInfoFile.Binary; } var contentStream = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(contentString)); newPortletInfoBinary.SetStream(contentStream); newPortletInfoFile.Name = newPortletInfoFileName; newPortletInfoFile.Binary = newPortletInfoBinary; newPortletInfoFile.Save(); }
private void exportToFile() { string fileName = "portlets.xml"; snc.File newPortletInfoFile = null; BinaryData newPortletInfoBinary = null; var portletContentPath = RepositoryPath.Combine(pageNode.Path, fileName); if (NodeHead.Get(portletContentPath) == null) { newPortletInfoFile = new snc.File(pageNode); newPortletInfoBinary = new BinaryData(); } else { newPortletInfoFile = Node.Load<snc.File>(portletContentPath); newPortletInfoBinary = newPortletInfoFile.Binary; } newPortletInfoFile.Name = fileName; newPortletInfoFile.Hidden = true; MemoryStream stream = new MemoryStream(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; using (XmlWriter writer = XmlWriter.Create(stream, settings)) { if (pageXml == null) loadXml(); pageXml.WriteTo(writer); writer.Flush(); newPortletInfoBinary.SetStream(stream); newPortletInfoFile.Binary = newPortletInfoBinary; newPortletInfoFile.Save(); } }
void btnExport_Click(object sender, EventArgs e) { if (CurrentForm != null) { string fileName = string.Concat("_", CurrentForm.Name, DateTime.Now.ToString("yyyy_MM_dd___HH_mm_ss"), ".csv"); var csv = new SNC.File(CurrentForm); csv.Name = fileName; csv.Binary = new BinaryData(); csv.Binary.FileName = fileName; csv.Binary.ContentType = "application/vnd.ms-excel"; string text = GetCSV(CurrentForm); MemoryStream stream = new MemoryStream(); StreamWriter writer = new StreamWriter(stream, Encoding.GetEncoding("windows-1250")); writer.Write(text); writer.Flush(); csv.Binary.SetStream(stream); csv.Save(); //HttpContext.Current.Response.ClearHeaders(); //HttpContext.Current.Response.Clear(); //HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + csv.Name); //HttpContext.Current.Response.AddHeader("Content-Length", csv.Binary.Size.ToString()); //HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; //HttpContext.Current.Response.Write(new BinaryReader(csv.Binary.GetStream()).ReadString()); //HttpContext.Current.Response.End(); (this.Parent as SingleContentView).OnUserAction(sender, "cancel", "Click"); } }
private WopiResponse ProcessPutRelativeFileRequest(PutRelativeFileRequest wopiReq, PortalContext portalContext) { if (!int.TryParse(wopiReq.FileId, out var contentId)) { return new WopiResponse { StatusCode = HttpStatusCode.NotFound } } ; if (!(Node.LoadNode(contentId) is File file)) { return new WopiResponse { StatusCode = HttpStatusCode.NotFound } } ; var allowIncrementalNaming = wopiReq.SuggestedTarget != null; var allowOverwrite = wopiReq.OverwriteRelativeTarget; var targetName = wopiReq.SuggestedTarget ?? wopiReq.RelativeTarget; if (targetName.StartsWith(".")) { targetName = Path.GetFileNameWithoutExtension(file.Name) + targetName; } File targetFile = null; if (!allowIncrementalNaming) { var targetPath = $"{file.ParentPath}/{targetName}"; var node = Node.LoadNode(targetPath); if (node != null) { if (!allowOverwrite || !(node is File loadedFile)) { return new PutRelativeFileResponse { StatusCode = HttpStatusCode.NotImplemented } } ; targetFile = loadedFile; } } if (targetFile == null) { targetFile = new File(file.Parent) { Name = targetName }; targetFile.AllowIncrementalNaming = allowIncrementalNaming; } else { throw new NotImplementedException(); //UNDONE:! Check lock } targetFile.Binary.FileName = targetName; targetFile.Binary.SetStream(wopiReq.RequestStream); targetFile.Save(); var url = "__notimplemented__"; //UNDONE:! Generate correct URL return(new PutRelativeFileResponse { StatusCode = HttpStatusCode.OK, Name = targetFile.Name, Url = url, }); }
private void WopiHandler_SaveFile(File file, string lockValue) { _wopiHandlerAcc.InvokeStatic("SaveFile", file, lockValue); }
internal static void SavePortletDefinition(WebPart webPart, string contentString) { if (webPart == null) throw new ArgumentNullException("webPart"); if (String.IsNullOrEmpty(contentString)) throw new ArgumentException("contentString"); var currentPage = SenseNet.Portal.Page.Current; var newPortletInfoFileName = String.Concat(webPart.ID, "$", webPart.Zone.ID, PortletInfoFileNameExtension); SNC.File newPortletInfoFile = null; BinaryData newPortletInfoBinary = null; var portletContentPath = RepositoryPath.Combine(currentPage.Path, newPortletInfoFileName); if (NodeHead.Get(portletContentPath) == null) { newPortletInfoFile = new SNC.File(currentPage); newPortletInfoBinary = new BinaryData(); } else { newPortletInfoFile = Node.Load<SNC.File>(portletContentPath); newPortletInfoBinary = newPortletInfoFile.Binary; } var contentStream = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(contentString)); newPortletInfoBinary.SetStream(contentStream); newPortletInfoFile.Name = newPortletInfoFileName; newPortletInfoFile.Binary = newPortletInfoBinary; newPortletInfoFile.Save(); }
/// <summary>Method for tests</summary> internal static async Task <WopiResponse> ProcessPutFileRequestAsync(File file, string lockValue, Stream stream, CancellationToken cancellationToken) {
private async Task <WopiResponse> ProcessPutRelativeFileRequestAsync(PutRelativeFileRequest wopiRequest, CancellationToken cancellationToken) { if (!int.TryParse(wopiRequest.FileId, out var contentId)) { return new WopiResponse { StatusCode = HttpStatusCode.NotFound } } ; if (!(await Node.LoadNodeAsync(contentId, cancellationToken).ConfigureAwait(false) is File file)) { return new WopiResponse { StatusCode = HttpStatusCode.NotFound } } ; var allowIncrementalNaming = wopiRequest.SuggestedTarget != null; var allowOverwrite = wopiRequest.OverwriteRelativeTarget; var targetName = wopiRequest.SuggestedTarget ?? wopiRequest.RelativeTarget; if (targetName.StartsWith(".")) { targetName = Path.GetFileNameWithoutExtension(file.Name) + targetName; } File targetFile = null; if (!allowIncrementalNaming) { var targetPath = $"{file.ParentPath}/{targetName}"; var node = await Node.LoadNodeAsync(targetPath, cancellationToken).ConfigureAwait(false); if (node != null) { if (!allowOverwrite || !(node is File loadedFile)) { return new PutRelativeFileResponse { StatusCode = HttpStatusCode.NotImplemented } } ; targetFile = loadedFile; } } if (targetFile == null) { targetFile = new File(file.Parent) { Name = targetName }; targetFile.AllowIncrementalNaming = allowIncrementalNaming; } else { throw new NotImplementedException(); //TODO:WOPI: ProcessPutRelativeFileRequest Check lock } targetFile.Binary.FileName = targetName; targetFile.Binary.SetStream(wopiRequest.RequestStream); targetFile.Save(); //TODO:WOPI: ProcessPutRelativeFileRequest shared lock? var url = "__notimplemented__"; //TODO:WOPI: ProcessPutRelativeFileRequest Generate correct URL return(new PutRelativeFileResponse { StatusCode = HttpStatusCode.NotImplemented, Name = targetFile.Name, Url = url, }); }
private List <SyncResultObject> GetFilesAndSync(Content cntToSync, string filePath) { var result = new List <SyncResultObject>(); DirectoryInfo dirInfo = new DirectoryInfo(filePath); IEnumerable <Content> children = cntToSync.Children.Where(c => c.TypeIs("File")); //Content lastContent = children.OrderByDescending(c => c.CreationDate).FirstOrDefault(); //DateTime lastContentDate = (lastContent != null) ? lastContent.CreationDate : DateTime.MinValue; //technical debt: I think creationdate won't be good here, we should probably use last syncdate var fileInfos = dirInfo.GetFiles(); //if (fileInfos.Length == 0) // result.Add(new SyncResultObject(filePath, SyncResult.NoSyncToDo)); //else if (fileInfos.Length > 0) { foreach (var file in fileInfos) { var fileSynced = false; string fileName = file.Name; try { using (Stream fileStream = file.Open(FileMode.Open, FileAccess.Read)) //Open the file ReadOnly mode { fileName = ContentNamingHelper.GetNameFromDisplayName(file.Name); using (new SystemAccount()) {//Technical Debt: as for now we do not check if file needs to be updated or not Content fileContent = cntToSync.Children.Where(c => c.Name == fileName).FirstOrDefault(); if (fileContent == null) { // create new SenseNet.ContentRepository.File newFile = new SenseNet.ContentRepository.File(cntToSync.ContentHandler); newFile.Name = ContentNamingHelper.GetNameFromDisplayName(file.Name); newFile.DisplayName = file.Name; newFile.Save(); fileContent = Content.Load(newFile.Id); var fileSyncAspect = Aspect.LoadAspectByPathOrName(ASPECTNAME); fileContent.Save(); // ez miert? elo is kell menteni? fileContent.AddAspects(fileSyncAspect); } SaveAsTechnicalUser(fileContent, fileStream); result.Add(new SyncResultObject(fileContent.Path, SyncResult.SyncSuccess)); } fileSynced = true; } } catch (Exception ex) { SnLog.WriteException(ex); result.Add(new SyncResultObject(string.Concat(cntToSync.Path, "/", fileName), SyncResult.SyncFailed)); } // result add would be better at here // delete file try { if (fileSynced) { //Logger.WriteInformation(40002, "FILESYNC delete 545 " + file.Name); file.Delete(); } // should we log deletion? } catch (Exception ex) { SnLog.WriteException(ex); } } } //// save refresh date on parent //SaveAsTechnicalUser(cntToSync, null, true); return(result); }
protected override void Execute(NativeActivityContext context) { var message = Message.Get(context); var parentPath = ParentPath.Get(context); var overwrite = OverwriteExistingContent.Get(context); var displayName = ContentDisplayName.Get(context); var name = ContentName.Get(context); if (string.IsNullOrEmpty(name)) name = ContentNamingHelper.GetNameFromDisplayName(displayName) + ".eml"; var parent = Node.LoadNode(parentPath); if (parent == null) throw new ApplicationException("Cannot create content because parent does not exist. Path: " + parentPath); //var displayName = message.Subject; //var name = ContentNamingHelper.GetNameFromDisplayName(message.Subject) + ".eml"; // check existing file var node = Node.LoadNode(RepositoryPath.Combine(parentPath, name)); File file; if (node == null) { // file does not exist, create new one file = new File(parent); if (!string.IsNullOrEmpty(displayName)) file.DisplayName = displayName; file.Name = name; } else { // file exists if (overwrite) { // overwrite it, so we open it file = node as File; // node exists and it is not a file -> delete it and create a new one if (file == null) { node.ForceDelete(); file = new File(parent); } file.DisplayName = displayName; file.Name = name; } else { // do not overwrite it file = new File(parent); if (!string.IsNullOrEmpty(displayName)) file.DisplayName = displayName; file.Name = name; file.AllowIncrementalNaming = true; } } try { using (var memoryStream = new System.IO.MemoryStream(message.MimeContent.Content)) { var binaryData = new BinaryData(); binaryData.SetStream(memoryStream); file.Binary = binaryData; file.Save(); } } catch (Exception ex) { Logger.WriteException(ex); } }
public override VirtualFile GetFile(string virtualPath) { var currentPortalContext = PortalContext.Current; // office protocol: instruct microsoft office to open the document without further webdav requests when simply downloading the file // webdav requests would cause an authentication window to pop up when downloading a docx if (HttpContext.Current != null && HttpContext.Current.Response != null) { if (WebApplication.DownloadExtensions.Any(extension => virtualPath.EndsWith(extension, StringComparison.InvariantCultureIgnoreCase))) { // we need to do it this way to support a 'download' query parameter with or without a value var queryParams = HttpContext.Current.Request.QueryString.GetValues(null); var download = HttpContext.Current.Request.QueryString.AllKeys.Contains("download") || (queryParams != null && queryParams.Contains("download")); if (download) { var fName = string.Empty; if (currentPortalContext != null && currentPortalContext.IsRequestedResourceExistInRepository) { // look for a content var node = Node.LoadNode(virtualPath); if (node != null) { fName = DocumentBinaryProvider.Current.GetFileName(node); } } else { // look for a file in the file system fName = Path.GetFileName(virtualPath); } HttpHeaderTools.SetContentDispositionHeader(fName); } } } if (WebApplication.DiskFSSupportMode == DiskFSSupportMode.Prefer && base.FileExists(virtualPath)) { var result = base.GetFile(virtualPath); // let the client code log file downloads if (PortalContext.Current != null && PortalContext.Current.ContextNodePath != null && string.Compare(virtualPath, PortalContext.Current.ContextNodePath, StringComparison.Ordinal) == 0) { File.Downloaded(virtualPath); } return(result); } // Indicates that the VirtualFile is requested by a HttpRequest (a Page.LoadControl also can be a caller, or an aspx for its codebehind file...) var isRequestedByHttpRequest = (HttpContext.Current != null) && (string.Compare(virtualPath, HttpContext.Current.Request.Url.LocalPath, StringComparison.InvariantCultureIgnoreCase) == 0); if (isRequestedByHttpRequest && currentPortalContext.IsRequestedResourceExistInRepository) { return(new RepositoryFile(virtualPath, currentPortalContext.RepositoryPath)); } else if (IsFileExistsInRepository(virtualPath)) { return(new RepositoryFile(virtualPath, virtualPath)); } else if (IsFileExistsInAssembly(virtualPath)) { return(new EmbeddedFile(virtualPath)); } else { // Otherwise it may exist in the filesystem - call the base return(base.GetFile(virtualPath)); } }