예제 #1
0
 private static void WriteDatas(HttpContext context, BinaryData cacheBinary)
 {
     if (cacheBinary.GetStream() != null)
     {
         MemoryStream result = new MemoryStream();
         result = (MemoryStream)cacheBinary.GetStream();
         context.Response.BinaryWrite(result.ToArray());
     }
 }
예제 #2
0
        public void GenericContent_KeepBinaryAfterPublish()
        {
            Page samplePage = new Page(TestRoot);

            samplePage.Name           = "SamplePage";
            samplePage.VersioningMode = ContentRepository.Versioning.VersioningType.MajorAndMinor;
            samplePage.ApprovingMode  = ContentRepository.Versioning.ApprovingType.True;

            //set binaries
            BinaryData pageBinaryData = CreateBinaryDataFromString("Page Binary");
            BinaryData psBinaryData   = CreateBinaryDataFromString("Page PersonalizationSettings");

            samplePage.Binary = pageBinaryData;
            samplePage.PersonalizationSettings = psBinaryData;

            //save page
            samplePage.Save();
            samplePage.CheckOut();
            samplePage.Publish();

            //asserts
            //TODO: CheckBinariesInPageByString hosszutavon folosleges
            CheckBinariesInPageByString(samplePage, "Page Binary", "Page PersonalizationSettings");
            CheckBinariesInPageByByte(samplePage, pageBinaryData.GetStream(), psBinaryData.GetStream());
        }
예제 #3
0
파일: Exporter.cs 프로젝트: y1027/sensenet
        private static void ExportContentType(Content content, ExportContext context)
        {
            BinaryData binaryData = ((ContentType)content.ContentHandler).Binary;

            var name   = content.Name + "Ctd.xml";
            var fsPath = Path.Combine(context.ContentTypeDirectory, name);

            Stream     source = null;
            FileStream target = null;

            try
            {
                source = binaryData.GetStream();
                target = new FileStream(fsPath, FileMode.Create);
                for (var i = 0; i < source.Length; i++)
                {
                    target.WriteByte((byte)source.ReadByte());
                }
            }
            finally
            {
                source?.Close();
                if (target != null)
                {
                    target.Flush();
                    target.Close();
                }
            }
        }
예제 #4
0
파일: EditText.cs 프로젝트: y1027/sensenet
        private void ExecuteOnContent(ExecutionContext context)
        {
            context.AssertRepositoryStarted();

            var path    = (string)context.ResolveVariable(Path);
            var content = Content.Load(path);
            var data    = content[Field ?? "Binary"];

            BinaryData binaryData = null;
            var        text       = data as string;

            if (text == null)
            {
                binaryData = data as BinaryData;
                if (binaryData != null)
                {
                    using (var r = new StreamReader(binaryData.GetStream()))
                        text = r.ReadToEnd();
                }
            }

            text = Edit(text, context);

            if (binaryData != null)
            {
                binaryData.SetStream(RepositoryTools.GetStreamFromString(text));
            }
            else
            {
                content[Field] = text;
            }

            content.SaveSameVersion();
        }
예제 #5
0
        private string GetStringFromBinaryData(BinaryData binary)
        {
            Stream       stream = binary.GetStream();
            StreamReader sr     = new StreamReader(stream, Encoding.UTF8);

            string value = sr.ReadToEnd();

            return(value);
        }
예제 #6
0
        public void BinaryData_DefaultValues()
        {
            BinaryData target = new BinaryData();

            Assert.AreEqual(0, target.Id, "ContentRepository.Storage.BinaryData.Id default value is incorrect.");
            Assert.AreEqual(string.Empty, target.ContentType, "ContentRepository.Storage.BinaryData.ContentType default value is incorrect.");
            Assert.AreEqual(string.Empty, target.FileName.Extension, "ContentRepository.Storage.BinaryData.FileName.Extension default value is incorrect.");
            Assert.AreEqual(string.Empty, target.FileName.FileNameWithoutExtension, "ContentRepository.Storage.BinaryData.FileName.FileNameWithoutExtension default value is incorrect.");
            Assert.AreEqual(Convert.ToInt64(-1), target.Size, "ContentRepository.Storage.BinaryData.Size default value is incorrect.");
            Assert.AreEqual(null, target.GetStream(), "ContentRepository.Storage.BinaryData.Stream default value is incorrect.");
        }
