Ejemplo n.º 1
0
        public void WriteAndReadSafeData()
        {
            var cut = new XmlFormatter <SafeData>();

            const string Secret = "S*ecret";

            var data = new SafeData
            {
                Password = Secret
            };

            var stream = new MemoryStream();

            cut.Serialize(data, stream);

            stream.Position = 0;

            var read = cut.Deserialize(stream);

            stream.Position = 0;
            using (var reader = new StreamReader(stream))
            {
                var text = reader.ReadToEnd();
                Assert.IsTrue(!text.Contains(Secret), "serialization contains secret");
            }

            Assert.AreEqual(data.Password, read.Password);
        }
Ejemplo n.º 2
0
        protected virtual void CreatePackage(Stream stream)
        {
            using (Package package = ZipPackage.Open(stream, FileMode.Create))
            {
                Uri         collectionUri = new Uri("/Content/Collection.xml", UriKind.Relative);
                PackagePart part          = package.CreatePart(collectionUri, System.Net.Mime.MediaTypeNames.Text.Xml, CompressionOption.Maximum);

                //Serialize the model into the part stream
                XmlFormatter formatter = Formatter;
                formatter.Shallow = false;

                formatter.Serialize(part.GetStream(), Model);

                package.CreateRelationship(part.Uri, TargetMode.Internal, "Main Document");

                //Loop through all resources and create parts
                foreach (string key in Formatter.Resources.Keys)
                {
                    Uri           resourceUri = new Uri(key, UriKind.Relative);
                    ResourceEntry entry       = Formatter.Resources[key];

                    //Need to use a valid mime type otherwise a null reference error occurs
                    PackagePart resourcePart = package.CreatePart(resourceUri, entry.GetMimeType(), CompressionOption.Maximum);
                    entry.SaveResourceStream(resourcePart.GetStream());
                    PackageRelationship relationship = package.CreateRelationship(resourcePart.Uri, TargetMode.Internal, "Resource");
                }

                //Close the package and save all the underlying streams
                package.Close();
            }
        }
Ejemplo n.º 3
0
        public void SerializationShallowLineTest()
        {
            Link object1 = new Link();

            //Serialize the object
            MemoryStream stream     = new MemoryStream();
            XmlFormatter serializer = new XmlFormatter();

            serializer.Shallow = true;
            serializer.Serialize(stream, object1);
            stream.Position = 0; // reset the stream to the beginning
            SqlXml xml = new SqlXml(stream);

            //Recreate the object in object 2 using object 1 as the target
            Link object2;

            serializer.Target = object1;

            using (MemoryStream stream2 = new MemoryStream(Encoding.UTF8.GetBytes(xml.Value)))
            {
                object2 = (Link)serializer.Deserialize(stream2);
            }

            Assert.IsTrue(object1 == object2);
        }
Ejemplo n.º 4
0
        public void SerializationExternalAssemblyTest()
        {
            SubElement object1 = new SubElement();

            SurrogateSelector selector = new SurrogateSelector();

            selector.AddSurrogate(typeof(SubElement), new StreamingContext(StreamingContextStates.All), new ElementSerialize());

            //Serialize the object
            MemoryStream stream     = new MemoryStream();
            XmlFormatter serializer = new XmlFormatter();

            serializer.SurrogateSelector = selector;
            serializer.Serialize(stream, object1);
            stream.Position = 0; // reset the stream to the beginning
            SqlXml xml = new SqlXml(stream);

            //Recreate the object in object 2
            Element object2;

            using (MemoryStream stream2 = new MemoryStream(Encoding.UTF8.GetBytes(xml.Value)))
            {
                object2 = (Element)serializer.Deserialize(stream2);
            }
        }
