Click here to Skip to main content
15,881,882 members
Articles / General Programming / Tools

LINQ on the Command-Line

Rate me:
Please Sign up or sign in to vote.
4.67/5 (4 votes)
4 May 2012CPOL1 min read 39.8K   330   22  
Ever want to run a Linq statement from powershell or command line?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Xml.Linq;
using System.IO;
using Microsoft.CSharp;

namespace LinqOot
{
    static class MyExtensions
    {
        public static object Dump(this object value) 
        {
            if (null == value)
                return null;
            else if (value is IEnumerable<object>)
                return (value as IEnumerable<object>).Select(v => v.Dump()).ToArray();
            else
                Console.WriteLine(value.ToString());

            return value;
        }
        public static string ToString(this IEnumerable<object> value)
        {
            return string.Join("\n", (value as IEnumerable<object>).Select(s => s.ToString()));
        }
    }

    class Program
    {
        static readonly string[] tmplApp = new string[]{
        "using System;",
        "using System.Collections.Generic;",
        "using System.Linq;",
        "using System.Xml.Linq;",
        "using System.Text;",
        "using System.IO;",
        "using System.Diagnostics;",
        "",
        "class Script{ public static object Main(string[] args){{CODE}} }",
        "",
        "public static class ScriptExtensions",
        "{",
        "    public static object Dump(this object value)",
        "    {",
        "        if (null != value)",
        "        {",
        "            if (value is IEnumerable<object>)",
        "                Console.WriteLine(string.Join(\"\\n\", (value as IEnumerable<object>).Select(s => s.Dump().ToString())));",
        "            else",
        "                Console.WriteLine(value);",
        "        }",
        "        return value;",
        "    }",
        "}"};

        static void Main(string[] args)
        {
            if (0 == args.Count())
            {
                Console.WriteLine("Expect a LINQ script file to run.");
                return;
            }

            var lins = File.ReadAllLines(args[0]);

            var isLinq = args[0].ToLower().EndsWith(".linq");
            string linqType = (isLinq) ? XDocument.Parse(lins[0]).Root.Attribute("Kind").Value : string.Empty;
            var script = string.Format(("Statements" == linqType) ? "{0}\nreturn null;" : "return {0};",
                string.Join("\n", (isLinq) ? lins.Skip(2).Where(s => !s.TrimStart().StartsWith("//")) : lins));

            Assembly asm = null;
            try
            {
                asm = CompileSource(string.Join("\n", tmplApp.Select(s => s.Replace("{CODE}", script))));
            }
            catch (Exception x)
            {
                Console.WriteLine("Failed compiling script:\n\n{0}\n\n{1}", script, x.Message);
                return;
            }

            var scrObj = asm.CreateInstance("Script");
            try
            {
                object result = scrObj.GetType().InvokeMember("Main", BindingFlags.InvokeMethod, null, scrObj, new object[] { args.Skip(1).ToArray() });
                if ("Statements" != linqType)
                    result.Dump();
            }
            catch (Exception x)
            {
                Console.WriteLine("Failed executing script:\n\n{0}\n\n{1}", script, x.Message);
            }
        }

        private static Assembly CompileSource(string sourceCode)
        {
            CodeDomProvider cpd = new CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters() { GenerateExecutable = false };
            cp.ReferencedAssemblies.AddRange(new string[] { "System.dll", "System.Xml.dll", "System.Xml.Linq.dll", "System.Core.dll", "System.Data.dll"});

            // Invoke compilation.
            CompilerResults cr = cpd.CompileAssemblyFromSource(cp, sourceCode);

            return cr.CompiledAssembly;
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer Big Company
United States United States
My professional career began as a developer fixing bugs on Microsoft Word97 and I've been fixing bad habits ever since. Now I do R&D work writing v1 line of business applications mostly in C#/.Net.

I've been an avid pilot/instructor for 13+ years, I've built two airplanes and mostly fly gliders now for fun. I commute in an all-electric 1986 BMW 325 conversion.

I'd like to get back to my academic roots of programming 3D analysis applications to organize complex systems.

Comments and Discussions