Ejemplo n.º 1
0
        private byte[] GenerateCode(BdsSoft.SharePoint.Linq.Tools.EntityGenerator.EntityGenerator gen, XmlDocument spml)
        {
            //
            // Generate code and report warnings/errors if any.
            //
            CodeCompileUnit compileUnit;

            try
            {
                compileUnit = gen.GenerateCode(spml);
            }
            catch (EntityGeneratorException ex)
            {
                if (ex.Data.Contains("messages"))
                {
                    foreach (var s in (List <ValidationEventArgs>)ex.Data["messages"])
                    {
                        this.GeneratorError(s.Severity == XmlSeverityType.Warning, 0, s.Message, (uint)s.Exception.LineNumber, (uint)s.Exception.LinePosition);
                    }
                }

                return(null);
            }

            //
            // Use CodeDOM to generate source code.
            //
            CodeDomProvider provider = GetCodeProvider();
            StringBuilder   code     = new StringBuilder();
            TextWriter      tw       = new StringWriter(code);

            provider.GenerateCodeFromCompileUnit(compileUnit, tw, null);
            tw.Flush();

            //
            // Do the right encoding to write to the target output file.
            //
            Encoding enc = Encoding.GetEncoding(tw.Encoding.WindowsCodePage);

            byte[] preamble       = enc.GetPreamble();
            int    preambleLength = preamble.Length;

            byte[] body = enc.GetBytes(code.ToString());
            Array.Resize <byte>(ref preamble, preambleLength + body.Length);
            Array.Copy(body, 0, preamble, preambleLength, body.Length);

            //
            // Return generated code.
            //
            return(preamble);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Entry point for SpMetal.
        /// </summary>
        /// <param name="args">Command-line arguments.</param>
        static void Main(string[] args)
        {
            //
            // Unhandled exception signaling.
            //
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(Error);

            //
            // Title including assembly version number.
            //
            Console.WriteLine("Bart De Smet SpMetal SharePoint List Definition Export version {0}", Assembly.GetEntryAssembly().GetName().Version);
            Console.WriteLine("Copyright (C) Bart De Smet 2007. All rights reserved.\n");

            //
            // Parse arguments.
            //
            Args a = Args.Parse(args);

            //
            // Invalid arguments: display help information and exit.
            //
            if (a == null)
            {
                ShowSyntaxInfo();
                return;
            }

            //
            // Entity generator.
            //
            EG.EntityGenerator gen = new EG.EntityGenerator(
                new EntityGeneratorArgs()
            {
                RunMode    = a.RunMode,
                Connection = new Connection()
                {
                    CustomAuthentication = a.User != null,
                    Url      = a.Url,
                    User     = a.User,
                    Password = a.Password,
                    Domain   = a.Domain
                },
                Namespace = a.Namespace,
                Language  = (a.Language == "VB" ? Language.VB : Language.CSharp)
            }
                );

            //
            // Pluralization setting.
            //
            List.AutoPluralize = a.Pluralize;

            //
            // Get SPML first.
            //
            XmlDocument spml = new XmlDocument();

            //
            // Check run mode: online or offline.
            //
            if ((a.RunMode & RunMode.Online) == RunMode.Online)
            {
                try
                {
                    spml.InnerXml = gen.GenerateSpml(a.Context, a.List).InnerXml;
                }
                catch (EntityGeneratorException ex)
                {
                    Console.WriteLine("Failed to generate SPML. " + ex.Message);
                    return;
                }
            }
            else if ((a.RunMode & RunMode.Offline) == RunMode.Offline)
            {
                try
                {
                    spml.InnerXml = File.ReadAllText(a.In);
                }
                catch (XmlException ex)
                {
                    Console.WriteLine("Invalid SPML file. " + ex.Message);
                    return;
                }
                catch (IOException ex)
                {
                    Console.WriteLine("Failed to read input file. " + ex.Message);
                    return;
                }
            }
            else
            {
                Debug.Assert(false);
            }

            //
            // Just save the SPML.
            //
            if ((a.RunMode & RunMode.Export) == RunMode.Export)
            {
                //
                // Write to output file.
                //
                try
                {
                    using (FileStream fs = File.Open(a.Xml, FileMode.Create, FileAccess.Write))
                    {
                        XmlWriterSettings settings = new XmlWriterSettings();
                        settings.Indent   = true;
                        settings.Encoding = Encoding.UTF8;
                        using (XmlWriter writer = XmlWriter.Create(fs, settings))
                        {
                            spml.WriteTo(writer);
                            Console.WriteLine("Output written to {0}.", a.Xml);
                        }
                    }
                }
                catch (UnauthorizedAccessException ex)
                {
                    Console.WriteLine("Failed to write ouput. " + ex.Message);
                    return;
                }
                catch (IOException ex)
                {
                    Console.WriteLine("Failed to write ouput. " + ex.Message);
                    return;
                }
            }
            //
            // Create and save entity code.
            //
            else if ((a.RunMode & RunMode.CodeGen) == RunMode.CodeGen)
            {
                //
                // Generate code in the appropriate language.
                //
                CodeCompileUnit compileUnit;
                try
                {
                    compileUnit = gen.GenerateCode(spml);
                }
                catch (EntityGeneratorException ex)
                {
                    Console.WriteLine(ex.Message);
                    if (ex.Data.Contains("messages"))
                    {
                        Console.WriteLine("\nSchema validation messages:");
                        foreach (var s in (List <ValidationEventArgs>)ex.Data["messages"])
                        {
                            Console.WriteLine("- [{3}] {0} ({1},{2})", s.Message, s.Exception.LineNumber, s.Exception.LinePosition, s.Severity.ToString().ToUpper());
                        }
                    }
                    return;
                }
                CodeDomProvider cdp  = CodeDomProvider.CreateProvider(a.Language);
                StringBuilder   code = new StringBuilder();
                TextWriter      tw   = new StringWriter(code);
                cdp.GenerateCodeFromCompileUnit(compileUnit, tw, null);

                //
                // Infer file name from list name if not specified on the command-line (v0.2.0.0).
                //
                if (a.Code == null || a.Code.Length == 0)
                {
                    string file;

                    if (!string.IsNullOrEmpty(a.Context))
                    {
                        file = a.Context + "SharePointDataContext";
                    }
                    else
                    {
                        XmlAttribute ctx = spml["SharePointDataContext"].Attributes["Name"];
                        if (ctx != null && !string.IsNullOrEmpty(ctx.Value))
                        {
                            file = ctx.Value + "SharePointDataContext";
                        }
                        else if (!string.IsNullOrEmpty(a.List))
                        {
                            file = a.List; //TODO: non-GUID file name
                        }
                        else
                        {
                            file = Path.GetRandomFileName();
                        }
                    }

                    file += (a.Language == "CS" ? ".cs" : ".vb");
                    foreach (char c in Path.GetInvalidFileNameChars())
                    {
                        file = file.Replace(c.ToString(), "");
                    }
                    a.Code = file;
                }

                //
                // Write to output file.
                //
                try
                {
                    using (StreamWriter sw = File.CreateText(a.Code))
                    {
                        sw.WriteLine(code.ToString());
                        Console.WriteLine("Output written to {0}.", a.Code);
                    }
                }
                catch (UnauthorizedAccessException ex)
                {
                    Console.WriteLine("Failed to write ouput. " + ex.Message);
                    return;
                }
                catch (IOException ex)
                {
                    Console.WriteLine("Failed to write ouput. " + ex.Message);
                    return;
                }
            }
            else
            {
                Debug.Assert(false);
            }
        }