Ejemplo n.º 5
0
        public void SerializationElementListTest()
        {
            ElementList object1 = new ElementList(true);
            Shape       shape1  = new Shape();
            Shape       shape2  = new Shape();

            shape1.Location = new PointF(10, 10);
            shape2.Location = new PointF(20, 20);

            object1.Add(shape1);
            object1.Add(shape2);

            //Serialize the object
            MemoryStream stream     = new MemoryStream();
            XmlFormatter serializer = new XmlFormatter();

            serializer.Serialize(stream, object1);
            stream.Position = 0; // reset the stream to the beginning
            SqlXml xml = new SqlXml(stream);

            //Recreate the object in object 2
            ElementList object2;

            using (MemoryStream stream2 = new MemoryStream(Encoding.UTF8.GetBytes(xml.Value)))
            {
                object2 = (ElementList)serializer.Deserialize(stream2);
            }

            Shape shape3 = object2[0] as Shape;
            Shape shape4 = object2[1] as Shape;

            Assert.IsTrue(object2.Count == 2, "ElementList collection does not contain 2 items.");
            Assert.IsTrue(shape3.Location == new PointF(10, 10), "Collection item 'shape1' location not deserialized correctly.");
            Assert.IsTrue(shape4.Location == new PointF(20, 20), "Collection item 'shape2' location not deserialized correctly.");
        }
Ejemplo n.º 6
0
        public void SerializationShapesTest()
        {
            Shapes object1 = new Shapes(new Model());
            Shape  shape1  = new Shape();
            Shape  shape2  = new Shape();

            shape1.Location = new PointF(10, 10);
            shape2.Location = new PointF(20, 20);

            object1.Add("shape1", shape1);
            object1.Add("shape2", shape2);

            //Serialize the object
            MemoryStream stream     = new MemoryStream();
            XmlFormatter serializer = new XmlFormatter();

            serializer.Serialize(stream, object1);
            stream.Position = 0; // reset the stream to the beginning
            SqlXml xml = new SqlXml(stream);

            //Recreate the object in object 2
            Shapes object2;

            using (MemoryStream stream2 = new MemoryStream(Encoding.UTF8.GetBytes(xml.Value)))
            {
                object2 = (Shapes)serializer.Deserialize(stream2);
            }

            Assert.IsTrue(object2.Count == 2, "Shapes collection does not contain 2 items.");
            Assert.IsTrue(object2.ContainsKey("shape1"), "Shapes collection does not contain key 'shape1'.");
            Assert.IsTrue(object2.ContainsKey("shape2"), "Shapes collection does not contain key 'shape2'.");
            Assert.IsTrue(object2["shape1"].Location == new PointF(10, 10), "Collection item 'shape1' location not deserialized correctly.");
            Assert.IsTrue(object2["shape2"].Location == new PointF(20, 20), "Collection item 'shape2' location not deserialized correctly.");
            Assert.IsTrue(object2.Model != null, "Shapes Model not deserialized correctly.");
        }
Ejemplo n.º 7
0
        public void SerializationBlankTest()
        {
            //Serialize an element with a blank serializer
            Element object1 = new Element();

            //Serialize the object
            MemoryStream stream     = new MemoryStream();
            XmlFormatter serializer = new XmlFormatter();

            SurrogateSelector selector = new SurrogateSelector();
            StreamingContext  context  = new StreamingContext(StreamingContextStates.All); //Need to ensure a context is supplied

            selector.AddSurrogate(typeof(Element), context, new BlankSerialize());
            serializer.SurrogateSelector = selector;

            serializer.Serialize(stream, object1);
            stream.Position = 0; // reset the stream to the beginning
            SqlXml xml = new SqlXml(stream);

            //Recreate the object in object 2
            Element object2;

            using (MemoryStream stream2 = new MemoryStream(Encoding.UTF8.GetBytes(xml.Value)))
            {
                object2 = (Element)serializer.Deserialize(stream2);
            }
        }
