Beispiel #1
0
        public void SetContent(Item item, Guid attachContentId)
        {
            BinaryItem binaryItem = item as BinaryItem;

            if (binaryItem != null)
            {
                byte[] data;
                if (this.itemAttach.TryGetValue(attachContentId, out data))
                {
                    binaryItem.Data = data;
                    return;
                }
                throw new KeyNotFoundException(string.Format("Attachment with key {0} for item {1} not found", attachContentId, item.Identifier));
            }
            else
            {
                ExchangeItem exchangeItem = item as ExchangeItem;
                if (exchangeItem == null)
                {
                    throw new ArgumentException("Unexpected item type");
                }
                MessageItem item2;
                if (this.messageItemAttach.TryGetValue(attachContentId, out item2))
                {
                    exchangeItem.Item = item2;
                    return;
                }
                throw new KeyNotFoundException(string.Format("Attachment with key {0} for item {1} not found", attachContentId, item.Identifier));
            }
        }
        // POST api/BinaryItem
        public async Task <HttpResponseMessage> Post(BinaryUploadRequest binaryUploadRequest)
        {
            var binaryItem = new BinaryItem
            {
                Id         = Guid.NewGuid().ToString("N"),
                ObjectId   = binaryUploadRequest.BinaryId,
                BinaryType = binaryUploadRequest.BinaryType,
                UserId     = binaryUploadRequest.UserId
            };

            binaryItem.BinaryUrl =
                await BlobUtils.SaveBinaryToAzureStorage(settings, binaryItem.Id, binaryUploadRequest.BinaryData);

            if (!string.IsNullOrEmpty(binaryItem.BinaryUrl))
            {
                BeerDrinkinContext context = new BeerDrinkinContext();
                context.BinaryItems.Add(binaryItem);
                await context.SaveChangesAsync();

                return(this.Request.CreateResponse(HttpStatusCode.OK));
            }

            return(this.Request.CreateResponse(HttpStatusCode.Conflict,
                                               "Something wrong"));
        }
        public ProcessingResultBase Process(Item item, NullTemplate template)
        {
            var extension = item.SourceKey.Split(".").Last();
            var htmlPath  = item.SourceKey.Replace("." + extension, ".html");

            return(item switch
            {
                TextItem textItem => new HtmlResult(textItem.Content, htmlPath),
                BinaryItem binaryItem => new BinaryResult(binaryItem.Content, item.SourceKey),
                _ => throw new InvalidOperationException("No Template Engine doesn't know what to do with this.")
            });
Beispiel #4
0
        public void VarBinaryNullTest()
        {
            var store = GetTestStore();

            store.AddType <BinaryItem>();

            var item = new BinaryItem();

            store.Insert(item);

            var test = store.Select <BinaryItem>(item.ID);
        }
 /// <summary>
 /// Parse the LeafNodeObjectData structure.
 /// </summary>
 /// <param name="s">An stream containing LeafNodeObjectData structure.</param>
 public override void Parse(Stream s)
 {
     base.Parse(s);
     this.LeafNodeStart = new bit16StreamObjectHeaderStart();
     this.LeafNodeStart.Parse(s);
     this.SignatureHeader = new bit16StreamObjectHeaderStart();
     this.SignatureHeader.Parse(s);
     this.SignatureData = new BinaryItem();
     this.SignatureData.Parse(s);
     this.DataSizeHeader = new bit16StreamObjectHeaderStart();
     this.DataSizeHeader.Parse(s);
     this.DataSize    = ReadUlong();
     this.LeafNodeEnd = new bit8StreamObjectHeaderEnd();
     this.LeafNodeEnd.Parse(s);
 }
 /// <summary>
 /// Parse the LeafNodeObjectData structure.
 /// </summary>
 /// <param name="s">A stream containing LeafNodeObjectData structure.</param>
 public override void Parse(Stream s)
 {
     base.Parse(s);
     this.LeafNodeStart = new bit16StreamObjectHeaderStart();
     this.LeafNodeStart.Parse(s);
     this.SignatureHeader = new bit16StreamObjectHeaderStart();
     this.SignatureHeader.Parse(s);
     this.SignatureData = new BinaryItem();
     this.SignatureData.Parse(s);
     this.DataSizeHeader = new bit16StreamObjectHeaderStart();
     this.DataSizeHeader.Parse(s);
     this.DataSize = ReadUlong();
     if (ContainsStreamObjectStart16BitHeader(0x2F))
     {
         this.OtherData = new UnKnowStructure();
         this.OtherData.Parse(s);
     }
     this.LeafNodeEnd = new bit8StreamObjectHeaderEnd();
     this.LeafNodeEnd.Parse(s);
 }
        public void FromBinaryPost_ReturnsBadResult(string binary, string errorMessage)
        {
            // Arrange
            var controller = new Base64Controller();

            // Act
            BinaryItem bi = new BinaryItem();

            bi.binary = binary;
            IActionResult actionResult = controller.PostFromBinary(bi);

            // Assert
            Assert.NotNull(actionResult);

            BadRequestObjectResult result = actionResult as BadRequestObjectResult;

            Assert.NotNull(result);

            string message = result.Value as string;

            Assert.Equal(errorMessage, message);
        }
Beispiel #8
0
        public IActionResult PostFromBinary([FromBody] BinaryItem value)
        {
            if (value == null || !ModelState.IsValid)
            {
                return(BadRequest("empty request"));
            }

            BitString bs;

            try {
                bs = new BitString(value.binary);
            } catch (InvalidOperationException e) {
                return(BadRequest("invalid bit string"));
            }

            if (!bs.isValid())
            {
                return(BadRequest("invalid bit string"));
            }

            return(Ok(bs.asBase64()));
        }
Beispiel #9
0
        /// <summary>
        /// Loads the file as data from XML data
        /// </summary>
        /// <param name="fileDocument">XML document containing the file</param>
        /// <param name="loadHeaderOnly">if true loads only header information</param>
        public void Load(XDocument fileDocument, bool loadHeaderOnly)
        {
            if (fileDocument == null)
            {
                throw new ArgumentNullException(nameof(fileDocument));
            }
            if (fileDocument.Root == null)
            {
                throw new ArgumentException("Document's root is NULL (empty document passed)");
            }

            // theoretically the namespace should be "http://www.gribuser.ru/xml/fictionbook/2.0" but just to be sure with invalid files
            _fileNameSpace = fileDocument.Root.GetDefaultNamespace();

            _styles.Clear();
            IEnumerable <XElement> xStyles = fileDocument.Root.Elements(_fileNameSpace + StyleElement.StyleElementName).ToArray();

            // attempt to load some bad FB2 with wrong namespace
            if (!xStyles.Any())
            {
                xStyles = fileDocument.Elements(StyleElement.StyleElementName);
            }
            foreach (var style in xStyles)
            {
                var element = new StyleElement();
                try
                {
                    element.Load(style);
                    _styles.Add(element);
                }
                catch
                {
                    // ignored
                }
            }

            LoadDescriptionSection(fileDocument);

            if (!loadHeaderOnly)
            {
                XNamespace namespaceUsed = _fileNameSpace;
                // Load body elements (first is main text)
                if (fileDocument.Root != null)
                {
                    IEnumerable <XElement> xBodyElements = fileDocument.Root.Elements(_fileNameSpace + Fb2TextBodyElementName).ToArray();
                    // try to read some badly formatted FB2 files
                    if (!xBodyElements.Any())
                    {
                        namespaceUsed = "";
                        xBodyElements = fileDocument.Root.Elements(namespaceUsed + Fb2TextBodyElementName);
                    }
                    foreach (var body in xBodyElements)
                    {
                        var bodyItem = new BodyItem {
                            NameSpace = namespaceUsed
                        };
                        try
                        {
                            bodyItem.Load(body);
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                        _bodiesList.Add(bodyItem);
                    }
                }
                if (_bodiesList.Count > 0)
                {
                    _mainBody = _bodiesList[0];
                }


                // Load binaries sections (currently images only)
                if (fileDocument.Root != null)
                {
                    IEnumerable <XElement> xBinaryElements = fileDocument.Root.Elements(namespaceUsed + Fb2BinaryElementName).ToArray();
                    if (!xBinaryElements.Any())
                    {
                        xBinaryElements = fileDocument.Root.Elements(Fb2BinaryElementName);
                    }
                    foreach (var binaryElement in xBinaryElements)
                    {
                        var item = new BinaryItem();
                        try
                        {
                            item.Load(binaryElement);
                        }
                        catch
                        {
                            continue;
                        }
                        // add just unique IDs to fix some invalid FB2s
                        if (!_binaryObjects.ContainsKey(item.Id))
                        {
                            _binaryObjects.Add(item.Id, item);
                        }
                    }
                }
            }
        }
Beispiel #10
0
        private void LoadDescriptionSection(XDocument fileDocument, bool loadBinaryItems = true)
        {
            if (fileDocument == null)
            {
                throw new ArgumentNullException(nameof(fileDocument));
            }
            if (fileDocument.Root == null)
            {
                throw new NullReferenceException("LoadDescriptionSection: Root is null");
            }
            XElement xTextDescription = fileDocument.Root.Element(_fileNameSpace + Fb2TextDescriptionElementName);
            // attempt to load some bad FB2 with wrong namespace
            XNamespace namespaceUsed = _fileNameSpace;

            if (xTextDescription == null)
            {
                namespaceUsed    = "";
                xTextDescription = fileDocument.Root.Element(Fb2TextDescriptionElementName);
            }
            if (xTextDescription != null)
            {
                // Load Title info
                XElement xTitleInfo = xTextDescription.Element(namespaceUsed + TitleInfoElementName);
                if (xTitleInfo != null)
                {
                    _titleInfo.Namespace = namespaceUsed;
                    try
                    {
                        _titleInfo.Load(xTitleInfo);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("Error reading title info : {0}", ex.Message);
                    }
                }

                // Load Src Title info
                XElement xSrcTitleInfo = xTextDescription.Element(namespaceUsed + SrcTitleInfoElementName);
                if (xSrcTitleInfo != null)
                {
                    _srcTitleInfo.Namespace = _fileNameSpace;
                    try
                    {
                        _srcTitleInfo.Load(xSrcTitleInfo);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("Error reading source title info : {0}", ex.Message);
                    }
                }

                // Load document info
                XElement xDocumentInfo = xTextDescription.Element(namespaceUsed + DocumentInfoElementName);
                if (xDocumentInfo != null)
                {
                    _documentInfo.Namespace = _fileNameSpace;
                    try
                    {
                        _documentInfo.Load(xDocumentInfo);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("Error reading document info : {0}", ex.Message);
                    }
                }

                // Load publish info
                XElement xPublishInfo = xTextDescription.Element(namespaceUsed + ItemPublishInfo.PublishInfoElementName);
                if (xPublishInfo != null)
                {
                    _publishInfo.Namespace = _fileNameSpace;
                    try
                    {
                        _publishInfo.Load(xPublishInfo);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("Error reading publishing info : {0}", ex.Message);
                    }
                }

                XElement xCustomInfo = xTextDescription.Element(namespaceUsed + ItemCustomInfo.CustomInfoElementName);
                if (xCustomInfo != null)
                {
                    var custElement = new ItemCustomInfo {
                        Namespace = _fileNameSpace
                    };
                    try
                    {
                        custElement.Load(xCustomInfo);
                        _customInfo.Add(custElement);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("Error reading custom info : {0}", ex.Message);
                    }
                }

                IEnumerable <XElement> xInstructions = xTextDescription.Elements(xTextDescription.Name.Namespace + "output");
                int outputCount = 0;
                _output.Clear();
                foreach (var xInstruction in xInstructions)
                {
                    // only two elements allowed by scheme
                    if (outputCount > 1)
                    {
                        break;
                    }
                    var outp = new ShareInstructionType {
                        Namespace = namespaceUsed
                    };
                    try
                    {
                        outp.Load(xInstruction);
                        _output.Add(outp);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("Error reading output instructions : {0}", ex);
                    }
                    finally
                    {
                        outputCount++;
                    }
                }

                if (loadBinaryItems && _titleInfo.Cover != null)
                {
                    foreach (InlineImageItem coverImag in _titleInfo.Cover.CoverpageImages)
                    {
                        if (string.IsNullOrEmpty(coverImag.HRef))
                        {
                            continue;
                        }
                        string coverRef = coverImag.HRef.Substring(0, 1) == "#" ? coverImag.HRef.Substring(1) : coverImag.HRef;
                        IEnumerable <XElement> xBinaryElements =
                            fileDocument.Root.Elements(_fileNameSpace + Fb2BinaryElementName).Where(
                                cov => ((cov.Attribute("id") != null) && (cov.Attribute("id").Value == coverRef)));
                        foreach (var binaryElement in xBinaryElements)
                        {
                            var item = new BinaryItem();
                            try
                            {
                                item.Load(binaryElement);
                            }
                            catch (Exception)
                            {
                                continue;
                            }
                            // add just unique IDs to fix some invalid FB2s
                            if (!_binaryObjects.ContainsKey(item.Id))
                            {
                                _binaryObjects.Add(item.Id, item);
                            }
                        }
                    }
                }
            }
        }
Beispiel #11
0
 /// <summary>
 /// Обертка для создания картинки
 /// </summary>
 /// <param name="item">Картинка</param>
 /// <param name="id">Идентификатор картинки</param>
 /// <returns></returns>
 public static ImageLine ToImageLine(this BinaryItem item, string id)
 {
     return(new ImageLine {
         Key = item.Id, Id = id
     });
 }