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 static StepResult InstallContent(Content content) { bool isNewContent; try { SnC.Content snContent = CreateOrLoadContent(content, out isNewContent); foreach (var attachment in content.Attachments) { var data = new BinaryData() { FileName = attachment.FileName }; data.SetStream(attachment.Manifest.GetStream(attachment.FileName)); snContent[attachment.FieldName] = data; } snContent.Save(); content.IsNewContent = isNewContent; if (!SetMetadata(snContent, content, isNewContent, false)) { Logger.LogWarningMessage(PrintFieldErrors(snContent)); return new StepResult { Kind = StepResultKind.Warning }; } } catch (Exception transferEx) { Logger.LogException(transferEx); return new StepResult { Kind = StepResultKind.Error }; } return new StepResult { Kind = StepResultKind.Successful }; }
public SenseNet.ContentRepository.Fields.ImageField.ImageFieldData GetImageFieldData() { if (this.ImageStream == null) return null; var binaryData = new BinaryData(); binaryData.SetStream(this.ImageStream); return new SenseNet.ContentRepository.Fields.ImageField.ImageFieldData(null, binaryData); }
private static void SetBinaryDataProperties(FileUpload fileUpload, BinaryData data) { var fileStream = fileUpload.PostedFile.InputStream; var contentType = fileUpload.PostedFile.ContentType; var fileName = fileUpload.PostedFile.FileName; data.ContentType = contentType; data.FileName = fileName; data.SetStream(fileStream); }
public override void SetProperty(string name, object value) { switch (name) { case "Binary": this.Binary = (BinaryData)value; break; default: base.SetProperty(name, value); break; } }
public static new Image CreateByBinary(IFolder parent, BinaryData binaryData) { if (parent == null) throw new ArgumentNullException("parent"); if (binaryData == null) return new Image(parent as Node); Image image = new Image(parent as Node);; // Resolve filetype by binary-config matching binaryData.FileName = new BinaryFileName(image.Name, image.Extension); image.Binary = binaryData; return image; }
// Events ///////////////////////////////////////////////////////////////// /// <summary> /// Gets object data. /// </summary> /// <returns> /// Object representing data of the wrapped Field /// </returns> /// <remarks> /// Exception handling and displayed is done at ContentView level; FormatExceptions and Exceptions are handled and displayed at this level. /// Should you need custom or localized error messages, throw a FieldControlDataException with your own error message. /// </remarks> public override object GetData() { if (_data == null) _data = new BinaryData(); #region template if ((!UseBrowseTemplate && !UseEditTemplate) && !UseInlineEditTemplate) { SetBinaryDataProperties(_data, _fileUploadControl, _textBox); return _data; } SetBinaryDataProperties(_data, GetUploadeControl() as FileUpload, GetInnerControl() as ITextControl); return _data; #endregion }
public bool ParseBinary(BinaryData binaryData) { if(binaryData == null) throw new ArgumentNullException("binaryData"); // TODO: Resolve correct File subtype by the SenseNet.ContentRepository.Storage.MimeTable _nodeType = ActiveSchema.NodeTypes[typeof(File).Name]; if(_nodeType == null) { // Unknown type _fileNameExtension = null; _contentType = null; return false; } else { // Fix extension and/or contenttype values by config matching _fileNameExtension = binaryData.FileName.Extension; _contentType = binaryData.ContentType; return true; } }
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(); } }
public override object GetData() { if (_data == null) _data = new BinaryData(); if (!UseBrowseTemplate && !UseEditTemplate && !UseInlineEditTemplate) { if (!_fileUploadControl.HasFile) return _data; SetBinaryDataProperties(_fileUploadControl, _data); } var innerControl = GetInnerControl() as FileUpload; if (innerControl == null) return _data; if (!innerControl.HasFile) return _data; SetBinaryDataProperties(_fileUploadControl, _data); return _data; }
//// Creating test node private string CreateTestFile() { File f = new File(this.TestRoot); f.Name = Guid.NewGuid().ToString(); BinaryData data = new BinaryData(); data.SetStream(TestTools.GetTestStream()); f.Binary = data; f.Save(); return RepositoryPath.Combine(this.TestRoot.Path, f.Name); }
public static void SaveBlob(string path, byte[] sharedDataBlob) { if (SNP.Page.Current == null || String.IsNullOrEmpty(SNP.Page.Current.Path)) { throw new PersonalizationException("No page loaded."); } var p = SNP.Page.Current; if (p.PersonalizationSettings != null) { if (sharedDataBlob.Length == 0) SenseNetPersonalizationProvider.WriteLog(String.Format("SaveBlob --> missing personalization settings at {0} path.", SNP.Page.Current.Path)); p.PersonalizationSettings.SetStream(new MemoryStream(sharedDataBlob)); } else { BinaryData binaryPers = new BinaryData(); binaryPers.SetStream(new MemoryStream(sharedDataBlob)); p.PersonalizationSettings = binaryPers; } p.Save(); }
public void File_CanCreateByBinary() { Node parent = Repository.Root; BinaryData binary = new BinaryData(); binary.SetStream(TestTools.GetTestStream()); File target = File.CreateByBinary(Repository.Root, binary); Assert.IsNotNull(target.Size, "Size is null."); Assert.IsFalse(target.Size == 0, "Size is 0."); }
/* ============================================================================= Methods */ public override object GetData() { if (_data == null) _data = new SenseNet.ContentRepository.Fields.ImageField.ImageFieldData(); var innerControl = _fileUploadControl; var imageIsRefControl = _cbxImageRef; // templates if (IsTemplated) { innerControl = GetInnerControl() as FileUpload; imageIsRefControl = GetImageIsRefControl() as CheckBox; } _binaryData = null; // newly posted filestream bool newStream = false; if (innerControl != null && innerControl.HasFile) { var fileStream = innerControl.PostedFile.InputStream; var contentType = innerControl.PostedFile.ContentType; var fileName = innerControl.PostedFile.FileName; _binaryData = new BinaryData(); _binaryData.ContentType = contentType; _binaryData.FileName = fileName; _binaryData.SetStream(fileStream); newStream = true; } // new image mode var originalImageMode = this.ImageField.ImageMode; var newImageMode = imageIsRefControl.Checked ? ImageRequestMode.Reference : ImageRequestMode.BinaryData; if (!newStream) { switch (this.ImageField.ImageMode) { case ImageRequestMode.BinaryData: _binaryData = _data.ImgData; break; case ImageRequestMode.Reference: if (_data.ImgRef != null) _binaryData = _data.ImgRef.Binary; break; } } // no uploads and no original data, so return with empty data if (_binaryData == null) return _data; // if mode is not changed, proceed only if new uploaded stream is available if ((newImageMode == this.ImageField.ImageMode) && (!newStream)) return _data; // from here either mode is changed or new stream is available // 2 possibilities: new mode is reference or new mode is binary // - reference // - former binarydata is cleared // - the referenced node is created or updated // - binary // - binarydata property is set // - referenced node is deleted if (newImageMode == ImageRequestMode.Reference) { // clear binarydata _data.ImgData = null; if (this.Content.Id != 0) CreateImageReference(this.ContentHandler); else this.ContentHandler.Created += new EventHandler<SenseNet.ContentRepository.Storage.Events.NodeEventArgs>(ContentHandler_Created); } else { // set binarydata _data.ImgData = new BinaryData(); _data.ImgData.CopyFrom(_binaryData); // if copied from referenced node -> node name should be filename, not node's binary's filename (latter could contain '\'-s) if (!newStream) _data.ImgData.FileName = new BinaryFileName(_data.ImgRef.Name); // clear referencedata (also delete the file but only after this node is saved!) this.ContentHandler.Modified += new EventHandler<SenseNet.ContentRepository.Storage.Events.NodeEventArgs>(ContentHandler_Modified); } // reset image url after new image is saved var imageControl = GetImageControl(); if (imageControl != null) { if (!string.IsNullOrEmpty(this.ImageUrl)) imageControl.ImageUrl = this.ImageUrl; } return _data; }
/// <summary> /// Finalizes a chunk saving process: sets the stream size and length for the binary. /// </summary> /// <param name="contentId">Id of the content</param> /// <param name="token">The token received from the StartChunk method that needs to be called before the chunk saving operation starts.</param> /// <param name="fullStreamSize">Full size of the binary stream</param> /// <param name="fieldName">Name of the field. Default: Binary</param> /// <param name="binaryMetadata">Additional metadata for the binary row: file name, extension, content type.</param> public static void CommitChunk(int contentId, string token, long fullStreamSize, string fieldName = "Binary", BinaryData binaryMetadata = null) { Node node; PropertyType pt; AssertChunk(contentId, fieldName, out node, out pt); DataProvider.Current.CommitChunk(node.VersionId, pt.Id, token, fullStreamSize, binaryMetadata == null ? null : binaryMetadata.RawData); NodeIdDependency.FireChanged(node.Id); StorageContext.L2Cache.Clear(); }
public void CopyFrom(BinaryData data) { //Id = data.Id; FileName = data.FileName; ContentType = data.ContentType; Size = data.Size; this.SetStream(data.GetStream()); }
private PageState GetPageState(BinaryData binaryData) { if (binaryData == null) throw new ArgumentNullException("binaryData"); PageState resultPageState = null; Stream sharedDataBlobStream = binaryData.GetStream(); int streamLength = Convert.ToInt32(sharedDataBlobStream.Length); var byteContent = new byte[streamLength]; //try //{ sharedDataBlobStream.Read(byteContent, 0, streamLength); resultPageState = new PageState(byteContent, PersonalizationScope.Shared); //} //catch (Exception exc) //{ // WriteException(exc); //} return resultPageState; }
/// <summary> /// Sets data within the FieldControl /// </summary> /// <param name="data">Data of the <see cref="SenseNet.ContentRepository.Field">Field</see> wrapped</param> public override void SetData(object data) { _data = data as BinaryData; var stream = _data == null ? null : _data.GetStream(); var streamString = string.Empty; try { if (IsTextInternal && stream != null) streamString = Tools.GetStreamString(stream); } catch (Exception ex) { // failed to load stream // streamString will be string.Empty, no need for special actions Logger.WriteException(ex); } if (_textBox != null) _textBox.Text = streamString; #region template if ((!UseBrowseTemplate && !UseEditTemplate) && !UseInlineEditTemplate) return; var title = GetLabelForTitleControl() as Label; var desc = GetLabelForDescription() as Label; var innerControl = GetInnerControl() as TextBox; if (title != null) title.Text = this.Field.DisplayName; if (desc != null) desc.Text = this.Field.Description; if (innerControl != null) innerControl.Text = streamString; #endregion }
private PageTemplate CreatePageTemplate(string zoneName, string parentPath) { var folderpath = parentPath ?? this.TestRoot.Path; PageTemplate pageTemplate = null; pageTemplate = Node.LoadNode(string.Concat(folderpath, "/TestPageTemplate.html")) as PageTemplate; if (pageTemplate == null) { var parent = Node.LoadNode(folderpath); pageTemplate = new PageTemplate(parent); pageTemplate.Name = "TestPageTemplate.html"; } BinaryData binaryData = new BinaryData(); binaryData.FileName = new BinaryFileName("TestPageTemplate.html"); string streamString = string.Concat( "<html>", " <body>", " <snpe-zone name=\"ZoneName_", zoneName, "\"></snpe-zone>", " <snpe-edit name=\"Editor\"></snpe-edit>", " <snpe-catalog name=\"Catalog\"></snpe-catalog>", " <snpe:PortalRemoteControl2 ID=\"RemoteControl1\" runat=\"server\" />", " </body>", "</html>" ); Stream stream = Tools.GetStreamFromString(streamString); binaryData.SetStream(stream); pageTemplate.Binary = binaryData; pageTemplate.Save(); return pageTemplate; }
public void PageTemplateManager_CheckPageTemplateBinaryStream_NullStreamTest() { PageTemplate pageTemplate = new PageTemplate(this.TestRoot); BinaryData binaryData = new BinaryData(); binaryData.SetStream(null); pageTemplate.Binary = binaryData; bool expected = false; bool actual = SenseNet.ContentRepository.Tests.SenseNet_Portal_PageTemplateManagerAccessor.CheckPageTemplateBinaryStream(pageTemplate); Assert.AreEqual(expected, actual, "PageTemplateManager.CheckPageTemplateBinaryStream did not return the expected value."); }
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); } }
private static void CreateTestPageTemplate() { PageTemplate pt = null; pt = new PageTemplate(Node.LoadNode(_rootNodePath)); pt.Name = _testPageTemplateName; BinaryData binaryData = new BinaryData(); binaryData.FileName = new BinaryFileName(_testPageTemplateName); string streamString = _pageTemplateHtml; Stream stream = Tools.GetStreamFromString(streamString); binaryData.SetStream(stream); pt.Binary = binaryData; pt.Save(); _pageTemplatePath = pt.Path; }
private void HandleAuthorPutDocument(HttpContext context, string firstLine, System.IO.Stream resultStream) { // firstline: method=put document:14.0.0.6009&service_name=/Root/Sites/Default_Site/workspaces/Project/budapestprojectworkspace/&document=[document_name=Document_Library/Aenean semper.doc;meta_info=[]]&put_option=edit&comment=&keep_checked_out=false var serviceNameIdx = firstLine.IndexOf("&service_name="); var workspacePathIdx = serviceNameIdx + "&service_name=".Length; var documentIdx = firstLine.IndexOf("&document=[document_name="); var documentPathIdx = documentIdx + "&document=[document_name=".Length; var workspacePath = firstLine.Substring(workspacePathIdx, documentIdx - workspacePathIdx); var documentPath = firstLine.Substring(documentPathIdx, firstLine.IndexOf(';') - documentPathIdx); //System.Diagnostics.Trace.Write(" FPP put document workspace: " + workspacePath); //System.Diagnostics.Trace.Write(" FPP put document doc path: " + documentPath); var nodePath = RepositoryPath.Combine(workspacePath, documentPath); var file = Node.LoadNode(nodePath) as File; if (file != null) { var binaryData = new BinaryData(); binaryData.SetStream(resultStream); file.SetBinary("Binary", binaryData); file.Save(SavingMode.KeepVersion); // file is not checked in as of yet. office will try to check it in via lists.asmx } var docinfo = GetDocInfo(file); var responseStr = GetFormattedString(string.Format(PUTDOCUMENTSTR, docinfo)); context.Response.Charset = ""; context.Response.ContentType = "application/x-vermeer-rpc"; context.Response.AddHeader("Content-Length", responseStr.Length.ToString()); context.Response.AddHeader("Connection", "close"); context.Response.Write(responseStr); context.Response.Flush(); context.Response.End(); }
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 void PageTemplateManager_CheckPageTemplateBinaryStream_Test() { PageTemplate pageTemplate = new PageTemplate(this.TestRoot); BinaryData binaryData = new BinaryData(); string streamData = "TestString"; binaryData.SetStream(Tools.GetStreamFromString(streamData)); pageTemplate.Binary = binaryData; bool expected = true; bool actual = SenseNet.ContentRepository.Tests.SenseNet_Portal_PageTemplateManagerAccessor.CheckPageTemplateBinaryStream(pageTemplate); Assert.AreEqual(expected, actual, "PageTemplateManager.CheckPageTemplateBinaryStream did not return the expected value."); }
private string GetStringFromBinaryData(BinaryData binary) { Stream stream = binary.GetStream(); StreamReader sr = new StreamReader(stream, Encoding.UTF8); string value = sr.ReadToEnd(); return value; }
private void SetBinaryDataProperties(BinaryData data, FileUpload fileUpload, ITextControl editor) { //if (editor == null) // return; //var hasText = editor.Text.Length > 0; //if (fileUpload != null && fileUpload.HasFile) //{ // var fileStream = fileUpload.PostedFile.InputStream; // var contentType = fileUpload.PostedFile.ContentType; // var fileName = fileUpload.PostedFile.FileName; // data.ContentType = contentType; // data.FileName = fileName; // data.SetStream(fileStream); // if (AutoName) // Content.Fields["Name"].SetData(Path.GetFileName(fileName)); //} //else if (hasText) // data.SetStream(Tools.GetStreamFromString(editor.Text)); if (editor == null) return; var textMode = ((TextBox)editor).Visible; if (textMode) { data.SetStream(Tools.GetStreamFromString(editor.Text)); } else { if (fileUpload != null && fileUpload.HasFile) { var fileStream = fileUpload.PostedFile.InputStream; var contentType = fileUpload.PostedFile.ContentType; var fileName = fileUpload.PostedFile.FileName; data.ContentType = contentType; data.FileName = fileName; data.SetStream(fileStream); //if (AutoName) // Content.Fields["Name"].SetData(Path.GetFileName(fileName)); } } }
/// <summary> /// Creates BinaryData from filename and stream /// </summary> /// <param name="fileName"></param> /// <param name="stream"></param> /// <returns></returns> public static BinaryData CreateBinaryData(string fileName, Stream stream) { var binaryData = new BinaryData(); binaryData.FileName = fileName; binaryData.SetStream(stream); return binaryData; }
/// <summary> /// Creates BinaryData from HttpPostedFile /// </summary> /// <param name="file"></param> /// <returns></returns> public static BinaryData CreateBinaryData(HttpPostedFile file) { BinaryData result = new BinaryData(); string fileName = file.FileName; if (file.FileName.LastIndexOf("\\") > -1) fileName = file.FileName.Substring(file.FileName.LastIndexOf("\\") + 1); result.FileName = new BinaryFileName(fileName); result.ContentType = file.ContentType; result.SetStream(file.InputStream); return result; }
public static BinaryData CreateTestBinary() { var data = new BinaryData(); data.SetStream(TestTools.GetTestStream()); return data; }
internal static ContentType LoadOrCreateNew(IXPathNavigable contentTypeDefinitionXml) { //==== saves and puts the holder //-- #1 Determine name and parent's name XPathNavigator nav = contentTypeDefinitionXml.CreateNavigator().SelectSingleNode("/*[1]"); string name = nav.GetAttribute("name", ""); string parentTypeName = nav.GetAttribute("parentType", ""); //-- #2 Load ContentType ContentType contentType = ContentTypeManager.Current.GetContentTypeByName(name); //-- #3 Parent Node: if it is loaded yet use it (ReferenceEqals) Node parentNode; if (String.IsNullOrEmpty(parentTypeName)) { parentNode = (Folder)Node.LoadNode(Repository.ContentTypesFolderPath); } else { parentNode = ContentTypeManager.Current.GetContentTypeByName(parentTypeName); if (parentNode == null) throw new ApplicationException(String.Concat(SR.Exceptions.Content.Msg_UnknownContentType, ": ", parentTypeName)); } //-- #4 Create ContentType if it does not exist if (contentType == null) { contentType = new ContentType(parentNode); contentType.Name = name; } //-- #5 Update hierarchy if parent is changed if (contentType.ParentId != parentNode.Id) { throw new NotImplementedException("Change ContentType hierarchy is not implemented"); } //-- #6 Set Binary data BinaryData binaryData = new BinaryData(); binaryData.FileName = new BinaryFileName(name, ContentType.ContentTypeFileNameExtension); binaryData.SetStream(Tools.GetStreamFromString(contentTypeDefinitionXml.CreateNavigator().OuterXml)); contentType.Binary = binaryData; //contentType.Save(false); //ContentTypeManager.Current.AddContentType(contentType, parentNode as ContentType); return contentType; }
public static void CopyFromStream(int contentId, Stream input, string fieldName = "Binary", BinaryData binaryData = null) { var token = StartChunk(contentId, input.Length, fieldName); Node node; PropertyType pt; AssertChunk(contentId, fieldName, out node, out pt); DataProvider.Current.CopyFromStream(node.VersionId, token, input); CommitChunk(contentId, token, input.Length, fieldName, binaryData); }