Ejemplo n.º 8
0
        public void WriteAndReadBadSubData()
        {
            var cut  = new XmlFormatter <SomeData>();
            var data = new SomeData
            {
                Name            = null,
                Number          = 0.42M + GetHashCode(),
                DataAfterObject = $"Some text after object at {GetHashCode()}",
                SubData         = new BadSubData($"Info at {GetHashCode()}"),
                Names           = new[] { "Name1", "Name2" },
            };

            cut.Serialize(data, Filename);
            var read = cut.Deserialize(Filename);

            Assert.AreEqual(data.Name, read.Name);
            Assert.AreEqual(data.Number, read.Number);
            Assert.AreEqual(data.YesNo, read.YesNo);
            Assert.AreEqual(data.Value, read.Value);
            Assert.AreNotEqual(data.SubData.Info, read.SubData.Info);
            Assert.AreEqual(data.DataAfterObject, read.DataAfterObject);
            Assert.AreNotEqual(data.NotGood, read.NotGood);
            Assert.AreEqual(data.Names.Length, read.Names.Length);
            for (var i = 0; i < data.Names.Length; i++)
            {
                Assert.AreEqual(data.Names[i], read.Names[i], $"Names[{i}] differ");
            }
        }
        static void Main(string[] args)
        {
            var person        = new Person("Nadia", "Comanici");
            var student       = new Student(123, "Simona", "Lungu");
            var jsonFormatter = new JsonFormatter();
            var xmlFormatter  = new XmlFormatter();

            // person json formatting
            Console.WriteLine("-------- Person as JSON ---------------");
            var formattedPerson = new FormattedPerson(person, jsonFormatter);

            Console.WriteLine(formattedPerson.GetObjectAsString());
            Console.WriteLine();

            // person xml formatting
            Console.WriteLine("-------- Person as XML ---------------");
            formattedPerson.Formatter = xmlFormatter;
            Console.WriteLine(formattedPerson.GetObjectAsString());
            Console.WriteLine();

            // student json formatting
            Console.WriteLine("-------- Student as JSON ---------------");
            var formattedStudent = new FormattedStudent(student, jsonFormatter);

            Console.WriteLine(formattedStudent.GetObjectAsString());
            Console.WriteLine();

            // student xml formatting
            Console.WriteLine("-------- Student as XML ---------------");
            formattedStudent.Formatter = xmlFormatter;
            Console.WriteLine(formattedStudent.GetObjectAsString());
            Console.WriteLine();
        }
Ejemplo n.º 10
0
        public void GetXmlFormatter_ContextSupplied_ContextIsUsed()
        {
            object       context   = Random.Next();
            XmlFormatter formatter = Serialize.GetXmlFormatter(context);

            Assert.AreEqual(new StreamingContext(StreamingContextStates.Other, context), formatter.Context);
        }
Ejemplo n.º 11
0
        public static void SaveFormatted(AddinDescription adesc)
        {
            XmlDocument  doc       = adesc.SaveToXml();
            XmlFormatter formatter = new XmlFormatter();

            TextStylePolicy     textPolicy = new TextStylePolicy(80, 4, false, false, true, EolMarker.Unix);
            XmlFormattingPolicy xmlPolicy  = new XmlFormattingPolicy();

            XmlFormatingSettings f = new XmlFormatingSettings();

            f.ScopeXPath.Add("*/*");
            f.EmptyLinesBeforeStart = 1;
            f.EmptyLinesAfterEnd    = 1;
            xmlPolicy.Formats.Add(f);

            f = new XmlFormatingSettings();
            f.ScopeXPath.Add("Addin");
            f.AttributesInNewLine = true;
            f.AlignAttributes     = true;
            f.AttributesInNewLine = false;
            xmlPolicy.Formats.Add(f);

            string xml = formatter.FormatXml(textPolicy, xmlPolicy, doc.OuterXml);

            File.WriteAllText(adesc.FileName, xml);
        }