예제 #7
0
        protected override void ExportData(XmlWriter writer, ExportContext context)
        {
            // <Binary attachment="Home.aspx" />
            BinaryData binaryData = this.GetData() as BinaryData;

            //var ext = Path.GetExtension(binaryData.FileName);
            //var contentName = this.Content.Name;
            //if (!(this.Content.ContentHandler is IFolder))
            //    if (ext == Path.GetExtension(this.Content.Name))
            //        ext = "";

            //var fieldExtName = String.Empty;
            //var expectedFieldExtName = "." + this.Name;
            //if (this.Name != "Binary")
            //{
            //    if (ext.ToLower() != expectedFieldExtName.ToLower())
            //        fieldExtName = expectedFieldExtName;
            //}

            //var attName = String.Concat(contentName, fieldExtName, ext);
            //var fsPath = Path.Combine(context.CurrentDirectory, attName);

            //writer.WriteAttributeString("attachment", attName);
            var attName = WriteXmlDataPrivate(writer);
            var fsPath  = Path.Combine(context.CurrentDirectory, attName);

            Stream     source = null;
            FileStream target = null;

            try
            {
                source = binaryData.GetStream();
                target = new FileStream(fsPath, FileMode.Create);
                if (source != null)
                {
                    for (var i = 0; i < source.Length; i++)
                    {
                        target.WriteByte((byte)source.ReadByte());
                    }
                }
            }
            finally
            {
                if (source != null)
                {
                    source.Close();
                }
                if (target != null)
                {
                    target.Flush();
                    target.Close();
                }
            }
        }
예제 #8
0
        /// <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
        }
예제 #9
0
        /// <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
        }
예제 #10
0
        protected override void ExportData(XmlWriter writer, ExportContext context)
        {
            // <Binary attachment="Home.aspx" />
            BinaryData binaryData = this.GetData() as BinaryData;

            var attName = WriteXmlDataPrivate(writer);

            var fsDirectory = context.CurrentDirectory;

            if (!String.IsNullOrEmpty(fsDirectory) && Directory.Exists(fsDirectory))
            {
                Stream     source = null;
                FileStream target = null;
                var        fsPath = Path.Combine(fsDirectory, attName);
                try
                {
                    source = binaryData.GetStream();
                    target = new FileStream(fsPath, FileMode.Create);
                    if (source != null)
                    {
                        for (var i = 0; i < source.Length; i++)
                        {
                            target.WriteByte((byte)source.ReadByte());
                        }
                    }
                }
                finally
                {
                    if (source != null)
                    {
                        source.Close();
                    }
                    if (target != null)
                    {
                        target.Flush();
                        target.Close();
                    }
                }
            }
        }
예제 #11
0
        //============================================================ Overrides

        public override Stream GetStream(Node node, string propertyName, out string contentType, out BinaryFileName fileName)
        {
            if (node == null)
            {
                throw new ArgumentNullException("node");
            }

            BinaryData binaryData = null;
            var        content    = Content.Create(node);

            //try to find a field with this name
            if (content.Fields.ContainsKey(propertyName) && content.Fields[propertyName] is BinaryField)
            {
                binaryData = content[propertyName] as BinaryData;
            }

            //no field found, try a property
            if (binaryData == null)
            {
                var property = node.PropertyTypes[propertyName];
                if (property != null && property.DataType == DataType.Binary)
                {
                    binaryData = node.GetBinary(property);
                }
            }

            if (binaryData != null)
            {
                contentType = binaryData.ContentType;
                fileName    = binaryData.FileName;

                return(binaryData.GetStream());
            }

            contentType = string.Empty;
            fileName    = string.Empty;

            return(null);
        }
