public void Creates_CompondDocument_for_collection_not_nested_single_class()
        {
            // Arrange
            var configuration = CreateContext();
            IEnumerable <SampleClass> objectsToTransform = CreateObjectToTransform().Take(1);
            var transformer = new JsonApiTransformerBuilder()
                              .With(CreateConfiguration())
                              .Build();

            // Act
            CompoundDocument result = transformer.Transform(objectsToTransform, configuration);

            // Assert
            Assert.NotNull(result.Data);
            var transformedObject = result.Data as ResourceCollection;

            Assert.NotNull(transformedObject);
        }
        public void Creates_CompondDocument_for_collection_not_nested_class_and_propertly_map_id()
        {
            // Arrange
            var configuration = CreateContext();
            IEnumerable <SampleClass> objectsToTransform = CreateObjectToTransform();
            var transformer = new JsonApiTransformerBuilder()
                              .With(CreateConfiguration())
                              .Build();

            // Act
            CompoundDocument result = transformer.Transform(objectsToTransform, configuration);

            // Assert
            var transformedObject = result.Data as ResourceCollection;

            Assert.Equal(transformedObject[0].Id, objectsToTransform.First().Id.ToString());
            Assert.Equal(transformedObject[1].Id, objectsToTransform.Last().Id.ToString());
        }
Ejemplo n.º 3
0
        public void Creates_CompondDocument_for_metadatawrapper_single_not_nested_class_and_propertly_map_properties()
        {
            // Arrange
            var context = CreateContext();
            MetaDataWrapper <SampleClass> objectToTransform = CreateObjectToTransform();
            var sut = new JsonApiTransformer();


            // Act
            CompoundDocument result = sut.Transform(objectToTransform, context);

            // Assert
            var transformedObject = result.Data as SingleResource;

            Assert.Equal(transformedObject.Attributes["someValue"], objectToTransform.Value.SomeValue);
            Assert.Equal(transformedObject.Attributes["date"], objectToTransform.Value.DateTime);
            Assert.Equal(transformedObject.Attributes.Count, 2);
        }
Ejemplo n.º 4
0
        private static bool TryGetWorkbook(Stream fileStream, CompoundDocument document, out Stream stream)
        {
            var workbookEntry = document.FindEntry(DirectoryEntryWorkbook, DirectoryEntryBook);

            if (workbookEntry != null)
            {
                if (workbookEntry.EntryType != STGTY.STGTY_STREAM)
                {
                    throw new ExcelReaderException(Errors.ErrorWorkbookIsNotStream);
                }

                stream = new CompoundStream(document, fileStream, workbookEntry.StreamFirstSector, (int)workbookEntry.StreamSize, workbookEntry.IsEntryMiniStream, false);
                return(true);
            }

            stream = null;
            return(false);
        }
