Example #1
0
        public void Nillables()
        {
            lock (testLock)
            {
                // Get the code namespace for the schema.
                string inputFilePath = GetInputFilePath("nillables.xsd", Resources.nillables);

                var generatorParams = GetGeneratorParams(inputFilePath);
                GetGeneratorParams(inputFilePath);

                generatorParams.Miscellaneous.EnableSummaryComment = true;
                generatorParams.TargetFramework = TargetFramework.Net35;
                generatorParams.PropertyParams.AutomaticProperties = true;
                generatorParams.EnableInitializeFields             = true;
                generatorParams.CollectionObjectType = CollectionType.List;


                var xsdGen = new GeneratorFacade(generatorParams);
                var result = xsdGen.Generate();

                Assert.IsTrue(result.Success, result.Messages.ToString());
                var compileResult = CompileCSFile(generatorParams.OutputFilePath);
                Assert.IsTrue(compileResult.Success, compileResult.Messages.ToString());
            }
        }
Example #2
0
        public void AutomaticProperties()
        {
            lock (testLock)
            {
                // Get the code namespace for the schema.
                GetInputFilePath("Actor.xsd", Resources.Actor);
                string inputFilePath = GetInputFilePath("dvd.xsd", Resources.dvd);

                var generatorParams = new GeneratorParams {
                    InputFilePath = inputFilePath
                };
                GetGeneratorParams(inputFilePath);
                generatorParams.TargetFramework = TargetFramework.Net30;
                generatorParams.Miscellaneous.EnableSummaryComment = false;
                generatorParams.GenerateDataContracts = false;
                generatorParams.PropertyParams.AutomaticProperties  = true;
                generatorParams.Serialization.GenerateXmlAttributes = true;
                generatorParams.OutputFilePath = Path.ChangeExtension(generatorParams.InputFilePath, ".autoProp.cs");

                var xsdGen = new GeneratorFacade(generatorParams);
                var result = xsdGen.Generate();

                Assert.IsTrue(result.Success, result.Messages.ToString());

                var compileResult = CompileCSFile(generatorParams.OutputFilePath);
                Assert.IsTrue(compileResult.Success, compileResult.Messages.ToString());
            }
        }
Example #3
0
        public void TestAnnotations()
        {
            lock (testLock)
            {
                // Get the code namespace for the schema.
                string inputFilePath = GetInputFilePath("TestAnnotations.xsd", Resources.TestAnnotations);

                var generatorParams = new GeneratorParams {
                    InputFilePath = inputFilePath
                };
                GetGeneratorParams(inputFilePath);

                generatorParams.Miscellaneous.EnableSummaryComment = true;
                generatorParams.TargetFramework = TargetFramework.Net35;
                generatorParams.PropertyParams.AutomaticProperties = true;
                generatorParams.OutputFilePath = Path.ChangeExtension(generatorParams.InputFilePath,
                                                                      ".TestAnnotations.cs");

                var xsdGen = new GeneratorFacade(generatorParams);
                var result = xsdGen.Generate();

                Assert.IsTrue(result.Success, result.Messages.ToString());

                var compileResult = CompileCSFile(generatorParams.OutputFilePath);
                Assert.IsTrue(compileResult.Success, compileResult.Messages.ToString());
            }
        }
Example #4
0
        public void ArrayOfArray()
        {
            lock (testLock)
            {
                // Copy resource file to the run-time directory
                var inputFilePath = GetInputFilePath("ArrayOfArray.xsd", Resources.ArrayOfArray);

                var generatorParams = new GeneratorParams
                {
                    GenerateCloneMethod  = true,
                    InputFilePath        = inputFilePath,
                    NameSpace            = "MyNameSpace",
                    CollectionObjectType = CollectionType.Array,
                    EnableDataBinding    = true,
                    Language             = GenerationLanguage.CSharp,
                    OutputFilePath       = Path.ChangeExtension(inputFilePath, ".TestGenerated.cs")
                };
                generatorParams.PropertyParams.AutomaticProperties = true;
                generatorParams.Serialization.Enabled = true;
                var xsdGen = new GeneratorFacade(generatorParams);
                var result = xsdGen.Generate();

                Assert.IsTrue(result.Success, result.Messages.ToString());

                var compileResult = CompileCSFile(generatorParams.OutputFilePath);
                Assert.IsTrue(compileResult.Success, compileResult.Messages.ToString());
            }
        }
Example #5
0
        public void UseBaseClass()
        {
            lock (testLock)
            {
                // Get the code namespace for the schema.
                GetInputFilePath("Actor.xsd", Resources.Actor);
                string inputFilePath = GetInputFilePath("dvd.xsd", Resources.dvd);

                string outputFilePath  = Path.ChangeExtension(inputFilePath, ".baseClass.cs");
                var    generatorParams = new GeneratorParams
                {
                    InputFilePath         = inputFilePath,
                    TargetFramework       = TargetFramework.Net30,
                    GenerateDataContracts = true,
                    EnableDataBinding     = true,
                    OutputFilePath        = outputFilePath
                };

                generatorParams.PropertyParams.AutomaticProperties = false;
                generatorParams.Miscellaneous.EnableSummaryComment = true;
                generatorParams.GenericBaseClass.Enabled           = true;
                generatorParams.GenericBaseClass.GenerateBaseClass = true;
                //generatorParams.GenericBaseClass.BaseClassName = "EntityObject";

                var xsdGen = new GeneratorFacade(generatorParams);
                var result = xsdGen.Generate();

                Assert.IsTrue(result.Success, result.Messages.ToString());

                var compileResult = CompileCSFile(generatorParams.OutputFilePath);
                Assert.IsTrue(compileResult.Success, compileResult.Messages.ToString());
            }
        }
Example #6
0
        public void SeparateFiles()
        {
            lock (testLock)
            {
                // Get the code namespace for the schema.
                string tvShowInputFilePath = GetInputFilePath("TVShow.xsd", Resources.TVShow);
                // copy included/imported files to the test folder
                GetInputFilePath("Actor.xsd", Resources.Actor);
                GetInputFilePath("Gender.xsd", Resources.Gender);

                var tvShowGeneratorParams = GetGeneratorParams(tvShowInputFilePath);
                GetGeneratorParams(tvShowInputFilePath);

                tvShowGeneratorParams.Miscellaneous.EnableSummaryComment = true;
                tvShowGeneratorParams.TargetFramework = TargetFramework.Net35;
                tvShowGeneratorParams.PropertyParams.AutomaticProperties = true;
                tvShowGeneratorParams.EnableInitializeFields             = true;
                tvShowGeneratorParams.CollectionObjectType  = CollectionType.List;
                tvShowGeneratorParams.GenerateSeparateFiles = true;
                tvShowGeneratorParams.OutputFilePath        = Path.ChangeExtension(tvShowGeneratorParams.InputFilePath, ".separate.cs");

                var           tvShowXsdGen      = new GeneratorFacade(tvShowGeneratorParams);
                var           tvShowResult      = tvShowXsdGen.Generate();
                List <string> tvShowOutputFiles = tvShowResult.Entity;
                Assert.IsTrue(tvShowResult.Success, tvShowResult.Messages.ToString());
                // compile TV show
                var compileResult = CompileCSFile(tvShowOutputFiles.ToArray());
                Assert.IsTrue(compileResult.Success, compileResult.Messages.ToString());
            }
        }