예제 #12
0
        private void ExecuteOnContent(ExecutionContext context)
        {
            context.AssertRepositoryStarted();

            var content = Content.Load(Path);
            var data    = content[Field ?? "Binary"];

            BinaryData binaryData = null;
            var        text       = data as string;

            if (text == null)
            {
                binaryData = data as BinaryData;
                if (binaryData != null)
                {
                    using (var r = new StreamReader(binaryData.GetStream()))
                        text = r.ReadToEnd();
                }
            }

            if (text == null)
            {
                return;
            }

            text = text.Replace(Template, GetSource());

            if (binaryData != null)
            {
                binaryData.SetStream(Tools.GetStreamFromString(text));
            }
            else
            {
                content[Field] = text;
            }

            content.SaveSameVersion();
        }
예제 #13
0
        public void GenericContent_KeepBinaryAfterUndocheckout()
        {
            Page samplePage = new Page(TestRoot);

            samplePage.Name = "SamplePage";

            //set binaries
            BinaryData pageBinaryData = CreateBinaryDataFromString("Page Binary");
            BinaryData psBinaryData   = CreateBinaryDataFromString("Page PersonalizationSettings");

            samplePage.Binary = pageBinaryData;
            samplePage.PersonalizationSettings = psBinaryData;

            //save page
            samplePage.Save();
            samplePage.CheckOut();
            samplePage.UndoCheckOut();

            //asserts
            //TODO: CheckBinariesInPageByString hosszutavon folosleges
            CheckBinariesInPageByString(samplePage, "Page Binary", "Page PersonalizationSettings");
            CheckBinariesInPageByByte(samplePage, pageBinaryData.GetStream(), psBinaryData.GetStream());
        }
예제 #14
0
        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);
        }
예제 #15
0
        public static string GetExtract(BinaryData binaryData, Node node)
        {
            var extractor = ResolveExtractor(binaryData);

            if (extractor == null)
            {
                return(string.Empty);
            }

            var result = string.Empty;
            var stream = binaryData.GetStream();

            if (stream == null)
            {
                return(String.Empty);
            }
            if (stream.Length == 0)
            {
                return(String.Empty);
            }

            try
            {
                var ctx = new TextExtractorContext(node.VersionId);
                //-- async
                Action <TimeboxedActivity> timeboxedFunctionCall = activity =>
                {
                    var x       = (Stream)activity.InArgument;
                    var extract = extractor.Extract(x, ctx);
                    activity.OutArgument = extract;
                };

                var act = new TimeboxedActivity();
                act.InArgument = stream;
                act.Activity   = timeboxedFunctionCall;
                act.Context    = HttpContext.Current;

                var finishedWithinTime = act.ExecuteAndWait(Repository.TextExtractTimeout * 1000);
                if (!finishedWithinTime)
                {
                    act.Abort();
                    var msg = String.Format("Text extracting timeout. Version: {0}, path: {1}", node.Version, node.Path);
                    Logger.WriteWarning(Logger.EventId.NotDefined, msg);
                    return(String.Empty);
                }
                else if (act.ExecutionException != null)
                {
                    WriteError(act.ExecutionException, node);
                }
                else
                {
                    result = (string)act.OutArgument;
                }
            }
            catch (Exception e)
            {
                WriteError(e, node);
            }

            if (result == null)
            {
                Logger.WriteWarning(Logger.EventId.NotDefined, String.Format(CultureInfo.InvariantCulture, @"Couldn't extract text. VersionId: {0}, path: '{1}' ", node.VersionId, node.Path));
            }
            else
            {
                result = result.Replace('\0', '.');
            }

            return(result);
        }
