protected override object GetModel() { string subscriptionCtd; using (new SystemAccount()) { var ctdFile = Node.LoadNode("/Root/System/Schema/ContentTypes/GenericContent/Subscription") as ContentType; if (ctdFile != null) { using (var ctdStream = ctdFile.Binary.GetStream()) { subscriptionCtd = RepositoryTools.GetStreamString(ctdStream); } } else { throw new InvalidOperationException("Subscription CTD not found."); } } var currentSite = PortalContext.Current.Site; var siteUrl = PortalContext.Current.SiteUrl; if (this.User == null) { return(null); } // edit subscription or create new if not exists var subscription = Subscription.GetSubscriptionByUser(this.User.Path, this.ContentPath); if (subscription != null) { IsSubscriptionNew = false; } else { subscription = new Subscription() { ContentPath = this.ContentPath, Frequency = NotificationFrequency.Immediately, IsActive = true, UserEmail = this.User.Email, UserPath = this.User.Path, UserId = this.User.Id, UserName = this.User.Name, Language = "en", SitePath = currentSite?.Path, SiteUrl = siteUrl }; IsSubscriptionNew = true; } var sct = Content.Create(subscription, subscriptionCtd); var rch = sct.ContentHandler as Content.RuntimeContentHandler; rch?.SetIsNew(IsSubscriptionNew); return(sct); }
// ================================================================================================ Public methods /// <summary> /// Gets Binary of a Content Repository File in a string. /// </summary> /// <param name="filePath"></param> /// <returns></returns> public static string GetMarkupString(string filePath) { var skinResolvedPath = SkinManager.Resolve(filePath); // Elevation: post and comment markup files should not be // visible to users. Please Control post and comment // visibility by assigning permissions to // post and comment content. using (new SystemAccount()) { var file = Node.Load <SNCR.File>(skinResolvedPath); if (file == null) { return(null); } string markupStr = null; using (var stream = file.Binary.GetStream()) { markupStr = RepositoryTools.GetStreamString(stream); } return(markupStr); } }
private void HackDatabaseForMorePermissiveLoadTest(string contentTypeName, string oldCtd, string newCtd) { // Get related data row (FileDoc of the InMemoryDatabase) var dataProvider = (InMemoryDataProvider)Providers.Instance.DataProvider; var db = dataProvider.DB; var fileRow = db.Files.First(x => x.FileNameWithoutExtension == contentTypeName); // Get blob id var bp = (InMemoryBlobProvider)Providers.Instance.BlobStorage.GetProvider(0); var data = (InMemoryBlobProviderData)bp.ParseData(fileRow.BlobProviderData); // Get and check the old CTD from the related blob var bpAcc = new ObjectAccessor(bp); var blobs = (Dictionary <Guid, byte[]>)bpAcc.GetField("_blobStorage"); var oldBuffer = blobs[data.BlobId]; Assert.AreEqual(oldCtd, RepositoryTools.GetStreamString(new MemoryStream(oldBuffer))); // Change the related blob to the invalid CTD var stream = (MemoryStream)RepositoryTools.GetStreamFromString(newCtd); var newBuffer = new byte[stream.Length]; var newStream = new MemoryStream(newBuffer); stream.CopyTo(newStream); fileRow.Buffer = newBuffer; fileRow.Size = newBuffer.Length; }
public void MultiStep_Existing_Incremental_CSrv() { Test(() => { var root = CreateTestRoot(); var file = new File(root) { Name = "test.txt" }; file.Binary.SetStream(RepositoryTools.GetStreamFromString("test file")); file.Save(); // ACTION: create a new file with the same name var expected = "new file content"; var file2 = new File(root) { Name = file.Name }; file2.Binary.SetStream(RepositoryTools.GetStreamFromString(expected)); // this should prevent the exception and simply generate a new name file2.AllowIncrementalNaming = true; // this is normal in case of chunk upload, it should not throw an exception file2.Save(SavingMode.StartMultistepSave); file2.FinalizeContent(); // ASSERT: Do not throw any exception and file is saved var loaded = Node.Load <File>(file2.Id); var actual = RepositoryTools.GetStreamString(loaded.Binary.GetStream()); Assert.AreEqual(expected, actual); }); }
public void SharedLock_Save_CheckedOutForMe_Unlocked_Upload() { var newContent = "Dolor sit amet..."; var context = OperationContext.Create().Checkout().UpdateFileContent(newContent); Assert.AreEqual(newContent, RepositoryTools.GetStreamString(context.LoadTestFile().Binary.GetStream())); }
public void SharedLock_Save_CheckedOutForMe_LockedSame_PutFile() { var newContent = "Dolor sit amet..."; var lockValue = "LCK_" + Guid.NewGuid(); var context = OperationContext.Create().Lock(lockValue).Checkout().WopiSave(lockValue, newContent); Assert.AreEqual(newContent, RepositoryTools.GetStreamString(context.LoadTestFile().Binary.GetStream())); }
//[TestMethod] public void InitialData_CtdLoad() { InitialDataTest(() => { var fileContentType = ContentType.GetByName("File"); var ctd = RepositoryTools.GetStreamString(fileContentType.Binary.GetStream()); Assert.IsNotNull(ctd); Assert.IsTrue(ctd.Length > 10); }); }
public void SharedLock_Save_CheckedOutForMe_Unlocked_PutFile() { var newContent = "Dolor sit amet..."; var lockValue = "LCK_" + Guid.NewGuid(); var context = OperationContext.Create().Checkout().WopiSave(lockValue, newContent); // expected result: file was not changed Assert.AreEqual(OperationContext.OriginalFileContent, RepositoryTools.GetStreamString(context.LoadTestFile().Binary.GetStream())); }
private void InstallContentType() { string contentString = RepositoryTools.GetStreamString(_handler.Context.Request.InputStream); if (!string.IsNullOrEmpty(contentString)) { ContentTypeInstaller.InstallContentType(contentString); } _handler.Context.Response.StatusCode = 200; }
public static string RenderCell(string fieldFullName, string contentListPath) { if (string.IsNullOrEmpty(fieldFullName)) { return(string.Empty); } try { var bindingName = FieldSetting.GetBindingNameFromFullName(fieldFullName); FieldSetting fieldSetting; var pathList = GetCellTemplatePaths(fieldFullName, contentListPath, out fieldSetting); if (pathList.Count > 0) { // get the template with the system account using (new SystemAccount()) { foreach (var templatePath in pathList) { var actualPath = SkinManagerBase.Resolve(templatePath); if (!Node.Exists(actualPath)) { continue; } var template = Node.Load <File>(actualPath); if (template == null) { continue; } // replace the template parameters var templateString = RepositoryTools.GetStreamString(template.Binary.GetStream()) .Replace("@@bindingName@@", bindingName) .Replace("@@fullName@@", fieldFullName); if (fieldSetting != null) { templateString = templateString.Replace("@@fieldName@@", fieldSetting.Name); } return(templateString); } } } } catch (Exception ex) { SnLog.WriteException(ex); } // default behavior: simple text rendering return(string.Format("<%# Eval(\"{0}\") %>", FieldSetting.GetBindingNameFromFullName(fieldFullName))); }
private Dictionary <string, string> GetTextContents() { var settingContent = Content.Load(Repository.SettingsFolderPath); settingContent.ChildrenDefinition.EnableAutofilters = FilterStatus.Disabled; var settingContents = settingContent.Children.ToArray(); return(settingContents .ToDictionary( x => x.Name, x => RepositoryTools.GetStreamString(((File)x.ContentHandler).Binary.GetStream()))); }
public async Task Cors_HttpContext_PolicyFound() { await Test(async() => { // set allowed domains for test var setting = await Node.LoadAsync <Settings>( RepositoryPath.Combine(Repository.SettingsFolderPath, "Portal.settings"), CancellationToken.None); var currentSettingText = RepositoryTools.GetStreamString(setting.Binary.GetStream()); var newSettingText = EditJson(currentSettingText, @" { ""AllowedOriginDomains"": [ ""localhost:*"", ""*.sensenet.com"" ] } "); setting.Binary.SetStream(RepositoryTools.GetStreamFromString(newSettingText)); setting.Save(SavingMode.KeepVersion); // default settings support localhost and sensenet.com var p = await AssertOriginPrivate("localhost", true); Assert.IsTrue(p.SupportsCredentials); p = await AssertOriginPrivate("localhost:123", true); Assert.IsTrue(p.SupportsCredentials); p = await AssertOriginPrivate("example.sensenet.com", true); Assert.IsTrue(p.SupportsCredentials); await AssertOriginPrivate("sensenet.com", false); await AssertOriginPrivate("example.com", false); }); async Task <CorsPolicy> AssertOriginPrivate(string origin, bool expected) { var cpp = new SnCorsPolicyProvider(null); var context = new DefaultHttpContext(); context.Request.Headers["Origin"] = origin; var p = await cpp.GetPolicyAsync(context, SnCorsPolicyProvider.DefaultSenseNetCorsPolicyName); Assert.AreEqual(expected, p.Origins.Contains(origin)); return(p); } }
public BinaryData GetASPXBinaryByPageTemplate(Page page, PageTemplate pageTemplate) { if (page == null) { throw new ArgumentNullException("page"); } if (pageTemplate == null) { throw new ArgumentNullException("pageTemplate"); } BinaryData binaryData = new BinaryData(); if (page.Binary != null) { binaryData = page.Binary; } string pageTmp = RepositoryTools.GetStreamString(pageTemplate.Binary.GetStream()); IList <object> fragments = SplitPageTemplate(pageTmp); StringBuilder aspx = new StringBuilder(); // MasterPage is inside the PageTemplates folder. var parentPath = RepositoryPath.GetParentPath(pageTemplate.Path); aspx.AppendFormat(ASPXHEADER, string.Concat("/", GetFileNameWithoutExt(pageTemplate.Name), MASTER), parentPath); for (int i = 0; i < fragments.Count; i++) { if (fragments[i] is PageZone) { PageZone zone = fragments[i] as PageZone; aspx.AppendFormat(WEBPARTZONE, zone.Name, zone.InnerText, zone.AttrListText); } } binaryData.SetStream(RepositoryTools.GetStreamFromString(aspx.ToString())); binaryData.FileName = new BinaryFileName(ASPX); binaryData.ContentType = ASPXCONTENTTYPE; return(binaryData); }
/// <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 = RepositoryTools.GetStreamString(GetFilteredStream(stream)); } } catch (Exception ex) { // failed to load stream // streamString will be string.Empty, no need for special actions SnLog.WriteException(ex); } if (_textBox != null) { _textBox.Text = streamString; } #region template if (!IsTemplated) { return; } SetTitleAndDescription(); var innerControl = GetInnerControl() as TextBox; if (innerControl != null) { innerControl.Text = streamString; } #endregion }
private void GenerateBinaryData() { string pageTmp = string.Empty; if (CheckPageTemplateBinaryStream(PageTemplateNode)) { pageTmp = RepositoryTools.GetStreamString(PageTemplateNode.Binary.GetStream()); } string oldPageTmp = string.Empty; if (OriginalStream != null) { oldPageTmp = RepositoryTools.GetStreamString(OriginalStream); } string fileName = GetFileNameWithoutExt(); GeneratePage(oldPageTmp, pageTmp, fileName); }
private void AssertRawData(DbFile dbFile, bool useChunk, string expectedText) { byte[][] data = BlobStoragePlatform.GetRawData(dbFile.FileId); if (dbFile.Size == 0L) { Assert.AreEqual(0, data.Length); } else if (useChunk && dbFile.BlobProvider == null) { Assert.AreEqual(1, data.Length); } else if (useChunk && dbFile.BlobProvider != null) { Assert.AreNotEqual(1, data.Length); } else { Assert.AreEqual(1, data.Length); } var length = data.Select(d => d.Length).Sum(); var buffer = new byte[length]; var offset = 0; foreach (var item in data) { Array.Copy(item, 0, buffer, offset, item.Length); offset += item.Length; } string actualText; using (var stream = new IO.MemoryStream(buffer)) actualText = RepositoryTools.GetStreamString(stream); Assert.AreEqual(expectedText, actualText); }
private Content GetRealParent() { if (!string.Equals(ContentTypeName, "ContentType", StringComparison.InvariantCultureIgnoreCase)) { return(Content); } // Workaround for content types. The client does not know where to put // the new type in the hierarchy. The real parent is determined by // looking into the content type xml. string ctd; if (FormFile != null) { using var stream = FormFile.OpenReadStream(); ctd = RepositoryTools.GetStreamString(stream); // request stream can be loaded only once, we have to save the value FileText = ctd; FormFile = null; } else { ctd = FileText; } var(parentName, name) = GetContentTypeInfo(ctd); var parentType = ContentType.GetByName(parentName); if (parentType != null) { FileName = name; return(Content.Load(parentType.Id)); } return(Content); }
public void InitialData_Core_GetBlobBytes_HexDump_WithoutHeader() { var path = "/Root/Anything"; var propertyName = "Binary"; var data = new InitialData { Blobs = new Dictionary <string, string>() }; var buffer = new byte[] { 0xFF, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }; var stream = new MemoryStream(buffer); var dump = InitialData.GetHexDump(stream); data.Blobs.Add($"{propertyName}:{path}", dump); // ACTION var bytes = data.GetBlobBytes(path, propertyName); // ASSERT // Without header the hex-dump need to be parsed as text instead of bytes Assert.IsNotNull(bytes); var expected = InitialData.GetHexDump(buffer); var actual = RepositoryTools.GetStreamString(new MemoryStream(bytes)); Assert.AreEqual(expected, actual); }
protected override object GetModel() { string subscriptionCtd; using (new SystemAccount()) { var ctdFile = Node.LoadNode("/Root/System/Schema/ContentTypes/GenericContent/Subscription") as ContentType; if (ctdFile != null) { using (var ctdStream = ctdFile.Binary.GetStream()) { subscriptionCtd = RepositoryTools.GetStreamString(ctdStream); } } else { throw new InvalidOperationException("Subscription CTD not found."); } } return((from subscripton in Subscription.GetSubscriptionsByUser(this.User.Path) where !string.IsNullOrEmpty(subscripton.ContentPath) && Node.Exists(subscripton.ContentPath) select SN.Content.Create(subscripton, subscriptionCtd)).ToList()); }
public override string Extract(Stream stream, TextExtractorContext context) { return(RepositoryTools.GetStreamString(stream)); }
/// <summary> /// Gets the text content from a given path and processes it. Override this method if you want to implement custom logic when each file is loaded. /// </summary> /// <param name="path">The path from which to the content should be retrieved.</param> /// <returns>The processed text content of the given path, or null if it was not found.</returns> protected virtual string GetTextFromPath(string path) { if (path[0] == '/') { // This is a repository URL var fsPath = HostingEnvironment.MapPath(path); var fileNodeHead = NodeHead.Get(path); var fileNode = fileNodeHead != null && SecurityHandler.HasPermission(fileNodeHead, PermissionType.Open) ? Node.Load <File>(path) : null; System.IO.Stream stream = null; if ((WebApplication.DiskFSSupportMode == DiskFSSupportMode.Prefer || fileNode == null) && System.IO.File.Exists(fsPath)) { // If DiskFsSupportMode is Prefer and the file exists, or it's fallback but the node doesn't exist in the repo get it from the file system stream = new System.IO.FileStream(fsPath, System.IO.FileMode.Open, System.IO.FileAccess.Read); } else if (path[0] == '/' && fileNode != null) { // If the node exists, get it from the repo stream = fileNode.Binary.GetStream(); } else if (path.StartsWith("/" + ResourceHandler.UrlPart + "/")) { // Special case, this is a resource URL, we will just render the resource script here var parsed = ResourceHandler.ParseUrl(path); if (parsed == null) { return(null); } var className = parsed.Item2; var culture = CultureInfo.GetCultureInfo(parsed.Item1); try { return(ResourceScripter.RenderResourceScript(className, culture)); } catch (Exception exc) { SnLog.WriteException(exc); return(null); } } try { return(stream != null?RepositoryTools.GetStreamString(stream) : null); } finally { if (stream != null) { stream.Dispose(); } } } if (path.StartsWith("http://") || path.StartsWith("https://")) { // This is a web URL try { HttpWebRequest req; if (PortalContext.IsKnownUrl(path)) { string url; var ub = new UriBuilder(path); var origHost = ub.Host; ub.Host = "127.0.0.1"; url = ub.Uri.ToString(); req = (HttpWebRequest)HttpWebRequest.Create(url); req.Host = origHost; } else { req = (HttpWebRequest)HttpWebRequest.Create(path); } req.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; var res = req.GetResponse(); using (var st = res.GetResponseStream()) using (var stream = new System.IO.MemoryStream()) { st.CopyTo(stream); var arr = stream.ToArray(); var result = Encoding.UTF8.GetString(arr); return(result); } } catch (Exception exc) { SnLog.WriteException(exc, "Error during bundle request: ", EventId.Portal, properties: new Dictionary <string, object> { { "Path", path } }); return(null); } } return(null); }
public override string Extract(Stream stream, TextExtractorContext context) { return(RichTextStripper.StripRichTextFormat(RepositoryTools.GetStreamString(stream))); }
private void HandleContent(string parentPath, string fileName, Node parentNode, Node node) { Content content = null; var contentXml = new XmlDocument(); string contentString = RepositoryTools.GetStreamString(_handler.Context.Request.InputStream); if (!string.IsNullOrEmpty(contentString)) { contentXml.LoadXml(contentString); // new content or previously uploded binary exists! if (node == null || node is IFile) { string ctName = contentXml.SelectSingleNode("/ContentMetaData/ContentType").InnerText; if (node == null || ctName.CompareTo(node.NodeType.Name) != 0) { WebDavProvider.Current.AssertCreateContent(parentPath, fileName, ctName); var nodeType = ActiveSchema.NodeTypes[ctName]; node = nodeType.CreateInstance(parentNode); node.Name = fileName; } } else { WebDavProvider.Current.AssertModifyContent(node); } content = Content.Create(node); XmlNodeList allFields = contentXml.SelectNodes("/ContentMetaData/Fields/*"); XmlNodeList binaryFields = contentXml.SelectNodes("/ContentMetaData/Fields/*[@attachment]"); // set attachments first foreach (XmlNode field in binaryFields) { string attachmentName = field.Attributes["attachment"].Value; var attachment = Node.LoadNode(RepositoryPath.Combine(parentPath, attachmentName)) as SN.File; // previously uploaded attachment found if (attachment != null && attachment.Id != node.Id) { attachment.Name = Guid.NewGuid().ToString(); attachment.Save(); SetBinaryStream(content.ContentHandler, attachment.Binary.GetStream(), field.Name, attachmentName); attachment.Delete(); } } var transferringContext = new ImportContext(allFields, "", node.Id == 0, true, false); // import flat properties content.ImportFieldData(transferringContext); // update references transferringContext.UpdateReferences = true; content.ImportFieldData(transferringContext); } _handler.Context.Response.StatusCode = 200; }