Ejemplo n.º 12
0
        private IRecipe SaveRecipeCore(string filename, IRecipe recipe)
        {
            if (filename == null)
            {
                throw new ArgumentNullException("fileName");
            }
            if (string.IsNullOrEmpty(filename))
            {
                throw new ArgumentException("FileName cannot be null");
            }
            if (recipe == null)
            {
                throw new ArgumentNullException("recipe");
            }
            var formatter = new XmlFormatter();

            Meal.Svc.Persistance.Recipe r = recipe as Meal.Svc.Persistance.Recipe ?? Meal.Svc.Persistance.Recipe.FromRecipe(recipe);

            using (var stream = System.IO.File.Create(filename))
            {
                formatter.Serialize(stream, r);
                stream.Close();
            }
            return(recipe);
        }
        public void Test1()
        {
            var o = new Test
            {
                String   = "MyTest",
                Integer  = 5,
                Float    = 4.5f,
                Children = new List <Test>
                {
                    new Test {
                        String = "Child1"
                    },
                    new Test {
                        String = "Child2"
                    }
                }
            };
            var formatter = new XmlFormatter();
            var m         = new MemoryStream();

            formatter.Serialize(m, o);
            m.Position = 0;
            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
            var d = (Test)formatter.Deserialize(m);

            Assert.IsTrue(DeepComparer.Compare(o, d));
        }
Ejemplo n.º 14
0
        private bool ProcessEx(Assembly assembly, XmlFormatter xmlFormatter)
        {
            if (Action == Action.Check)
            {
                Type[] types       = DbAttributesManager.LoadDbRecordTypes(assembly);
                int    errorNumber = 1;
                for (int i = 0; i < types.Length; i++)
                {
                    Type type    = types[i];
                    bool isValid = StructureGateway.IsValid(type);
                    if (isValid)
                    {
                        xmlFormatter.AppendUnitTestResult("Mapping Test - " + type.FullName, Outcome.Passed, "");
                        string message = string.Format(
                            "{0} ({1}) - Ok"
                            , type, assembly.ManifestModule.Name);
                        Console.WriteLine(message);
                    }
                    else
                    {
                        string message = string.Format(
                            "\r\n{3}. {0} ({1}) \r\n{4}\r\n{2}\r\n{4}"
                            , type, assembly.ManifestModule.Name, StructureGateway.LastError, errorNumber++,
                            "----------------------------------------------------------------------------"
                            );
                        Console.WriteLine(message);

                        ExitCode = ExitCode.Failure;
                        xmlFormatter.AppendUnitTestResult("Mapping Test - " + type.FullName, Outcome.Failed, StructureGateway.LastError);
                    }
                }
                return(true);
            }
            return(false);
        }
Ejemplo n.º 15
0
        public void SetUp()
        {
            streamingData = new InMemoryStreamingData();
            writer        = new InMemoryOutputWriter();

            theFormatter = new XmlFormatter(streamingData, writer);
        }
Ejemplo n.º 16
0
        public void MultiArrayTest()
        {
            var cut = new XmlFormatter <ArrayData>();

            var data = new ArrayData
            {
                Numbers = new int[3, 2]
                {
                    { 1, 2 }, { 3, 4 }, { 5, 6 }
                }
            };

            cut.Serialize(data, Filename);
            var read = cut.Deserialize(Filename);

            var dataN = data.Numbers;
            var readN = read.Numbers;

            Assert.AreEqual(dataN.Length, readN.Length);
            Assert.AreEqual(dataN.Rank, readN.Rank);
            Assert.AreEqual(dataN.GetUpperBound(0), readN.GetUpperBound(0));
            Assert.AreEqual(dataN.GetUpperBound(1), readN.GetUpperBound(1));

            for (var i = 0; i < dataN.GetUpperBound(0); i++)
            {
                for (int j = 0; j < dataN.GetUpperBound(1); j++)
                {
                    Assert.AreEqual(dataN[i, j], readN[i, j], $"Array[{i},{j}]");
                }
            }
        }
Ejemplo n.º 17
0
        public void SetUp()
        {
            streamingData = new InMemoryStreamingData();
            writer = new InMemoryOutputWriter();

            theFormatter = new XmlFormatter(streamingData, writer);
        }