Example #7
0
        public void GenarateVBCS()
        {
            lock (testLock)
            {
                // Get the code namespace for the schema.
                string inputFilePath = GetInputFilePath("Actor.xsd", Resources.Actor);

                var generatorParams = GetGeneratorParams(inputFilePath);
                generatorParams.TargetFramework = TargetFramework.Net30;
                generatorParams.PropertyParams.AutomaticProperties = true;
                generatorParams.GenerateDataContracts = true;
                generatorParams.Serialization.GenerateXmlAttributes = true;
                generatorParams.OutputFilePath    = GetOutputFilePath(inputFilePath);
                generatorParams.EnableDataBinding = true;
                generatorParams.Miscellaneous.EnableSummaryComment = true;
                generatorParams.Language = GenerationLanguage.VisualBasic;
                var xsdGen = new GeneratorFacade(generatorParams);
                var result = xsdGen.Generate();
                Assert.IsTrue(result.Success, result.Messages.ToString());

                generatorParams.Language = GenerationLanguage.CSharp;
                xsdGen = new GeneratorFacade(generatorParams);
                result = xsdGen.Generate();

                var canCompile = CompileCSFile(generatorParams.OutputFilePath);
                Assert.IsTrue(canCompile.Success, canCompile.Messages.ToString());
            }
        }
Example #8
0
        public void UseBaseClass()
        {
            lock (testLock)
            {
                // Get the code namespace for the schema.
                GetInputFilePath("Actor.xsd", Resources.Actor);
                string inputFilePath = GetInputFilePath("dvd.xsd", Resources.dvd);

                string outputFilePath  = Path.ChangeExtension(inputFilePath, ".baseClass.cs");
                var    generatorParams = new GeneratorParams
                {
                    InputFilePath         = inputFilePath,
                    TargetFramework       = TargetFramework.Net30,
                    GenerateDataContracts = true,
                    EnableDataBinding     = true,
                    OutputFilePath        = outputFilePath
                };

                generatorParams.PropertyParams.AutomaticProperties = false;
                generatorParams.Miscellaneous.EnableSummaryComment = true;
                generatorParams.GenericBaseClass.Enabled           = true;
                generatorParams.GenericBaseClass.GenerateBaseClass = true;
                generatorParams.GenericBaseClass.BaseClassName     = "EntityObject";

                var xsdGen = new GeneratorFacade(generatorParams);
                var result = xsdGen.Generate();

                Assert.IsTrue(result.Success, result.Messages.ToString());

                var compileResult = CompileCSFile(generatorParams.OutputFilePath);
                Assert.IsTrue(compileResult.Success, compileResult.Messages.ToString());

                // check if autogeneration-parameters are written to file
                var lastGenerationParamsFile = Path.ChangeExtension(inputFilePath, "xsd.xsd2code");
                if (File.Exists(lastGenerationParamsFile))
                {
                    if (File.GetLastWriteTime(lastGenerationParamsFile) > File.GetLastWriteTime(generatorParams.OutputFilePath))
                    {
                        File.Delete(lastGenerationParamsFile);
                        File.Copy(generatorParams.OutputFilePath, lastGenerationParamsFile);
                    }
                }
                else
                {
                    File.Copy(generatorParams.OutputFilePath, lastGenerationParamsFile);
                }

                var autogenParams = GeneratorParams.LoadFromFile(inputFilePath);
                Assert.AreEqual(autogenParams.TargetFramework, generatorParams.TargetFramework);
                Assert.AreEqual(autogenParams.GenerateDataContracts, generatorParams.GenerateDataContracts);
                Assert.AreEqual(autogenParams.EnableDataBinding, generatorParams.EnableDataBinding);
                Assert.AreEqual(autogenParams.PropertyParams.AutomaticProperties, generatorParams.PropertyParams.AutomaticProperties);
                Assert.AreEqual(autogenParams.Miscellaneous.EnableSummaryComment, generatorParams.Miscellaneous.EnableSummaryComment);
                Assert.AreEqual(autogenParams.GenericBaseClass.Enabled, generatorParams.GenericBaseClass.Enabled);
                Assert.AreEqual(autogenParams.GenericBaseClass.GenerateBaseClass, generatorParams.GenericBaseClass.GenerateBaseClass);
                Assert.AreEqual(autogenParams.GenericBaseClass.BaseClassName, generatorParams.GenericBaseClass.BaseClassName);
                File.Delete(lastGenerationParamsFile);
            }
        }
Example #9
0
        private void GenerateAndCompile(GeneratorParams generatorParams, params string[] additionalFiles)
        {
            var xsdGen = new GeneratorFacade(generatorParams);
            var result = xsdGen.Generate();

            Assert.IsTrue(result.Success, result.Messages.ToString());

            var canCompile = CompileCSFile(generatorParams.OutputFilePath, additionalFiles);

            Assert.IsTrue(canCompile.Success, canCompile.Messages.ToString());
        }
Example #10
0
        public void Circular()
        {
            lock (testLock)
            {
                // Copy resource file to the run-time directory
                string inputFilePath = GetInputFilePath("Circular.xsd", Resources.Circular);

                var xsdGen = new GeneratorFacade(GetGeneratorParams(inputFilePath));
                var result = xsdGen.Generate();

                Assert.IsTrue(result.Success, result.Messages.ToString());
            }
        }
        public void Throw_Exception_When_Database_Is_Null()
        {
            Assesment assesment = new Assesment();

            assesment.Name           = "Test";
            assesment.SourcePlatform = "OnPrem";
            assesment.Status         = "Completed";
            assesment.TargetPlatform = "Azure Managed Instance";
            //assesment.Databases = new List<Database>();
            assesment.ServerInstances = new List <ServerInstance>();
            Assert.Throws <InvalidDataException>
                (() => GeneratorFacade.Generate(assesment));
        }