예제 #16
0
        public static string GetExtract(BinaryData binaryData, Node node)
        {
            if (binaryData == null)
            {
                return(string.Empty);
            }
            var fname = binaryData.FileName;

            if (fname == null)
            {
                return(string.Empty);
            }
            var ext = fname.Extension;

            if (String.IsNullOrEmpty(ext))
            {
                return(string.Empty);
            }

            ITextExtractor extractor = null;
            var            result    = string.Empty;

            switch (ext.ToLower())
            {
            case "contenttype":
            case "xml": extractor = new XmlTextExtractor(); break;

            case "doc": extractor = new DocTextExtractor(); break;

            case "xls": extractor = new XlsTextExtractor(); break;

            case "pdf": extractor = new PdfTextExtractor(); break;

            case "docx": extractor = new DocxTextExtractor(); break;

            case "xlsx": extractor = new XlsxTextExtractor(); break;

            case "pptx": extractor = new PptxTextExtractor(); break;

            case "txt": extractor = new PlainTextExtractor(); break;

            default:
                return(String.Empty);
            }

            var stream = binaryData.GetStream();

            if (stream == null)
            {
                return(String.Empty);
            }
            if (stream.Length == 0)
            {
                return(String.Empty);
            }

            try
            {
                ////-- sync
                //result = extractor.Extract(stream);

                //-- async
                Action <TimeboxedActivity> timeboxedFunctionCall = activity =>
                {
                    var x       = (Stream)activity.InArgument;
                    var extract = extractor.Extract(x);
                    activity.OutArgument = extract;
                };

                var act = new TimeboxedActivity();
                act.InArgument = stream;
                act.Activity   = timeboxedFunctionCall;
                act.Context    = HttpContext.Current;

                var finishedWithinTime = act.ExecuteAndWait(Repository.TextExtractTimeout * 1000);
                if (!finishedWithinTime)
                {
                    act.Abort();
                    var msg = String.Format("Text extracting timeout. Version: {0}, path: {1}", node.Version, node.Path);
                    Logger.WriteWarning(msg);
                    return(String.Empty);
                }
                else if (act.ExecutionException != null)
                {
                    WriteError(act.ExecutionException, node);
                }
                else
                {
                    result = (string)act.OutArgument;
                }
            }
            catch (Exception e)
            {
                WriteError(e, node);
            }

            if (String.IsNullOrEmpty(result))
            {
                var format = @"Couldn't extract text. VersionId: {0}, path: '{1}' ";
                var inf    = String.Format(CultureInfo.InvariantCulture, format, node.VersionId, node.Path);
                Logger.WriteWarning(inf);
            }

            result = result.Replace('\0', '.');
            return(result);
        }
예제 #17
0
        public static string GetExtract(BinaryData binaryData, Node node)
        {
            using (var op = SnTrace.Index.StartOperation("Getting text extract, VId:{0}, Path:{1}", node.VersionId, node.Path))
            {
                var extractor = ResolveExtractor(binaryData);
                if (extractor == null)
                {
                    op.Successful = true;
                    return(string.Empty);
                }

                var result = string.Empty;

                using (var stream = binaryData.GetStream())
                {
                    if (stream == null || stream.Length == 0)
                    {
                        op.Successful = true;
                        return(String.Empty);
                    }

                    try
                    {
                        var ctx = new TextExtractorContext(node.VersionId);
                        // async
                        Action <TimeboxedActivity> timeboxedFunctionCall = activity =>
                        {
                            var x       = (Stream)activity.InArgument;
                            var extract = extractor.Extract(x, ctx);
                            activity.OutArgument = extract;
                        };

                        var act = new TimeboxedActivity();
                        act.InArgument = stream;
                        act.Activity   = timeboxedFunctionCall;
                        act.Context    = HttpContext.Current;

                        var finishedWithinTime = act.ExecuteAndWait(Configuration.Indexing.TextExtractTimeout * 1000);
                        if (!finishedWithinTime)
                        {
                            act.Abort();
                            var msg = String.Format("Text extracting timeout. Version: {0}, path: {1}", node.Version, node.Path);
                            SnTrace.Index.Write(msg);
                            SnLog.WriteWarning(msg);
                            op.Successful = true;
                            return(String.Empty);
                        }
                        else if (act.ExecutionException != null)
                        {
                            WriteError(act.ExecutionException, node);
                        }
                        else
                        {
                            result = (string)act.OutArgument;
                        }
                    }
                    catch (Exception e)
                    {
                        WriteError(e, node);
                    }
                }

                if (result == null)
                {
                    SnLog.WriteWarning(string.Format(CultureInfo.InvariantCulture, @"Couldn't extract text. VersionId: {0}, path: '{1}' ", node.VersionId, node.Path));
                }
                else
                {
                    result = result.Replace('\0', '.');
                }

                if (result == null)
                {
                    SnTrace.Index.Write("Couldn't extract text");
                }
                else
                {
                    SnTrace.Index.Write("Extracted length length: {0}.", result.Length);
                }

                op.Successful = true;
                return(result);
            }
        }