Ejemplo n.º 18
0
        public void IndentXmlTest3()
        {
            XmlFormatter formatter = new XmlFormatter();
            string       expected  = string.Empty;
            string       actual    = formatter.IndentXml(string.Empty);

            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 19
0
        private static void PrintInfo()
        {
            var xmlFormatter     = new XmlFormatter(null);
            var consoleFormatter = new ConsoleFormatter();

            consoleFormatter.Format(tracer.GetTraceResult());
            xmlFormatter.Format(tracer.GetTraceResult());
        }
Ejemplo n.º 20
0
        static void Main()
        {
            var printer = new Printer();
            IFormatter formatter = new XmlFormatter();
            //formatter = new JsonFormatter();

            printer.Print("gosho", formatter);
        }
Ejemplo n.º 21
0
        public void IndentXmlTest1()
        {
            XmlFormatter formatter = new XmlFormatter();
            string       expected  = _IndentedXml;
            string       actual    = formatter.IndentXml(_RawXml);

            Assert.AreEqual(expected, actual);
        }
        public void SetProjectChoiceWindowPeriod(int courseId, int semesterId, string startDate, string endDate)
        {
            XDocument xDocument = XmlReader.ReadXmlDocument(Constants.PersistentDataXmlVirtualFilePath);

            XmlFormatter.UpdateNodeValue(ref xDocument, "/PersistentData/Course[CourseId=" + courseId + "]/ProjectChoiceWindowPeriod/Semester" + semesterId + "/StartDate", startDate.Replace("/", "-") + ":00");
            XmlFormatter.UpdateNodeValue(ref xDocument, "/PersistentData/Course[CourseId=" + courseId + "]/ProjectChoiceWindowPeriod/Semester" + semesterId + "/EndDate", endDate.Replace("/", "-") + ":00");
            XmlFormatter.FinalizeXmlWriting(ref xDocument, Constants.PersistentDataXmlVirtualFilePath);
        }
Ejemplo n.º 23
0
        internal ProfileContainer Clone()
        {
            var formatter = new XmlFormatter <ProfileContainer>();
            var stream    = new MemoryStream();

            formatter.Serialize(this, stream);
            stream.Position = 0;
            return(formatter.Deserialize(stream));
        }
Ejemplo n.º 24
0
        public void XmlFormatterShouldThrowOnMissingFileName()
        {
            formatterElement fileConfiguration = new formatterElement();

            fileConfiguration.output.fileName = null;
            XmlFormatter formatter = new XmlFormatter(fileConfiguration);

            formatter.WriteReport(null, LogLevel.Information);
        }
Ejemplo n.º 25
0
        public void XmlFormatter_WhenCustomerHaveMultipleRentals_ShouldPass()
        {
            var      customer       = CustomerFactory.GetCustomer();
            var      xmlFormatter   = new XmlFormatter();
            var      serializedData = customer.GetStatement(xmlFormatter);
            Customer actual         = xmlFormatter.Deserialize(serializedData);

            Assert.True(customer.Equals(actual));
        }
Ejemplo n.º 26
0
        static void Main()
        {
            var        printer   = new Printer();
            IFormatter formatter = new XmlFormatter();

            //formatter = new JsonFormatter();

            printer.Print("gosho", formatter);
        }
Ejemplo n.º 27
0
        public static string SaveFormattedXml(PolicyContainer policies, AddinDescription adesc)
        {
            XmlDocument doc = adesc.SaveToXml();

            TextStylePolicy     textPolicy = policies.Get <TextStylePolicy> (DesktopService.GetMimeTypeInheritanceChain("application/x-addin+xml"));
            XmlFormattingPolicy xmlPolicy  = policies.Get <XmlFormattingPolicy> (DesktopService.GetMimeTypeInheritanceChain("application/x-addin+xml"));

            return(XmlFormatter.FormatXml(textPolicy, xmlPolicy, doc.OuterXml));
        }
Ejemplo n.º 28
0
        private void btnGenerate_Click(object sender, EventArgs e)
        {
            int          keySize  = Convert.ToInt32(txtKeySize.Text);
            string       savePath = txtSavePath.Text.Trim();
            XmlFormatter xmlFmt   = new XmlFormatter(keySize, savePath);

            xmlFmt.GenerateKey();
            MessageBox.Show("Key Generated");
        }
Ejemplo n.º 29
0
        private static ExitCode Run(string[] args)
        {
            var parameters = new InputParameters();

            if (!parameters.Init(args))
            {
                printUsage();
                return(ExitCode.Exception);
            }

            var processor = new Processor();

            try
            {
                parameters.Apply(processor);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                printUsage();
                return(ExitCode.Exception);
            }

            try
            {
                switch (processor.Action)
                {
                case Action.Generate:
                    processor.GenerateClasses(args);
                    break;

                case Action.ImportExcel:
                    processor.ImportFromExcel(args);
                    break;

                default:
                    string outputFormatter = ConfigurationManager.AppSettings["OutputFormatter"];
                    using (XmlFormatter xmlFormatter = FormattersFactory.GetFormatter(outputFormatter))
                    {
                        processor.Run(parameters.Assemblies, xmlFormatter);
                    }
                    break;
                }

                if (processor.ExitCode != ExitCode.Success)
                {
                    printUsage();
                }

                return(processor.ExitCode);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Internal exception occured: " + ex.Message);
                return(ExitCode.Exception);
            }
        }
Ejemplo n.º 30
0
        public void HighlightShortStringUsingMockStringWriterWithRandomExceptions()
        {
            XmlFormatter x = new XmlFormatter();
            Highlighter h = new Highlighter("cs", x);

            for (int i = 0; i < 10; i++) {
                h.Highlight("public void Foo() { int i = 5; }", new MockStringWriter(2));
            }
        }
Ejemplo n.º 31
0
        public void WriteAndRead()
        {
            var cut  = new XmlFormatter <SomeData>();
            var data = new SomeData
            {
                Name            = null,
                Number          = 0.42M + GetHashCode(),
                Time            = DateTime.Now,
                Span            = TimeSpan.FromMilliseconds(457575578),
                DataAfterObject = $"Some text after object at {GetHashCode()}",
                SubData         = new SubData
                {
                    Info = $"Info at {GetHashCode()}"
                },
                Names    = new[] { "Name1", "Name2" },
                Products = { "product1", "product2", "product3" },
                SubDatas =
                {
                    { "Test1", new SubData {
                          Info = $"Test1 dictionary at {GetHashCode()}"
                      } },
                    { "Test2", new SubData {
                          Info = $"Test2 dictionary at {GetHashCode()}"
                      } }
                },
                Location = new Point(5, 6)
            };

            cut.Serialize(data, Filename);
            var read = cut.Deserialize(Filename);

            Assert.AreEqual(data.Name, read.Name);
            Assert.AreEqual(data.Number, read.Number);
            Assert.AreEqual(data.Time, read.Time);
            Assert.AreEqual(data.Span, read.Span);
            Assert.AreEqual(data.YesNo, read.YesNo);
            Assert.AreEqual(data.Value, read.Value);
            Assert.AreEqual(data.Location, read.Location);
            Assert.AreEqual(data.SubData.Info, read.SubData.Info);
            Assert.AreEqual(data.DataAfterObject, read.DataAfterObject);
            Assert.AreNotEqual(data.NotGood, read.NotGood);
            Assert.AreEqual(data.Names.Length, read.Names.Length);
            for (var i = 0; i < data.Names.Length; i++)
            {
                Assert.AreEqual(data.Names[i], read.Names[i], $"Names[{i}] differ");
            }
            Assert.AreEqual(data.Products.Count, read.Products.Count);
            for (var i = 0; i < data.Products.Count; i++)
            {
                Assert.AreEqual(data.Products[i], read.Products[i], $"Products[{i}] differ");
            }
            Assert.AreEqual(data.SubDatas.Count, read.SubDatas.Count);
            foreach (var key in data.SubDatas.Keys)
            {
                Assert.AreEqual(data.SubDatas[key].Info, read.SubDatas[key].Info);
            }
        }
Ejemplo n.º 32
0
 private void SaveProcessDescription()
 {
     foreach (var part in ProcessDescParts)
     {
         var xmlDoc = XDocument.Load(part.GetStream());
         IWfProcessDescriptor wfProcessDesc = (IWfProcessDescriptor)XmlFormatter.Deserialize(xmlDoc.Root);
         WfProcessDescHelper.SaveWfProcess(wfProcessDesc);
     }
 }
Ejemplo n.º 33
0
        static void Main(string[] args)
        {
            var formatter = new XmlFormatter();
            var appender = new ConsoleAppender(formatter);
            var logger = new Logger(appender);

            logger.Info("This is app");
            logger.Error("Cannot be empty!");
            logger.Critical("You are illigle");
        }
Ejemplo n.º 34
0
        public void OmitXmlDeclarationIsFalse_XmlDeclarationExists_XmlDeclarationUnmodified()
        {
            xmlPolicy.DefaultFormat.OmitXmlDeclaration = false;
            string input          = "<?xml version=\"1.0\"?><a></a>";
            string expectedResult = "<?xml version=\"1.0\"?>\n<a>\n</a>";

            string result = XmlFormatter.FormatXml(textPolicy, xmlPolicy, input);

            Assert.AreEqual(expectedResult, result);
        }
Ejemplo n.º 35
0
        public void HighlightLongStringUsingMockStringWriterWithRandomExceptions()
        {
            StringBuilder sb = new StringBuilder(3000*20);

            for (int i = 0; i < 3000; i++) {
                sb.Append("public void Foo() { int i = 5; }");
            }

            XmlFormatter x = new XmlFormatter();
            Highlighter h = new Highlighter("cs", x);
            string s = sb.ToString();
            h.Highlight(s, new MockStringWriter(2));
        }
 public IRecipe LoadRecipe(string filename)
 {
     var formatter = new XmlFormatter ();
      using (var stream = System.IO.File.OpenRead (filename))
      {
     object o = formatter.Deserialize (stream);
     if (o is Sellars.Meal.Svc.Persistance.Recipe)
     {
        ((Sellars.Meal.Svc.Persistance.Recipe)o).FileName = filename;
     }
     return (IRecipe)o;
      }
 }
Ejemplo n.º 37
0
        public void SetUp()
        {
            theRequest = OwinHttpRequest.ForTesting();
            writer = new InMemoryOutputWriter();

            var container = new Container(x => {
                x.For<IHttpRequest>().Use(theRequest);
                x.For<IOutputWriter>().Use(writer);
                x.For<IFubuRequest>().Use(new InMemoryFubuRequest());
            });

            context = new MockedFubuRequestContext(container);

            theFormatter = new XmlFormatter();
        }
 public void Test1()
 {
     var o = new Test
     {
         String = "MyTest",
         Integer = 5,
         Float = 4.5f,
         Children = new List<Test>
     {
         new Test { String = "Child1" },
         new Test { String = "Child2" }
     }
     };
     var formatter = new XmlFormatter();
     var m = new MemoryStream();
     formatter.Serialize(m, o);
     m.Position = 0;
     System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
     var d = (Test)formatter.Deserialize(m);
     Assert.IsTrue(DeepComparer.Compare(o, d));
 }
        private IRecipe SaveRecipeCore(string filename, IRecipe recipe)
        {
            if (filename == null)
            throw new ArgumentNullException ("fileName");
             if (string.IsNullOrEmpty (filename))
            throw new ArgumentException ("FileName cannot be null");
             if (recipe == null)
            throw new ArgumentNullException ("recipe");
             var formatter = new XmlFormatter ();

             Meal.Svc.Persistance.Recipe r = recipe as Meal.Svc.Persistance.Recipe ?? Meal.Svc.Persistance.Recipe.FromRecipe (recipe);

             using (var stream = System.IO.File.Create (filename))
             {
            formatter.Serialize (stream, r);
            stream.Close ();
             }
             return recipe;
        }
Ejemplo n.º 40
0
        public IRecipe LoadRecipe(string filename)
        {
            var formatter = new XmlFormatter ();
             using (var stream = System.IO.File.OpenRead (filename))
             {
            object o = formatter.Deserialize (stream);
            return o as IRecipe;
             }

             //using (var stream = System.IO.File.OpenRead (filename))
             //{
             //   object o = XamlReader.Load (stream);

             //   var r = o as Sellars.Meal.Svc.Persistance.Recipe;

             //   r.FileName = filename;

             //   return o as IRecipe;
             //}
        }
Ejemplo n.º 41
0
        public void HighlightUsingMockReaderFailingOn3rdRead()
        {
            StringBuilder sb = new StringBuilder(32768*4);

            while(sb.Length < 32768*4 - 300) {
                sb.AppendLine("public void Foo() { int i = 5; }");
            }

            XmlFormatter x = new XmlFormatter();
            Highlighter h = new Highlighter("cs", x);

            h.Highlight(new MockStringReaderWithExceptionOnNthRead(sb.ToString(), 3), new StringWriter());
        }
Ejemplo n.º 42
0
        public void HighlightUsingMockReaderFailingOnZerothRead()
        {
            XmlFormatter x = new XmlFormatter();
            Highlighter h = new Highlighter("cs", x);

            h.Highlight(new MockStringReaderWithExceptionOnNthRead("public void Foo() { int i = 5; }", 0), new StringWriter());
        }
Ejemplo n.º 43
0
        public IRecipe SaveRecipe(string filename, IRecipe recipe)
        {
            var formatter = new XmlFormatter ();

             Meal.Svc.Persistance.Recipe r = recipe as Meal.Svc.Persistance.Recipe ?? Meal.Svc.Persistance.Recipe.FromRecipe (recipe);

             using (var stream = System.IO.File.Create (filename))
             {
            //XamlWriter.Save (r, stream);

            formatter.Serialize (stream, r);
            stream.Close ();
             }
             return recipe;
        }
Ejemplo n.º 44
0
 public void SetUp()
 {
     streamingData = new InMemoryStreamingData();
     theFormatter = new XmlFormatter(streamingData);
 }
Ejemplo n.º 45
0
 internal Broadcaster(Dictionary<TcpClient, Handler.PlayerInfo> to, Handler handler)
 {
     this.to = to; this.handler = handler;
     xml = new XmlFormatter(this, handler);
 }
Ejemplo n.º 46
0
 internal void RefreshTypes()
 {
     bool bBin = false, bXml = false;
     foreach (Handler.PlayerInfo pi in to.Values)
     {
         bBin |= pi.binary == true;
         bXml |= pi.binary == false;
     }
     if (bBin && bin == null) bin = new BinFormatter(this, handler);
     else if (!bBin && bin != null) bin = null;
     if (bXml && xml == null) xml = new XmlFormatter(this, handler);
     else if (!bXml && xml != null) xml = null;
 }
Ejemplo n.º 47
0
        public void XMLFormatter_CanRead_ReturnsFalseForUnsupportedMediaTypes(string requestContentType)
        {
            // Arrange
            var formatter = new XmlFormatter();
            var httpContext = new DefaultHttpContext();
            httpContext.Request.ContentType = requestContentType;

            var provider = new EmptyModelMetadataProvider();
            var metadata = provider.GetMetadataForType(typeof(void));
            var context = new InputFormatterContext(
                httpContext,
                modelName: string.Empty,
                modelState: new ModelStateDictionary(),
                metadata: metadata);

            // Act
            var result = formatter.CanRead(context);

            // Assert
            Assert.False(result);
        }