Ejemplo n.º 5
0
        public void Creates_CompondDocument_for_metadatawrapper_single_not_nested_class_and_propertly_map_id()
        {
            // Arrange
            var context = CreateContext();
            MetaDataWrapper <SampleClass> objectToTransform = CreateObjectToTransform();
            var sut = new JsonApiTransformer()
            {
                TransformationHelper = new TransformationHelper()
            };

            // Act
            CompoundDocument result = sut.Transform(objectToTransform, context);

            // Assert
            var transformedObject = result.Data as SingleResource;

            transformedObject.Id.ShouldEqual(objectToTransform.Value.Id.ToString());
        }
        public void Creates_CompondDocument_for_single_not_nested_class_and_propertly_map_resourceName()
        {
            // Arrange
            var         context           = CreateContext();
            SampleClass objectToTransform = CreateObjectToTransform();
            var         transformer       = new JsonApiTransformerBuilder()
                                            .With(CreateConfiguration())
                                            .Build();

            // Act
            CompoundDocument result = transformer.Transform(objectToTransform, context);

            // Assert
            Assert.NotNull(result.Data);
            var transformedObject = result.Data as SingleResource;

            Assert.NotNull(transformedObject);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Creates an instance of <see cref="ExcelBinaryReader"/> or <see cref="ExcelOpenXmlReader"/>
        /// </summary>
        /// <param name="fileStream">The file stream.</param>
        /// <param name="configuration">The configuration object.</param>
        /// <returns>The excel data reader.</returns>
        public static IExcelDataReader CreateReader(Stream fileStream, ExcelReaderConfiguration configuration = null)
        {
            if (configuration == null)
            {
                configuration = new ExcelReaderConfiguration();
            }

            var probe = new byte[8];

            fileStream.Seek(0, SeekOrigin.Begin);
            fileStream.Read(probe, 0, probe.Length);
            fileStream.Seek(0, SeekOrigin.Begin);

            if (CompoundDocument.IsCompoundDocument(probe))
            {
                // Can be BIFF5-8 or password protected OpenXml
                var document = new CompoundDocument(fileStream);
                if (TryGetWorkbook(fileStream, document, out var stream))
                {
                    return(new ExcelBinaryReader(stream, configuration.Password, configuration.FallbackEncoding));
                }
                else if (TryGetEncryptedPackage(fileStream, document, configuration.Password, out stream))
                {
                    return(new ExcelOpenXmlReader(stream));
                }
                else
                {
                    throw new ExcelReaderException(Errors.ErrorStreamWorkbookNotFound);
                }
            }
            else if (XlsWorkbook.IsRawBiffStream(probe))
            {
                return(new ExcelBinaryReader(fileStream, configuration.Password, configuration.FallbackEncoding));
            }
            else if (probe[0] == 0x50 && probe[1] == 0x4B)
            {
                // zip files start with 'PK'
                return(new ExcelOpenXmlReader(fileStream));
            }
            else
            {
                throw new HeaderException(Errors.ErrorHeaderSignature);
            }
        }
Ejemplo n.º 8
0
        public void Creates_CompondDocument_for_single_not_nested_class_and_propertly_map_resourceName()
        {
            // Arrange
            var         context           = CreateContext();
            SampleClass objectToTransform = CreateObjectToTransform();
            var         sut = new JsonApiTransformer()
            {
                TransformationHelper = new TransformationHelper()
            };

            // Act
            CompoundDocument result = sut.Transform(objectToTransform, context);

            // Assert
            result.Data.ShouldNotBeNull();
            var transformedObject = result.Data as SingleResource;

            transformedObject.ShouldNotBeNull();
        }
Ejemplo n.º 9
0
        public void Creates_CompoundDocument_for_single_not_nested_class_and_properly_map_properties()
        {
            // Arrange
            var         context           = CreateContext();
            SampleClass objectToTransform = CreateObjectToTransform();
            var         transformer       = new JsonApiTransformerBuilder()
                                            .With(CreateConfiguration())
                                            .Build();

            // Act
            CompoundDocument result = transformer.Transform(objectToTransform, context);

            // Assert
            var transformedObject = result.Data as SingleResource;

            Assert.Equal(transformedObject.Attributes["someValue"], objectToTransform.SomeValue);
            Assert.Equal(transformedObject.Attributes["date"], objectToTransform.DateTime);
            Assert.Equal(transformedObject.Attributes.Count, 2);
        }
Ejemplo n.º 10
0
 //Helpmethod to output the streams in the storage
 //private void WriteDoc(CompoundDocument.StoragePart storagePart, string p)
 //{
 //    foreach (var store in storagePart.SubStorage)
 //    {
 //        string sdir=p + store.Key.Replace((char)6,'x') + "\\";
 //        Directory.CreateDirectory(sdir);
 //        WriteDoc(store.Value, sdir);
 //    }
 //    foreach (var str in storagePart.DataStreams)
 //    {
 //        File.WriteAllBytes(p + str.Key.Replace((char)6, 'x') + ".bin", str.Value);
 //    }
 //}
 /// <summary>
 /// Read the package from the OLE document and decrypt it using the supplied password
 /// </summary>
 /// <param name="stream">The memory stream. </param>
 /// <param name="encryption">The encryption object from the Package</param>
 /// <returns></returns>
 internal void DecryptPackage(MemoryStream stream, ExcelEncryption encryption, Stream outputStream)
 {
     try
     {
         if (CompoundDocument.IsCompoundDocument(stream))
         {
             var doc = new CompoundDocument(stream, this.tempFolder);
             GetStreamFromPackage(doc, encryption, outputStream);
         }
         else
         {
             throw (new InvalidDataException("The stream is not an valid/supported encrypted document."));
         }
     }
     catch// (Exception ex)
     {
         throw;
     }
 }
Ejemplo n.º 11
0
        public void Creates_CompondDocument_for_collection_not_nested_single_class()
        {
            // Arrange
            var configuration = CreateContext();
            IEnumerable <SampleClass> objectsToTransform = CreateObjectToTransform().Take(1);
            var sut = new JsonApiTransformer()
            {
                TransformationHelper = new TransformationHelper()
            };

            // Act
            CompoundDocument result = sut.Transform(objectsToTransform, configuration);

            // Assert
            result.Data.ShouldNotBeNull();
            var transformedObject = result.Data as ResourceCollection;

            transformedObject.ShouldNotBeNull();
        }
Ejemplo n.º 12
0
        public void Creates_CompondDocument_for_collection_not_nested_class_and_propertly_map_type()
        {
            // Arrange
            var configuration = CreateContext();
            IEnumerable <SampleClass> objectsToTransform = CreateObjectToTransform();
            var sut = new JsonApiTransformer()
            {
                TransformationHelper = new TransformationHelper()
            };

            // Act
            CompoundDocument result = sut.Transform(objectsToTransform, configuration);

            // Assert
            var transformedObject = result.Data as ResourceCollection;

            transformedObject[0].Type.ShouldEqual("sampleClasses");
            transformedObject[1].Type.ShouldEqual("sampleClasses");
        }
Ejemplo n.º 13
0
 //Helpmethod to output the streams in the storage
 //private void WriteDoc(CompoundDocument.StoragePart storagePart, string p)
 //{
 //    foreach (var store in storagePart.SubStorage)
 //    {
 //        string sdir=p + store.Key.Replace((char)6,'x') + "\\";
 //        Directory.CreateDirectory(sdir);
 //        WriteDoc(store.Value, sdir);
 //    }
 //    foreach (var str in storagePart.DataStreams)
 //    {
 //        File.WriteAllBytes(p + str.Key.Replace((char)6, 'x') + ".bin", str.Value);
 //    }
 //}
 /// <summary>
 /// Read the package from the OLE document and decrypt it using the supplied password
 /// </summary>
 /// <param name="stream">The memory stream. </param>
 /// <param name="encryption">The encryption object from the Package</param>
 /// <returns></returns>
 internal MemoryStream DecryptPackage(MemoryStream stream, ExcelEncryption encryption)
 {
     try
     {
         if (CompoundDocument.IsCompoundDocument(stream))
         {
             var doc = new CompoundDocument(stream);
             return(GetStreamFromPackage(doc, encryption));
         }
         else
         {
             throw (new InvalidDataException("The stream is not an valid/supported encrypted document."));
         }
     }
     catch// (Exception ex)
     {
         throw;
     }
 }
Ejemplo n.º 14
0
        public void Creates_CompoundDocument_for_single_class_with_relationship_metadata_and_properly_map_metadata()
        {
            // Arrange
            var context = CreateContext();
            SampleClassWithRelatedClassesWithRelationshipMetadata objectToTransform = CreateObjectWithRelationshipMetadataToTransform();
            var transformer = new JsonApiTransformerBuilder()
                              .With(CreateConfiguration())
                              .Build();

            // Act
            CompoundDocument result = transformer.Transform(objectToTransform, context);

            // Assert
            var transformedObject = result.Data as SingleResource;

            Assert.Equal("value100", ((SingleResourceIdentifier)(transformedObject.Relationships["relatedObject"]).Data).MetaData["meta100"]);
            Assert.Equal("value1", ((MultipleResourceIdentifiers)(transformedObject.Relationships["relatedObjects"]).Data)[0].MetaData["meta1"]);
            Assert.Equal("value2", ((MultipleResourceIdentifiers)(transformedObject.Relationships["relatedObjects"]).Data)[1].MetaData["meta2"]);
        }
Ejemplo n.º 15
0
 private void openOToolStripMenuItem_Click(object sender, EventArgs e)
 {
     try
     {
         string xlsfilter = "Excel files(*.xls)|*.xls|All files (*.*)|*.*";
         string file      = FileSelector.BrowseFile(xlsfilter);
         if (file == null)
         {
             return;
         }
         doc      = CompoundDocument.Open(file);
         IsOpened = true;
         PopulateTreeview(file);
     }
     catch (Exception error)
     {
         MessageBox.Show(error.Message);
     }
 }
Ejemplo n.º 16
0
        public void Creates_CompondDocument_for_single_not_nested_class_and_propertly_map_properties()
        {
            // Arrange
            var         context           = CreateContext();
            SampleClass objectToTransform = CreateObjectToTransform();
            var         sut = new JsonApiTransformer()
            {
                TransformationHelper = new TransformationHelper()
            };

            // Act
            CompoundDocument result = sut.Transform(objectToTransform, context);

            // Assert
            var transformedObject = result.Data as SingleResource;

            transformedObject.Attributes["someValue"].ShouldEqual(objectToTransform.SomeValue);
            transformedObject.Attributes["date"].ShouldEqual(objectToTransform.DateTime);
            transformedObject.Attributes.ShouldHaveCountOf(2);
        }
Ejemplo n.º 17
0
        public void Creates_CompoundDocument_for_list_class_and_property_map_type()
        {
            // Arrange
            var             context           = CreateContext();
            SampleListClass objectToTransform = CreateListObjectToTransform();
            var             transformer       = new JsonApiTransformerBuilder()
                                                .With(CreateConfigurationForListType())
                                                .Build();

            // Act
            CompoundDocument result = transformer.Transform(objectToTransform, context);

            // Assert
            var transformedObject = result.Data as SingleResource;

            Assert.Equal(transformedObject.Type, "sampleListClasses");
            Assert.Equal(transformedObject.Attributes.Count, 2);
            Assert.True(transformedObject.Attributes.ContainsKey("listAttribute"));
            Assert.Equal(objectToTransform.ListAttribute, transformedObject.Attributes["listAttribute"]);
        }
Ejemplo n.º 18
0
        public void Creates_CompoundDocument_for_single_class_with_no_links_and_properly_map_no_links()
        {
            // Arrange
            var         context           = CreateContext();
            SampleClass objectToTransform = CreateObjectToTransform();
            var         transformer       = new JsonApiTransformerBuilder()
                                            .With(CreateConfiguration())
                                            .Build();

            // Act
            CompoundDocument result = transformer.Transform(objectToTransform, context);

            // Assert
            Assert.NotNull(result.Data);
            var transformedObject = result.Data as SingleResource;

            Assert.NotNull(transformedObject);
            Assert.Equal(1, transformedObject.Links.Count);
            Assert.Equal("http://example.com/", ((ISimpleLink)((LinkData)transformedObject.Links)["self"]).Href);
        }
Ejemplo n.º 19
0
        private void _btSave_Click(object sender, EventArgs e)
        {
            if (doc == null)
            {
                return;
            }
            string file = FileSelector.BrowseFileForSave(FileType.All);

            if (file == null)
            {
                return;
            }

            using (CompoundDocument newDoc = CompoundDocument.Create(file))
            {
                foreach (string streamName in doc.RootStorage.Members.Keys)
                {
                    newDoc.WriteStreamData(new string[] { streamName }, doc.GetStreamData(streamName));
                }

                byte[] bookdata = doc.GetStreamData("Workbook");
                if (bookdata != null)
                {
                    if (workbook == null)
                    {
                        workbook = WorkbookDecoder.Decode(new MemoryStream(bookdata));
                    }
                    MemoryStream stream = new MemoryStream();
                    //WorkbookEncoder.Encode(workbook, stream);

                    BinaryWriter writer = new BinaryWriter(stream);
                    foreach (Record record in workbook.Records)
                    {
                        record.Write(writer);
                    }
                    writer.Close();
                    newDoc.WriteStreamData(new string[] { "Workbook" }, stream.ToArray());
                }
                newDoc.Save();
            }
        }
Ejemplo n.º 20
0
        private bool Parse(string path)
        {
            CompoundDocument doc = CompoundDocument.Load(path);

            if (doc == null)
            {
                throw new InvalidOperationException(Constants.Messages.Error_ExcelFileNotFound);
            }

            Lines.Clear();
            byte[] bookdata = doc.GetStreamData("Workbook");
            if (bookdata == null)
            {
                throw new InvalidOperationException(Constants.Messages.Error_ExcelFileNoWorkbook);
            }

            Workbook workbook = WorkbookDecoder.Decode(new MemoryStream(bookdata));

            if (workbook.Worksheets.Count == 0)
            {
                throw new InvalidOperationException(Constants.Messages.Error_ExcelFileNoWorksheet);
            }

            Worksheet sheet = workbook.Worksheets[0];

            for (int rowIndex = sheet.Cells.FirstRowIndex; rowIndex <= sheet.Cells.LastRowIndex; rowIndex++)
            {
                SourceLine line = new SourceLine();
                Row        row  = sheet.Cells.GetRow(rowIndex);
                for (int colIndex = row.FirstColIndex; colIndex <= row.LastColIndex; colIndex++)
                {
                    Cell cell = row.GetCell(colIndex);
                    line.Columns.Add(cell.StringValue);
                }
                Lines.Add(line);
            }

            doc.Close();

            return(true);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Creates an instance of <see cref="ExcelOpenXmlReader"/>
        /// </summary>
        /// <param name="fileStream">The file stream.</param>
        /// <param name="configuration">The reader configuration -or- <see langword="null"/> to use the default configuration.</param>
        /// <returns>The excel data reader.</returns>
        public static IExcelDataReader CreateOpenXmlReader(Stream fileStream, ExcelReaderConfiguration configuration = null)
        {
            if (configuration == null)
            {
                configuration = new ExcelReaderConfiguration();
            }

            if (configuration.LeaveOpen)
            {
                fileStream = new LeaveOpenStream(fileStream);
            }

            var probe = new byte[8];

            fileStream.Seek(0, SeekOrigin.Begin);
            fileStream.Read(probe, 0, probe.Length);
            fileStream.Seek(0, SeekOrigin.Begin);

            // Probe for password protected compound document or zip file
            if (CompoundDocument.IsCompoundDocument(probe))
            {
                var document = new CompoundDocument(fileStream);
                if (TryGetEncryptedPackage(fileStream, document, configuration.Password, out var stream))
                {
                    return(new ExcelOpenXmlReader(stream));
                }
                else
                {
                    throw new ExcelReaderException(Errors.ErrorCompoundNoOpenXml);
                }
            }
            else if (probe[0] == 0x50 && probe[1] == 0x4B)
            {
                // Zip files start with 'PK'
                return(new ExcelOpenXmlReader(fileStream));
            }
            else
            {
                throw new HeaderException(Errors.ErrorHeaderSignature);
            }
        }
Ejemplo n.º 22
0
        public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
        {
            CompoundDocument value = this.configuration.JsonApiTransformer.Transform(context.Object, context.HttpContext.ToContext(this.configuration));

            this.configuration.BeforeSerialization(new PreSerializationContext()
            {
                CompoundDocument = value,
                Type             = context.ObjectType,
                Value            = context.Object
            });

            using (StreamWriter streamWriter = new StreamWriter(context.HttpContext.Response.Body, selectedEncoding, 1024, true))
            {
                using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                {
                    this.configuration.Serializer.Serialize(jsonWriter, value);
                }
            }

            return(Task.CompletedTask);
        }
Ejemplo n.º 23
0
        public static CompoundDocument HandleException(Exception exception)
        {
            var scfException = exception is NJsonApiBaseException
                ? exception as NJsonApiBaseException
                : new NJsonApiBaseException(exception.Message, exception);

            var compoundDocument = new CompoundDocument
            {
                Errors = new Dictionary <string, Error>
                {
                    { "error", new Error
                      {
                          Id     = scfException.Id.ToString(),
                          Title  = scfException.Message,
                          Status = ((int)scfException.GetHttpStatusCode()).ToString(CultureInfo.InvariantCulture),
                      } }
                }
            };

            return(compoundDocument);
        }
Ejemplo n.º 24
0
        public void Creates_CompoundDocument_for_single_class_with_link_objects_and_properly_map_links()
        {
            // Arrange
            var context = CreateContext();
            SampleClassWithObjectLinks objectToTransform = CreateObjectWithLinkObjectsToTransform();
            var transformer = new JsonApiTransformerBuilder()
                              .With(CreateConfiguration())
                              .Build();

            // Act
            CompoundDocument result = transformer.Transform(objectToTransform, context);

            // Assert
            var transformedObject = result.Data as SingleResource;

            Assert.Equal("url1", ((ILinkObject)transformedObject.Links["link1"]).Link.Href);
            Assert.Equal("url2", ((ILinkObject)transformedObject.Links["link2"]).Link.Href);

            Assert.Equal("data1", ((ILinkObject)transformedObject.Links["link1"]).Meta["meta1"]);
            Assert.Equal("data2", ((ILinkObject)transformedObject.Links["link2"]).Meta["meta2"]);
        }
Ejemplo n.º 25
0
        public void Creates_CompoundDocument_for_single_not_nested_class_and_properly_suppress_nullable_properties()
        {
            // Arrange
            var context = CreateContext();
            SampleClassWithNullableProperty objectToTransform = CreateObjectWithNullPropertyToTransform();
            var config = CreateConfiguration();

            config.GetJsonSerializerSettings().NullValueHandling = NullValueHandling.Ignore;
            var transformer = new JsonApiTransformerBuilder()
                              .With(config)
                              .Build();

            // Act
            CompoundDocument result = transformer.Transform(objectToTransform, context);

            // Assert
            var transformedObject = result.Data as SingleResource;

            Assert.Equal(transformedObject.Attributes["someValue"], objectToTransform.SomeValue);
            Assert.False(transformedObject.Attributes.ContainsKey("date"));
            Assert.Equal(transformedObject.Attributes.Count, 1);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Creates an instance of <see cref="ExcelBinaryReader"/>
        /// </summary>
        /// <param name="fileStream">The file stream.</param>
        /// <param name="configuration">The configuration object.</param>
        /// <returns>The excel data reader.</returns>
        public static IExcelDataReader CreateBinaryReader(Stream fileStream, ExcelReaderConfiguration configuration = null)
        {
            if (configuration == null)
            {
                configuration = new ExcelReaderConfiguration();
            }

            if (configuration.LeaveOpen)
            {
                fileStream = new LeaveOpenStream(fileStream);
            }

            var probe = new byte[8];

            fileStream.Seek(0, SeekOrigin.Begin);
            fileStream.Read(probe, 0, probe.Length);
            fileStream.Seek(0, SeekOrigin.Begin);

            if (CompoundDocument.IsCompoundDocument(probe))
            {
                var document = new CompoundDocument(fileStream);
                if (TryGetWorkbook(fileStream, document, out var stream))
                {
                    return(new ExcelBinaryReader(stream, configuration.Password, configuration.FallbackEncoding));
                }
                else
                {
                    throw new ExcelReaderException(Errors.ErrorStreamWorkbookNotFound);
                }
            }
            else if (XlsWorkbook.IsRawBiffStream(probe))
            {
                return(new ExcelBinaryReader(fileStream, configuration.Password, configuration.FallbackEncoding));
            }
            else
            {
                throw new HeaderException(Errors.ErrorHeaderSignature);
            }
        }
Ejemplo n.º 27
0
        public CompoundDocument Transform(object objectGraph, Context context)
        {
            Type innerObjectType = TransformationHelper.GetObjectType(objectGraph);

            if (objectGraph is HttpError)
            {
                return(TransformationHelper.HandleHttpError(objectGraph as HttpError));
            }

            if (objectGraph is Exception)
            {
                return(TransformationHelper.HandleException(objectGraph as Exception));
            }

            TransformationHelper.VerifyTypeSupport(innerObjectType);
            TransformationHelper.AssureAllMappingsRegistered(innerObjectType, context.Configuration);

            var result = new CompoundDocument
            {
                Meta = TransformationHelper.GetMetadata(objectGraph)
            };

            var resource        = TransformationHelper.UnwrapResourceObject(objectGraph);
            var resourceMapping = context.Configuration.GetMapping(innerObjectType);

            var resourceList       = TransformationHelper.UnifyObjectsToList(resource);
            var representationList = resourceList.Select(o => TransformationHelper.CreateResourceRepresentation(o, resourceMapping, context));
            var primaryResource    = TransformationHelper.ChooseProperResourceRepresentation(resource, representationList);

            result.Data = primaryResource;

            if (resourceMapping.Relationships.Any())
            {
                result.Included = TransformationHelper.CreateIncludedRepresentations(resourceList, resourceMapping, context);
            }

            return(result);
        }
Ejemplo n.º 28
0
        private MemoryStream EncryptPackageBinary(byte[] package, ExcelEncryption encryption)
        {
            byte[] encryptionKey;
            //Create the Encryption Info. This also returns the Encryptionkey
            var encryptionInfo = CreateEncryptionInfo(encryption.Password,
                                                      encryption.Algorithm == EncryptionAlgorithm.AES128 ?
                                                      AlgorithmID.AES128 :
                                                      encryption.Algorithm == EncryptionAlgorithm.AES192 ?
                                                      AlgorithmID.AES192 :
                                                      AlgorithmID.AES256, out encryptionKey);

            //ILockBytes lb;
            //var iret = CreateILockBytesOnHGlobal(IntPtr.Zero, true, out lb);

            //IStorage storage = null;
            //MemoryStream ret = null;

            var doc = new CompoundDocument();

            CreateDataSpaces(doc);

            doc.Storage.DataStreams.Add("EncryptionInfo", encryptionInfo.WriteBinary());

            //Encrypt the package
            byte[]       encryptedPackage = EncryptData(encryptionKey, package, false);
            MemoryStream ms = new MemoryStream();

            ms.Write(BitConverter.GetBytes((ulong)package.LongLength), 0, 8);
            ms.Write(encryptedPackage, 0, encryptedPackage.Length);
            doc.Storage.DataStreams.Add("EncryptedPackage", ms.ToArray());

            var ret    = new MemoryStream();
            var buffer = doc.Save();

            ret.Write(buffer, 0, buffer.Length);

            return(ret);
        }
Ejemplo n.º 29
0
        public void Creates_CompondDocument_for_metadatawrapper_single_not_nested_class_and_propertly_map_metadata()
        {
            // Arrange
            const string pagingValue = "1";
            const string countValue  = "2";

            var context = CreateContext();
            MetaDataWrapper <SampleClass> objectToTransform = CreateObjectToTransform();

            objectToTransform.MetaData.Add("Paging", pagingValue);
            objectToTransform.MetaData.Add("Count", countValue);
            var sut = new JsonApiTransformer();


            // Act
            CompoundDocument result = sut.Transform(objectToTransform, context);

            // Assert
            var transformedObjectMetadata = result.Meta;

            Assert.Equal(transformedObjectMetadata["Paging"], pagingValue);
            Assert.Equal(transformedObjectMetadata["Count"], countValue);
        }
Ejemplo n.º 30
0
        public void Creates_CompondDocument_for_collection_not_nested_class_and_propertly_map_properties()
        {
            // Arrange
            var configuration = CreateContext();
            IEnumerable <SampleClass> objectsToTransform = CreateObjectToTransform();
            var sut = new JsonApiTransformer();

            // Act
            CompoundDocument result = sut.Transform(objectsToTransform, configuration);

            // Assert
            var transformedObject = result.Data as ResourceCollection;

            Action <SingleResource, SampleClass> assertSame = (actual, expected) =>
            {
                Assert.Equal(actual.Attributes["someValue"], expected.SomeValue);
                Assert.Equal(actual.Attributes["date"], expected.DateTime);
                Assert.Equal(actual.Attributes.Count(), 2);
            };

            assertSame(transformedObject[0], objectsToTransform.First());
            assertSame(transformedObject[1], objectsToTransform.Last());
        }
Ejemplo n.º 31
0
        private void GetProject()
        {

            var stream = Part.GetStream();
            byte[] vba;
            vba = new byte[stream.Length];
            stream.Read(vba, 0, (int)stream.Length);

            Document = new CompoundDocument(vba);
            ReadDirStream();
            ProjectStreamText = Encoding.GetEncoding(CodePage).GetString(Document.Storage.DataStreams["PROJECT"]);
            ReadModules();
            ReadProjectProperties();
        }
Ejemplo n.º 32
0
        internal void Save()
        {
            if (Validate())
            {
                CompoundDocument doc = new CompoundDocument();
                doc.Storage = new CompoundDocument.StoragePart();
                var store = new CompoundDocument.StoragePart();
                doc.Storage.SubStorage.Add("VBA", store);

                store.DataStreams.Add("_VBA_PROJECT", CreateVBAProjectStream());
                store.DataStreams.Add("dir", CreateDirStream());
                foreach (var module in Modules)
                {
                    store.DataStreams.Add(module.Name, CompoundDocument.CompressPart(Encoding.GetEncoding(CodePage).GetBytes(module.Attributes.GetAttributeText() + module.Code)));
                }

                //Copy streams from the template, if used.
                if (Document != null)
                {
                    foreach (var ss in Document.Storage.SubStorage)
                    {
                        if (ss.Key != "VBA")
                        {
                            doc.Storage.SubStorage.Add(ss.Key, ss.Value);
                        }
                    }
                    foreach (var s in Document.Storage.DataStreams)
                    {
                        if (s.Key != "dir" && s.Key != "PROJECT" && s.Key != "PROJECTwm")
                        {
                            doc.Storage.DataStreams.Add(s.Key, s.Value);
                        }
                    }
                }

                doc.Storage.DataStreams.Add("PROJECT", CreateProjectStream());
                doc.Storage.DataStreams.Add("PROJECTwm", CreateProjectwmStream());

                if (Part == null)
                {
                    Uri = new Uri(PartUri, UriKind.Relative);
                    Part = _pck.CreatePart(Uri, ExcelPackage.schemaVBA);
                    var rel = _wb.Part.CreateRelationship(Uri, TargetMode.Internal, schemaRelVba);
                }
                var vbaBuffer=doc.Save();
                var st = Part.GetStream(FileMode.Create);
                st.Write(vbaBuffer, 0, vbaBuffer.Length);
                st.Flush();
                st.Close();
                //Save the digital signture
                Signature.Save(this);
            }
        }