Example #12
0
        public void Run()
        {
            bool confirm = false;

            while (confirm == false)
            {
                Console.WriteLine("Please Enter the number of cities the salesman will visit");
                cityCount = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine("Please Enter the number of solutions per generation");
                population = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine("Please enter the total number of generations to create");
                generations = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine("Please enter, in decimal format, the mutation rate.");
                mutationRate = Convert.ToDouble(Console.ReadLine());

                Console.WriteLine("Please enter a seed value");
                seed = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine();
                Console.WriteLine($"The salesman will visit {cityCount} cities.");
                Console.WriteLine($"The location of these cities will be generated with the seed value {seed}.");
                Console.WriteLine($"There will be {population} solutions generated, and {generations} generations overall. ");
                Console.WriteLine($"This will cause a total of {population * generations} solution objects to be created.");
                Console.WriteLine($"{mutationRate * 100}% of solution objects generated after the initial generation will be mutated.");

                Console.WriteLine();
                Console.WriteLine($"Do you wish to proceed? [Y/N]");
                if (Console.ReadLine() == "y" || Console.ReadLine() == "Y")
                {
                    confirm = true;
                }
            }
            generator.Generate(population, generations, cityCount, mutationRate, seed);
            Solution      bestFit = generator.GetBestFit();
            StringBuilder sb      = new StringBuilder();

            foreach (string location in bestFit.path)
            {
                sb.Append($"{location} ");
            }

            Console.WriteLine($"The best solution, after {generations} generations, is thus");
            Console.WriteLine($"PATH     : {sb.ToString()}");
            Console.WriteLine($"DISTANCE : {bestFit.distance}");
            Console.WriteLine($"ID       : {bestFit.id}");
            Console.ReadLine();
        }
        public void Works_Properly_When_Valid_Input_Is_Given()
        {
            Assesment assesment = new Assesment();

            assesment.Name            = "Test";
            assesment.SourcePlatform  = "OnPrem";
            assesment.Status          = "Completed";
            assesment.TargetPlatform  = "Azure Managed Instance";
            assesment.Databases       = new List <Database>();
            assesment.ServerInstances = new List <ServerInstance>();
            var table = GeneratorFacade.Generate(assesment);

            Assert.NotNull(table);
        }
Example #14
0
        public void Hierarchical()
        {
            lock (testLock)
            {
                // Copy resource file to the run-time directory
                string inputFilePath = GetInputFilePath("Hierarchical.xsd", Resources.Hierarchical);

                var generatorParams = GetGeneratorParams(inputFilePath);
                var xsdGen          = new GeneratorFacade(generatorParams);
                var result          = xsdGen.Generate();

                Assert.IsTrue(result.Success, result.Messages.ToString());

                var compileResult = CompileCSFile(generatorParams.OutputFilePath);
                Assert.IsTrue(compileResult.Success, compileResult.Messages.ToString());
            }
        }
Example #15
0
        public void HexBinary()
        {
            lock (testLock)
            {
                // Copy resource file to the run-time directory
                string inputFilePath = GetInputFilePath("hexBinary.xsd", Resources.hexBinary);

                var generatorParams = GetGeneratorParams(inputFilePath);
                generatorParams.EnableInitializeFields = true;
                var xsdGen = new GeneratorFacade(generatorParams);
                var result = xsdGen.Generate();

                Assert.IsTrue(result.Success, result.Messages.ToString());

                var compileResult = CompileCSFile(generatorParams.OutputFilePath);
                Assert.IsTrue(compileResult.Success, compileResult.Messages.ToString());
            }
        }
Example #16
0
        public void LazyLoading()
        {
            lock (testLock)
            {
                // Copy resource file to the run-time directory
                string inputFilePath   = GetInputFilePath("LazyLoading.xsd", Resources.LazyLoading);
                var    generatorParams = GetGeneratorParams(inputFilePath);
                generatorParams.CollectionObjectType             = CollectionType.List;
                generatorParams.TargetFramework                  = TargetFramework.Net20;
                generatorParams.PropertyParams.EnableLazyLoading = true;
                generatorParams.EnableInitializeFields           = true;

                var xsdGen = new GeneratorFacade(generatorParams);
                xsdGen.Generate();

                var compileResult = CompileCSFile(generatorParams.OutputFilePath);
                Assert.IsTrue(compileResult.Success, compileResult.Messages.ToString());
            }
        }
Example #17
0
        public void Silverlight()
        {
            lock (testLock)
            {
                // Get the code namespace for the schema.
                GetInputFilePath("Actor.xsd", Resources.Actor);
                string inputFilePath = GetInputFilePath("dvd.xsd", Resources.dvd);

                var generatorParams = GetGeneratorParams(inputFilePath);
                generatorParams.TargetFramework = TargetFramework.Silverlight;
                generatorParams.OutputFilePath  = Path.ChangeExtension(generatorParams.InputFilePath,
                                                                       ".Silverlight20_01.cs");

                generatorParams.Serialization.Enabled        = true;
                generatorParams.Serialization.EnableEncoding = true;
                var xsdGen = new GeneratorFacade(generatorParams);

                var result = xsdGen.Generate();
                Assert.IsTrue(result.Success, result.Messages.ToString());
            }
        }
Example #18
0
        public void AlowDebug()
        {
            lock (testLock)
            {
                // Copy resource file to the run-time directory
                GetInputFilePath("Actor.xsd", Resources.Actor);
                string inputFilePath = GetInputFilePath("Dvd.xsd", Resources.dvd);

                var generatorParams = GetGeneratorParams(inputFilePath);
                generatorParams.Miscellaneous.DisableDebug = false;
                generatorParams.OutputFilePath             = Path.ChangeExtension(generatorParams.InputFilePath, ".DebugEnabled.cs");

                var xsdGen = new GeneratorFacade(generatorParams);
                var result = xsdGen.Generate();

                Assert.IsTrue(result.Success, result.Messages.ToString());

                var compileResult = CompileCSFile(generatorParams.OutputFilePath);
                Assert.IsTrue(compileResult.Success, compileResult.Messages.ToString());
            }
        }
Example #19
0
        public void WcfAttributes()
        {
            lock (testLock)
            {
                // Get the code namespace for the schema.
                GetInputFilePath("Actor.xsd", Resources.Actor);
                string inputFilePath = GetInputFilePath("dvd.xsd", Resources.dvd);

                var generatorParams = GetGeneratorParams(inputFilePath);
                generatorParams.GenerateDataContracts = true;
                generatorParams.TargetFramework       = TargetFramework.Net30;
                generatorParams.OutputFilePath        = Path.ChangeExtension(generatorParams.InputFilePath, ".wcf.cs");

                var xsdGen = new GeneratorFacade(generatorParams);
                var result = xsdGen.Generate();

                Assert.IsTrue(result.Success, result.Messages.ToString());

                var compileResult = CompileCSFile(generatorParams.OutputFilePath);
                Assert.IsTrue(compileResult.Success, compileResult.Messages.ToString());
            }
        }
Example #20
0
        public void PropertyNameSpecified()
        {
            lock (testLock)
            {
                // Copy resource file to the run-time directory
                string inputFilePath   = GetInputFilePath("PropertyNameSpecified.xsd", Resources.PropertyNameSpecified);
                var    generatorParams = GetGeneratorParams(inputFilePath);
                generatorParams.TargetFramework       = TargetFramework.Net20;
                generatorParams.Serialization.Enabled = false;
                generatorParams.Miscellaneous.HidePrivateFieldInIde = false;

                // All
                generatorParams.PropertyParams.GeneratePropertyNameSpecified = PropertyNameSpecifiedType.All;
                generatorParams.OutputFilePath = Path.ChangeExtension(generatorParams.InputFilePath, ".all.cs");
                var xsdGen = new GeneratorFacade(generatorParams);
                var result = xsdGen.Generate();

                var compileResult = CompileCSFile(generatorParams.OutputFilePath);
                Assert.IsTrue(compileResult.Success, compileResult.Messages.ToString());

                // none
                generatorParams.PropertyParams.GeneratePropertyNameSpecified = PropertyNameSpecifiedType.None;
                generatorParams.OutputFilePath = Path.ChangeExtension(generatorParams.InputFilePath, ".none.cs");
                xsdGen = new GeneratorFacade(generatorParams);
                result = xsdGen.Generate();

                compileResult = CompileCSFile(generatorParams.OutputFilePath);
                Assert.IsTrue(compileResult.Success, compileResult.Messages.ToString());

                // Default
                generatorParams.PropertyParams.GeneratePropertyNameSpecified = PropertyNameSpecifiedType.Default;
                generatorParams.OutputFilePath = Path.ChangeExtension(generatorParams.InputFilePath, ".default.cs");
                xsdGen = new GeneratorFacade(generatorParams);
                result = xsdGen.Generate();

                compileResult = CompileCSFile(generatorParams.OutputFilePath);
                Assert.IsTrue(compileResult.Success, compileResult.Messages.ToString());
            }
        }
Example #21
0
        public void CircularClassReference()
        {
            lock (testLock)
            {
                // Copy resource file to the run-time directory
                string inputFilePath   = GetInputFilePath("CircularClassReference.xsd", Resources.CircularClassReference);
                var    generatorParams = new GeneratorParams
                {
                    InputFilePath   = inputFilePath,
                    TargetFramework = TargetFramework.Net20,
                    OutputFilePath  = GetOutputFilePath(inputFilePath)
                };
                generatorParams.PropertyParams.AutomaticProperties = true;
                generatorParams.Serialization.Enabled    = false;
                generatorParams.GenericBaseClass.Enabled = false;

                var xsdGen = new GeneratorFacade(generatorParams);
                var result = xsdGen.Generate();

                Assert.IsTrue(result.Success, result.Messages.ToString());

                try
                {
                    var cs = new Circular();

#pragma warning disable 168
                    int count = cs.circular.count;
#pragma warning restore 168

                    var compileResult = CompileCSFile(generatorParams.OutputFilePath);
                    Assert.IsTrue(compileResult.Success, compileResult.Messages.ToString());
                }
                catch (Exception e)
                {
                    Assert.Fail(e.Message);
                }
            }
        }
Example #22
0
        public void Gender()
        {
            lock (testLock)
            {
                // Get the code namespace for the schema.
                string inputFilePath = GetInputFilePath("Gender.xsd", Resources.Gender);

                var generatorParams = GetGeneratorParams(inputFilePath);
                generatorParams.TargetFramework = TargetFramework.Net30;
                generatorParams.PropertyParams.AutomaticProperties = true;
                generatorParams.GenerateDataContracts = true;
                generatorParams.Serialization.GenerateXmlAttributes = true;
                generatorParams.OutputFilePath = GetOutputFilePath(inputFilePath);

                var xsdGen = new GeneratorFacade(generatorParams);

                var result = xsdGen.Generate();

                Assert.IsTrue(result.Success, result.Messages.ToString());

                var genderRoot = new Root
                {
                    GenderAttribute          = ksgender.female,
                    GenderAttributeSpecified = true,
                    GenderElement            = ksgender.female,
                    GenderIntAttribute       = "toto"
                };
                Exception ex;
                genderRoot.SaveToFile(Path.Combine(OutputFolder, "gender.xml"), out ex);
                if (ex != null)
                {
                    throw ex;
                }

                var canCompile = CompileCSFile(generatorParams.OutputFilePath);
                Assert.IsTrue(canCompile.Success, canCompile.Messages.ToString());
            }
        }
Example #23
0
        private static void GenereateCodeWithXsd2Code(string xsdFilepath, string codeOutPath, string nameSpace)
        {
            GeneratorParams generatorParams = new GeneratorParams
            {
                InputFilePath        = xsdFilepath,
                OutputFilePath       = codeOutPath,
                Language             = GenerationLanguage.CSharp,
                NameSpace            = nameSpace,
                CollectionObjectType = CollectionType.List,
                PropertyParams       =
                {
                    AutomaticProperties = true,
                    PascalCaseProperty  = true
                },
                Serialization = { Enabled = true, GenerateXmlAttributes = true }
            };

            // Create an instance of Generator
            GeneratorFacade generator = new GeneratorFacade(generatorParams);

            // Generate code
            Result <string> result = generator.Generate();
        }
Example #24
0
        public void XMLAttributes()
        {
            lock (testLock)
            {
                // Get the code namespace for the schema.
                GetInputFilePath("Actor.xsd", Resources.Actor);
                string inputFilePath = GetInputFilePath("mailxml_base.xsd", Resources.mailxml_base);
                GetInputFilePath("mailxml_base_120108.xsd", Resources.mailxml_base_120108);

                var generatorParams = GetGeneratorParams(inputFilePath);
                generatorParams.TargetFramework = TargetFramework.Net30;
                generatorParams.PropertyParams.AutomaticProperties  = true;
                generatorParams.Serialization.GenerateXmlAttributes = true;
                generatorParams.OutputFilePath = Path.ChangeExtension(generatorParams.InputFilePath, ".xml.cs");

                var xsdGen = new GeneratorFacade(generatorParams);
                var result = xsdGen.Generate();

                Assert.IsTrue(result.Success, result.Messages.ToString());

                //var compileResult = CompileCSFile(generatorParams.OutputFilePath);
                //Assert.IsTrue(compileResult.Success, compileResult.Messages.ToString());
            }
        }
Example #25
0
        public void Dvd()
        {
            lock (testLock)
            {
                // Copy resource file to the run-time directory
                GetInputFilePath("Actor.xsd", Resources.Actor);

                // Copy resource file to the run-time directory
                string inputFilePath   = GetInputFilePath("Dvd.xsd", Resources.dvd);
                var    generatorParams = GetGeneratorParams(inputFilePath);
                generatorParams.CollectionObjectType = CollectionType.List;
                generatorParams.TargetFramework      = TargetFramework.Net35;
                generatorParams.EnableDataBinding    = true;
                generatorParams.Miscellaneous.EnableSummaryComment = true;
                generatorParams.GenerateDataContracts                   = false;
                generatorParams.GenericBaseClass.Enabled                = false;
                generatorParams.Serialization.GenerateXmlAttributes     = true;
                generatorParams.TrackingChanges.Enabled                 = false;
                generatorParams.TrackingChanges.GenerateTrackingClasses = false;
                generatorParams.Serialization.EnableEncoding            = false;
                generatorParams.Serialization.DefaultEncoder            = DefaultEncoder.UTF8;

                var xsdGen = new GeneratorFacade(generatorParams);
                var result = xsdGen.Generate();

                Assert.IsTrue(result.Success, result.Messages.ToString());

                // Create new dvd collection and save it to file
                var dvd = new DvdCollection();
                dvd.Dvds.Add(new dvd {
                    Title = "Matrix יא?"
                });
                var newitem = new dvd();
                newitem.Actor.Add(new Actor {
                    firstname = "Jamיs א&", nationality = "Us"
                });
                dvd.Dvds.Add(newitem);
                var originalXml = dvd.Serialize();
                var dvdFile     = Path.Combine(OutputFolder, "dvd.xml");
                dvd.SaveToFile(dvdFile);

                // Load data fom file and serialize it again.

                var loadedDvdCollection = DvdCollection.LoadFromFile(dvdFile);
                var finalXml            = loadedDvdCollection.Serialize();

                // Then comprate two xml string
                if (!originalXml.Equals(finalXml))
                {
                    Assert.Fail("Xml value are not equals");
                }
                Exception     exp;
                DvdCollection deserialiseDvd;

                var testEncodings = new [] {
                    Encoding.ASCII, Encoding.UTF8, Encoding.Unicode, Encoding.UTF32
                };
                foreach (var encoding in testEncodings)
                {
                    var encodedFile = Path.Combine(OutputFolder, "dvd" + encoding.EncodingName + ".xml");
                    dvd.SaveToFile(encodedFile, encoding);
                    if (!DvdCollection.LoadFromFile(encodedFile, encoding, out deserialiseDvd, out exp))
                    {
                        Assert.Fail("LoadFromFile failed on {0} encoding", encoding.EncodingName);
                    }
                    else if (!deserialiseDvd.Dvds[0].Title.Equals("Matrix יא?"))
                    {
                        Assert.Fail("LoadFromFile failed on {0} encoding", encoding.EncodingName);
                    }
                }

                var compileResult = CompileCSFile(generatorParams.OutputFilePath);
                Assert.IsTrue(compileResult.Success, compileResult.Messages.ToString());
            }
        }
        /// <summary>
        /// Code from Xsd2Code.Addin::Connect
        /// </summary>
        private void openConfigurationWindow()
        {
            ProjectItem proitem          = Dte.SelectedItems.Item(1).ProjectItem;
            Project     proj             = proitem.ContainingProject;
            string      projectDirectory = Path.GetDirectoryName(proj.FullName);

            // Try to get default nameSpace
            string defaultNamespace = string.Empty;
            uint?  targetFramework  = 0;
            bool?  isSilverlightApp = false;

            try
            {
                defaultNamespace = proj.Properties.Item("DefaultNamespace").Value as string;
                targetFramework  = proj.Properties.Item("TargetFramework").Value as uint?;
                isSilverlightApp = proj.Properties.Item("SilverlightProject.IsSilverlightApplication").Value as bool?;
            }
            catch
            {
            }

            string xsdFileName = proitem.FileNames[0];

            try
            {
                proitem.Save(xsdFileName);
            }
            catch (Exception)
            {
            }

            TargetFramework framework = TargetFramework.Net20;

            if (targetFramework.HasValue)
            {
                uint target = targetFramework.Value;
                switch (target)
                {
                case 196608:
                    framework = TargetFramework.Net30;
                    break;

                case 196613:
                    framework = TargetFramework.Net35;
                    break;

                case 262144:
                    framework = TargetFramework.Net40;
                    break;
                }
            }
            if (isSilverlightApp.HasValue)
            {
                if (isSilverlightApp.Value)
                {
                    framework = TargetFramework.Silverlight;
                }
            }

            // We associate an outputfile with the selected XSD file to know were to look for the parameters
            // TODO embed all the parameters as attributes of the XSD file in the project ?
            IVsHierarchy            hierarchy = null;
            uint                    itemid;
            string                  outputFile           = null;
            IVsBuildPropertyStorage buildPropertyStorage = null;

            if (IsSingleProjectItemSelection(out hierarchy, out itemid))
            {
                buildPropertyStorage = hierarchy as IVsBuildPropertyStorage;
                if (buildPropertyStorage != null)
                {
                    buildPropertyStorage.GetItemAttribute(itemid, "Xsd2CodeOutputFile", out outputFile);
                }
            }

            var frm = new FormOption();

            frm.Init(xsdFileName, proj.CodeModel.Language, defaultNamespace, framework, Path.IsPathRooted(outputFile) ? outputFile : Path.Combine(projectDirectory, outputFile ?? string.Empty));

            DialogResult result = frm.ShowDialog();

            GeneratorParams generatorParams = frm.GeneratorParams.Clone();

            generatorParams.InputFilePath = xsdFileName;

            var gen = new GeneratorFacade(generatorParams);

            bool foundOutputFile = false;

            if (xsdFileName.Length > 0)
            {
                if (result == DialogResult.OK)
                {
                    // Close file if open in IDE
                    ProjectItem projElmts = null;
                    if (!String.IsNullOrEmpty(outputFile))
                    {
                        string rootedOutputFile = Path.IsPathRooted(outputFile) ? outputFile : Path.Combine(projectDirectory, outputFile);
                        foundOutputFile = FindInProject(proj.ProjectItems, rootedOutputFile, out projElmts);
                        if (foundOutputFile)
                        {
                            Window window = projElmts.Open(EnvDTE.Constants.vsViewKindCode);
                            window.Close(vsSaveChanges.vsSaveChangesNo);
                        }
                    }

                    Result <List <string> > generateResult  = gen.Generate();
                    List <string>           outputFileNames = generateResult.Entity;

                    if (!generateResult.Success)
                    {
                        MessageBox.Show(generateResult.Messages.ToString(), "XSD2Code", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        string vsProjectOutputFilePath = outputFileNames[0];
                        // Save one of the output file path so we can read the parameters from it the next time
                        if (buildPropertyStorage != null)
                        {
                            buildPropertyStorage.SetItemAttribute(itemid, "Xsd2CodeOutputFile", GetRelativePath(vsProjectOutputFilePath, projectDirectory));
                        }

                        // try again now that the generation occured
                        string newRootedOutputFile = Path.Combine(projectDirectory, vsProjectOutputFilePath);
                        foundOutputFile = FindInProject(proj.ProjectItems, newRootedOutputFile, out projElmts);
                        if (!foundOutputFile)
                        {
                            projElmts = proj.ProjectItems.AddFromFile(newRootedOutputFile);
                        }


                        if (frm.OpenAfterGeneration && projElmts != null)
                        {
                            Window window = projElmts.Open(EnvDTE.Constants.vsViewKindCode);
                            window.Activate();
                            window.SetFocus();

                            try
                            {
                                // this.applicationObjectField.DTE.ExecuteCommand("Edit.RemoveAndSort", "");
                                Dte.ExecuteCommand("Edit.FormatDocument", string.Empty);
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }
            }

            return;
        }
Example #27
0
        private static void Main(string[] args)
        {
            // Display hekp when no parameters have been specified
            if (args.Length < 1)
            {
                DisplayApplicationInfo();
                DisplayHelp();
                return;
            }

            DisplayApplicationInfo();

            // Create new instance of GeneratorParams, which contains all generation parameters
            var xsdFilePath     = args[0];
            var generatorParams = new GeneratorParams {
                InputFilePath = xsdFilePath
            };

            // When only the XSD file name is specified,
            // try to locate generated Designer file and load output parameters from the file header
            if (args.Length == 1)
            {
                string outputFilePath;
                var    tempGeneratorParams = GeneratorParams.LoadFromFile(xsdFilePath, out outputFilePath);
                if (tempGeneratorParams != null)
                {
                    generatorParams = tempGeneratorParams;
                    generatorParams.InputFilePath = xsdFilePath;

                    if (!string.IsNullOrEmpty(outputFilePath))
                    {
                        generatorParams.OutputFilePath = outputFilePath;
                    }
                }
            }

            // Second command-line parameter that is not a switch  is the generated code namespace
            if (args.Length > 1 && !args[1].StartsWith("/"))
            {
                generatorParams.NameSpace = args[1];

                // Third command-line parameter that is not a switch is the generated code namespace
                if (args.Length > 2 && !args[2].StartsWith("/"))
                {
                    generatorParams.OutputFilePath = args[2];
                }
            }

            // Process command-line parameter switches
            for (int i = 1; i < args.Length; i++)
            {
                switch (args[i].Trim().ToLower())
                {
                case "/n":
                case "/ns":
                case "/namespace":
                    if (i < args.Length - 1)
                    {
                        generatorParams.NameSpace = args[i + 1];
                        i++;
                    }
                    break;

                case "/o":
                case "/out":
                case "/output":
                    if (i < args.Length - 1)
                    {
                        generatorParams.OutputFilePath = args[i + 1];
                        i++;
                    }
                    break;

                case "/l":
                case "/lang":
                case "/language":
                    if (i < args.Length - 1)
                    {
                        generatorParams.Language = Utility.GetGenerationLanguage(args[i + 1]);
                        i++;
                    }
                    break;

                case "/c":
                case "/col":
                case "/collection":
                case "/collectionbase":
                    if (i < args.Length - 1)
                    {
                        generatorParams.CollectionObjectType = Utility.ToEnum <CollectionType>(args[i + 1]);
                        i++;
                    }
                    break;

                //Duplicate with /pl
                case "/cb":
                case "/codebase":
                    if (i < args.Length - 1)
                    {
                        Console.WriteLine("Warning: /cb /codebase is obsolete please use /pl[atform] <Platform> - Generated code target platform (Net20|Net30|Net35|Silverlight20). Default: Net20");
                        generatorParams.TargetFramework = Utility.ToEnum <TargetFramework>(args[i + 1]);
                        i++;
                    }
                    break;

                case "/gsf":
                case "/generateseparatefiles":
                    if (i < args.Length - 1)
                    {
                        generatorParams.GenerateSeparateFiles = true;
                    }
                    break;

                case "/cu":
                case "/customusings":
                    if (i < args.Length - 1)
                    {
                        //generatorParams.CustomUsingsString = args[i + 1];

                        foreach (string item in args[i + 1].Split(','))
                        {
                            generatorParams.CustomUsings.Add(new NamespaceParam {
                                NameSpace = item
                            });
                        }

                        i++;
                    }
                    break;

                case "/lf":
                case "/lfm":
                    if (i < args.Length - 1)
                    {
                        generatorParams.Serialization.LoadFromFileMethodName = args[i + 1];
                        i++;
                    }
                    break;

                case "/sm":
                    if (i < args.Length - 1)
                    {
                        generatorParams.Serialization.SerializeMethodName = args[i + 1];
                        i++;
                    }
                    break;

                case "/sf":
                case "/sfm":
                    if (i < args.Length - 1)
                    {
                        generatorParams.Serialization.SaveToFileMethodName = args[i + 1];
                        i++;
                    }
                    break;

                case "/p":
                case "/pl":
                case "/tp":
                case "/tpl":
                case "/platform":
                    if (i < args.Length - 1)
                    {
                        generatorParams.TargetFramework = Utility.GetTargetPlatform(args[i + 1]);
                        i++;
                    }
                    break;

                case "/u":
                case "/us":
                case "/using":
                    if (i < args.Length - 1)
                    {
                        var nsList = args[i + 1].Split(',');
                        foreach (var ns in nsList)
                        {
                            generatorParams.CustomUsings.Add(new NamespaceParam {
                                NameSpace = ns
                            });
                        }
                        i++;
                    }
                    break;

                case "/dbg":
                case "/dbg+":
                case "/debug":
                case "/debug+":
                    generatorParams.Miscellaneous.DisableDebug = false;
                    break;

                case "/dbg-":
                case "/debug-":
                    generatorParams.Miscellaneous.DisableDebug = true;
                    break;

                case "/db":
                case "/db+":
                    generatorParams.EnableDataBinding = true;
                    break;

                case "/db-":
                    generatorParams.EnableDataBinding = false;
                    break;

                case "/dc":
                case "/dc+":
                    generatorParams.GenerateDataContracts = true;
                    break;

                case "/dc-":
                    generatorParams.GenerateDataContracts = false;
                    break;

                case "/ap":
                case "/ap+":
                    generatorParams.PropertyParams.AutomaticProperties = true;
                    break;

                case "/ap-":
                    generatorParams.PropertyParams.AutomaticProperties = false;
                    break;

                case "/if":
                case "/if+":
                    generatorParams.EnableInitializeFields = true;
                    break;

                case "/if-":
                    generatorParams.EnableInitializeFields = false;
                    break;

                case "/eit":
                case "/eit+":
                    generatorParams.Miscellaneous.ExcludeIncludedTypes = true;
                    break;

                case "/eit-":
                    generatorParams.Miscellaneous.ExcludeIncludedTypes = false;
                    break;

                case "/gbc":
                case "/gbc+":
                    generatorParams.GenericBaseClass.Enabled = true;
                    break;

                case "/gbc-":
                    generatorParams.GenericBaseClass.Enabled = false;
                    break;

                case "/ggbc":
                case "/ggbc+":
                    generatorParams.GenericBaseClass.GenerateBaseClass = true;
                    break;

                case "/ggbc-":
                    generatorParams.GenericBaseClass.GenerateBaseClass = false;
                    break;

                case "/sc":
                case "/sc+":
                    generatorParams.Miscellaneous.EnableSummaryComment = true;
                    break;

                case "/sc-":
                case "/sum-":
                    generatorParams.Miscellaneous.EnableSummaryComment = false;
                    break;

                case "/xa":
                case "/xa+":
                    generatorParams.Serialization.GenerateXmlAttributes = true;
                    break;

                case "/xa-":
                    generatorParams.Serialization.GenerateXmlAttributes = false;
                    break;

                case "/cl":
                case "/cl+":
                    generatorParams.GenerateCloneMethod = true;
                    break;

                case "/cl-":
                    generatorParams.GenerateCloneMethod = false;
                    break;

                case "/hp":
                case "/hp+":
                    generatorParams.Miscellaneous.HidePrivateFieldInIde = true;
                    break;

                case "/hp-":
                    generatorParams.Miscellaneous.HidePrivateFieldInIde = false;
                    break;

                case "/tc":
                case "/tc+":
                    generatorParams.TrackingChanges.Enabled = true;
                    break;

                case "/tc-":
                    generatorParams.TrackingChanges.Enabled = false;
                    break;

                case "/tcc":
                case "/tcc+":
                    generatorParams.TrackingChanges.GenerateTrackingClasses = true;
                    break;

                case "/tcc-":
                    generatorParams.TrackingChanges.GenerateTrackingClasses = false;
                    break;

                case "/ssp":
                case "/ssp+":
                    generatorParams.PropertyParams.GenerateShouldSerializeProperty = true;
                    break;

                case "/ssp-":
                    generatorParams.PropertyParams.GenerateShouldSerializeProperty = false;
                    break;

                case "/s":
                case "/s+":
                case "/is":
                case "/is+":
                    generatorParams.Serialization.Enabled = true;
                    break;

                case "/s-":
                case "/is-":
                    generatorParams.Serialization.Enabled = false;
                    break;

                case "/ee":
                case "/ee+":
                    generatorParams.Serialization.EnableEncoding = true;
                    break;

                case "/ee-":
                    generatorParams.Serialization.EnableEncoding = false;
                    break;

                case "/lic":
                case "/license":
                    DisplayLicense();
                    return;

                case "/?":
                case "/h":
                case "/hlp":
                case "/help":
                    DisplayHelp();
                    return;
                }
            }

            // Auto-generate missing output file path
            if (string.IsNullOrEmpty(generatorParams.OutputFilePath))
            {
                generatorParams.OutputFilePath =
                    Utility.GetOutputFilePath(generatorParams.InputFilePath,
                                              generatorParams.Language);
            }

            // Auto-generate missing generated code namespace
            if (string.IsNullOrEmpty(generatorParams.NameSpace))
            {
                generatorParams.NameSpace = Path.GetFileNameWithoutExtension(generatorParams.InputFilePath);
            }


            // Create an instance of Generator
            var generator = new GeneratorFacade(generatorParams);

            // Generate code
            var result = generator.Generate();

            if (!result.Success)
            {
                // Display the error and wait for user confirmation
                Console.WriteLine();
                Console.WriteLine(result.Messages.ToString());
                Console.WriteLine();
                Console.WriteLine("Press ENTER to continue...");
                Console.ReadLine();

                return;
            }

            Console.WriteLine("Generated code has been saved into the file {0}.", result.Entity);

            Console.WriteLine();
            Console.WriteLine("Finished");
            Console.WriteLine();
        }
Example #28
0
        /// <summary>
        /// Execute Addin Command
        /// </summary>
        /// <param name="cmdName">
        /// Command name
        /// </param>
        /// <param name="executeOption">
        /// Execute options
        /// </param>
        /// <param name="variantIn">
        /// object variant in
        /// </param>
        /// <param name="variantOut">
        /// object variant out
        /// </param>
        /// <param name="handled">
        /// Handled true or false
        /// </param>
        public void Exec(string cmdName, vsCommandExecOption executeOption, ref object variantIn, ref object variantOut, ref bool handled)
        {
            handled = false;
            if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
            {
                if (cmdName == "Xsd2Code.Addin.Connect.Xsd2CodeAddin")
                {
                    UIHierarchy uIH  = this.applicationObjectField.ToolWindows.SolutionExplorer;
                    var         item = (UIHierarchyItem)((Array)uIH.SelectedItems).GetValue(0);

                    UIHierarchyItems items = item.UIHierarchyItems;

                    ProjectItem proitem = uIH.DTE.SelectedItems.Item(1).ProjectItem;
                    Project     proj    = proitem.ContainingProject;

                    // Try to get default nameSpace
                    string defaultNamespace = string.Empty;
                    uint?  targetFramework  = 0;
                    bool?  isSilverlightApp = false;
                    try
                    {
                        defaultNamespace = proj.Properties.Item("DefaultNamespace").Value as string;
                        targetFramework  = proj.Properties.Item("TargetFramework").Value as uint?;
                        isSilverlightApp = proj.Properties.Item("SilverlightProject.IsSilverlightApplication").Value as bool?;
                    }
                    catch
                    {
                    }

                    CodeModel codeModel = proitem.ContainingProject.CodeModel;
                    string    fileName  = proitem.FileNames[0];
                    try
                    {
                        proitem.Save(fileName);
                    }
                    catch (Exception)
                    {
                    }

                    TargetFramework framework = TargetFramework.Net20;
                    if (targetFramework.HasValue)
                    {
                        uint target = targetFramework.Value;
                        switch (target)
                        {
                        case 196608:
                            framework = TargetFramework.Net30;
                            break;

                        case 196613:
                            framework = TargetFramework.Net35;
                            break;

                        case 262144:
                            framework = TargetFramework.Net40;
                            break;
                        }
                    }
                    if (isSilverlightApp.HasValue)
                    {
                        if (isSilverlightApp.Value)
                        {
                            framework = TargetFramework.Silverlight;
                        }
                    }

                    var frm = new FormOption();
                    frm.Init(fileName, proj.CodeModel.Language, defaultNamespace, framework);

                    DialogResult result = frm.ShowDialog();

                    GeneratorParams generatorParams = frm.GeneratorParams.Clone();
                    generatorParams.InputFilePath = fileName;

                    var gen = new GeneratorFacade(generatorParams);

                    // Close file if open in IDE
                    ProjectItem projElmts;
                    bool        found = FindInProject(proj.ProjectItems, gen.GeneratorParams.OutputFilePath, out projElmts);
                    if (found)
                    {
                        Window window = projElmts.Open(Constants.vsViewKindCode);
                        window.Close(vsSaveChanges.vsSaveChangesNo);
                    }

                    if (fileName.Length > 0)
                    {
                        if (result == DialogResult.OK)
                        {
                            Result <string> generateResult = gen.Generate();
                            string          outputFileName = generateResult.Entity;

                            if (!generateResult.Success)
                            {
                                MessageBox.Show(generateResult.Messages.ToString(), "XSD2Code", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                                if (!found)
                                {
                                    projElmts = proitem.Collection.AddFromFile(outputFileName);
                                }

                                if (frm.OpenAfterGeneration)
                                {
                                    Window window = projElmts.Open(Constants.vsViewKindCode);
                                    window.Activate();
                                    window.SetFocus();

                                    try
                                    {
                                        // this.applicationObjectField.DTE.ExecuteCommand("Edit.RemoveAndSort", "");
                                        applicationObjectField.DTE.ExecuteCommand("Edit.FormatDocument", string.Empty);
                                    }
                                    catch (Exception)
                                    {
                                    }
                                }
                            }
                        }
                    }

                    handled = true;
                    return;
                }
            }
        }
Example #29
0
        static void Main(string[] args)
        {
            const string outFile = @"cobieliteuk.designer.cs";
            const string inFile  = @"..\..\..\Xbim.COBieLiteUK\Schemas\cobieliteuk.xsd";

            if (!File.Exists(inFile))
            {
                Console.WriteLine(@"COBieLiteUK schema not found.");
            }

            var generatorParams = new GeneratorParams
            {
                InputFilePath          = inFile,
                CollectionObjectType   = CollectionType.List,
                Language               = GenerationLanguage.CSharp,
                NameSpace              = "Xbim.COBieLiteUK",
                OutputFilePath         = outFile,
                TargetFramework        = TargetFramework.CobieLiteUk,
                EnableInitializeFields = false,
                Serialization          = new SerializeParams
                {
                    DefaultEncoder        = DefaultEncoder.UTF8,
                    GenerateXmlAttributes = true
                }
            };

            generatorParams.PropertyParams = new PropertyParams(generatorParams)
            {
                GenerateShouldSerializeProperty = true,
                GeneratePropertyNameSpecified   = PropertyNameSpecifiedType.None
            };

            // Create an instance of Generator
            var generator = new GeneratorFacade(generatorParams);

            // Generate code
            var result = generator.Generate();

            if (!result.Success)
            {
                // Display the error and wait for user confirmation
                Console.WriteLine();
                Console.WriteLine(result.Messages.ToString());
                Console.WriteLine();
                Console.WriteLine(@"Press ENTER to continue...");
                Console.ReadLine();

                return;
            }

            //do textual replacement
            var outFileFullPath = Path.Combine(Path.GetDirectoryName(inFile), outFile);
            var code            = File.ReadAllText(outFileFullPath);

            code = code.Replace("System.", "global::System.");
            code = code.Replace("System;", "global::System;");
            File.WriteAllText(outFileFullPath, code);


            Console.WriteLine(@"Generated code has been saved to the file {0}.", result.Entity);

            Console.WriteLine();
            Console.WriteLine(@"Finished");
            Console.WriteLine();
        }
Example #30
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            DTE dte = (DTE)ServiceProvider.GetService(typeof(DTE));

            ProjectItem proitem = dte.SelectedItems.Item(1).ProjectItem;
            Project     proj    = proitem.ContainingProject;

            // Try to get default nameSpace
            string defaultNamespace = string.Empty;
            uint?  targetFramework  = 0;
            bool?  isSilverlightApp = false;

            try
            {
                defaultNamespace = proj.Properties.Item("DefaultNamespace").Value as string;
                targetFramework  = proj.Properties.Item("TargetFramework").Value as uint?;
                isSilverlightApp = proj.Properties.Item("SilverlightProject.IsSilverlightApplication").Value as bool?;
            }
            catch
            {
            }

            CodeModel codeModel = proitem.ContainingProject.CodeModel;
            string    fileName  = proitem.FileNames[0];

            try
            {
                proitem.Save(fileName);
            }
            catch (Exception)
            {
            }

            TargetFramework framework = TargetFramework.Net20;

            if (targetFramework.HasValue)
            {
                uint target = targetFramework.Value;
                switch (target)
                {
                case 196608:
                    framework = TargetFramework.Net30;
                    break;

                case 196613:
                    framework = TargetFramework.Net35;
                    break;

                case 262144:
                    framework = TargetFramework.Net40;
                    break;
                }
            }
            if (isSilverlightApp.HasValue)
            {
                if (isSilverlightApp.Value)
                {
                    framework = TargetFramework.Silverlight;
                }
            }

            var frm = new FormOption();

            frm.Init(fileName, proj.CodeModel.Language, defaultNamespace, framework);

            DialogResult result = frm.ShowDialog();

            GeneratorParams generatorParams = frm.GeneratorParams.Clone();

            generatorParams.InputFilePath = fileName;

            var gen = new GeneratorFacade(generatorParams);

            // Close file if open in IDE
            ProjectItem projElmts;
            bool        found = FindInProject(proj.ProjectItems, gen.GeneratorParams.OutputFilePath, out projElmts);

            if (found)
            {
                Window window = projElmts.Open(EnvDTE.Constants.vsViewKindCode);
                window.Close(vsSaveChanges.vsSaveChangesNo);
            }

            if (fileName.Length > 0)
            {
                if (result == DialogResult.OK)
                {
                    Result <string> generateResult = gen.Generate();
                    string          outputFileName = generateResult.Entity;

                    if (!generateResult.Success)
                    {
                        MessageBox.Show(generateResult.Messages.ToString(), "XSD2Code", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        if (!found)
                        {
                            projElmts = proitem.Collection.AddFromFile(outputFileName);
                        }

                        if (frm.OpenAfterGeneration)
                        {
                            Window window = projElmts.Open(EnvDTE.Constants.vsViewKindCode);
                            window.Activate();
                            window.SetFocus();

                            try
                            {
                                // this.applicationObjectField.DTE.ExecuteCommand("Edit.RemoveAndSort", "");
                                dte.ExecuteCommand("Edit.FormatDocument", string.Empty);
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }
            }
        }