예제 #1
0
        private static int restartAsAdmin(XS.ScriptContext context, string[] args, bool hidden)
        {
            context.WriteLine(XS.OutputType.Info, "** Administrative privileges are required to run this script.\n** Please confirm to continue.");

            int n = AppDomainLoader.RunWithElevatedContext(
                delegate(XS.ScriptContext ctx)
            {
                XS.ScriptContextScope.DefaultContext = ctx;
                try
                {
                    return(MainWithContext(ctx, args));
                }
                finally
                {
                    XS.ScriptContextScope.DefaultContext = null;
                }
            }, hidden);

            if (n == -1)
            {
                throw new XS.ScriptRuntimeException("An error occured while granting administrative privileges.");
            }
            if (n != 0)
            {
                throw new XS.ScriptRuntimeException("An error occured during script execution.");
            }
            return(0);
        }
예제 #2
0
 public int OnContextReady(XS.ScriptContext context)
 {
     if (Callback != null)
     {
         return(Callback(context));
     }
     return(-1);
 }
예제 #3
0
 private static void resetAbort(XS.ScriptContext context)
 {
     if (Thread.CurrentThread.ThreadState == System.Threading.ThreadState.AbortRequested)
     {
         Thread.ResetAbort();
     }
     context.ResetAbort();
 }
예제 #4
0
        public static string GetLogo(ScriptContext context)
        {
            var titleAttr=(AssemblyTitleAttribute[])Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute),true);
            var cpr = (AssemblyCopyrightAttribute[])Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), true);
            var cn=(AssemblyCompanyAttribute[])Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), true);
            string tt = (titleAttr.Length>0)?titleAttr[0].Title:"XSharper";

            return tt + " v." + context.CoreVersion + " "+
                ((cn.Length > 0) ? cn[0].Company : "DeltaX Inc.") +" "+
                ((cpr.Length > 0) ? cpr[0].Copyright : "(c) 2006-2013");
        }
예제 #5
0
        private static Script createEmptyScript(ScriptContext context, string id)
        {
            Script s = context.CreateNewScript(Process.GetCurrentProcess().MainModule.FileName);
            s.Id = id;
            s.EngineVersion = context.CoreVersion.ToString();

            if (context.Compiler.DefaultNETVersion>new Version(3,5))
            {
                if (Environment.Version.Major >= 4)
                    s.NetVersion = "4.0.30319";
                else
                    s.NetVersion = "3.5";
            }
            else
                s.NetVersion = context.Compiler.DefaultNETVersion.ToString();

            return s;
        }
예제 #6
0
        private static List<IScriptAction> getCommandlineReferences(ScriptContext context)
        {
            List<IScriptAction> preScript = new List<IScriptAction>();
            if (context.IsSet(xs.@ref))
            {
                foreach (var param in context.GetStr(xs.@ref ?? string.Empty).Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
                {
                    string r = param.Trim();
                    bool withTypes = false;
                    bool file = false;

                    if (r.StartsWith("#", StringComparison.Ordinal))
                    {
                        withTypes = true;
                        r = r.Substring(1);
                    }
                    if (r.EndsWith(".dll",StringComparison.OrdinalIgnoreCase))
                        file = true;

                    if (!string.IsNullOrEmpty(r))
                    {
                        Reference rr = null;
                        bool addUsing = false;
                        if (r.StartsWith("@", StringComparison.Ordinal))
                        {
                            r = r.Substring(1);
                            addUsing = true;
                        }
                        if (file)
                        {
                            rr = new Reference {From = r, WithTypes = withTypes, Transform = TransformRules.None, AddUsing = addUsing};
                            preScript.Add(new Embed { From = r, IsAssembly = true, Transform = TransformRules.None });
                        }
                        else
                            rr = new Reference { Name = r, WithTypes = withTypes, Transform = TransformRules.None, AddUsing = addUsing };
                        if (withTypes)
                            context.AddAssembly(rr.AddReference(context, true),true);
                        preScript.Add(rr);
                    }
                }
            }
            return preScript;
        }
예제 #7
0
        static int Main(string[] args)
        {
            ScriptContext context = new ScriptContext();
            using (ConsoleWithColors cout = new ConsoleWithColors(Environment.GetEnvironmentVariable("XSH_COLORS")))
            using (ConsoleRedirector redir = new ConsoleRedirector(context))
            using (CtrlCInterceptor ctrl = new CtrlCInterceptor())
            {
                context.Output += cout.OnOutput;
                ctrl.Output = context.Error;
                ctrl.Abort += delegate { context.Abort(); };
                cout.DebugMode = true;

                // context.Progress=console.OnOutputProgress;
                int exitCode = 0;
                try
                {
                    var script = new Generated.$safeprojectname$().Script;
                    ctrl.IgnoreCtrlC = script.IgnoreCtrlC;
                    ctrl.AbortDelay = Utils.ToTimeSpan(script.AbortDelay) ?? ctrl.AbortDelay;
                    ctrl.ExitDelay = Utils.ToTimeSpan(script.ExitDelay) ?? ctrl.ExitDelay;

                    object o = context.ExecuteScript(script, args);
                    if (o != null)
                        exitCode = Utils.To<int>(o);
                }
                catch (ScriptTerminateException te)
                {
                    exitCode = te.ExitCode;
                    if (te.InnerException != null)
                        context.WriteException(te.InnerException);
                }
                catch (Exception e)
                {
                    context.WriteException(e);
                    exitCode = -1;
                }
                return exitCode;
            }
        }
예제 #8
0
        private static void setOutputOptions(XS.ScriptContext context, XS.ConsoleWithColors cout)
        {
            // Set output level
            context.Verbose     = context.GetBool(xs.verbose, false);
            cout.DebugMode      = context.GetBool(xs.debug, false) || context.Verbose || context.GetBool(xs.debugc, false) || context.Verbose;;
            cout.DebugToConsole = context.GetBool(xs.debugc, false);
            if (cout.DebugMode)
            {
                context.MinOutputType = XS.OutputType.Debug;
            }
            if (context.GetBool(xs.quiet, false))
            {
                context.MinOutputType = XS.OutputType.Out;
            }

            // Fill console properties
            cout.LogFile = context.GetString(xs.log, null);
            if (context.GetBool(xs.nocolors, false))
            {
                cout.UseColors = false;
            }
        }
예제 #9
0
파일: Exec.cs 프로젝트: xsharper/xsharper
 /// Build command line
 public static string GetCommandLine(ScriptContext context, IEnumerable<ShellArg> parameters)
 {
     return string.Join(" ",getArgs(context, parameters, true));
 }
예제 #10
0
        private static int upgrade(ScriptContext cout)
        {
            string procName = Process.GetCurrentProcess().MainModule.FileName;

            string tmp = null;
            try
            {
                cout.WriteLine(OutputType.Bold, HelpHelper.GetLogo(cout));
                cout.WriteLine(OutputType.Info, "Currently executing " + procName);
                if (BitConverter.ToString(Assembly.GetExecutingAssembly().GetName().GetPublicKeyToken()).Length==0)
                {
                    cout.Write(OutputType.Error, "This XSharper build is not digitally signed and cannot be upgraded automatically. Please upgrade manually...");
                    return -1;
                }

                // Find out if upgrade is due
                var current = Assembly.GetExecutingAssembly().GetName().Version;
                cout.Write(OutputType.Info, "Checking the latest XSharper version...");

                using (var wc = new WebClientEx())
                {
                    wc.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Revalidate);

                    var verBytes = wc.DownloadData("http://www.xsharper.com/xsharper-version.txt");
                    var latest = new Version(Encoding.ASCII.GetString(verBytes));
                    cout.WriteLine(OutputType.Info, string.Empty);
                    cout.WriteLine(OutputType.Info, "The latest available version is " + latest);
                    if (latest <= current)
                    {
                        cout.WriteLine("Installed XSharper version is up to date.");
                        return 0;
                    }

                    cout.WriteLine(OutputType.Info, "Downloading the latest XSharper binary...");
                    byte[] exe = wc.DownloadData(Environment.Version.Major>=4?
                        "http://www.xsharper.com/xsharper4.exe" :
                        "http://www.xsharper.com/xsharper.exe");
                    Assembly a=Assembly.Load(exe);

                    tmp = Utils.BackslashAdd(Path.GetTempPath()) + "xsharper" + latest + ".exe";
                    File.WriteAllBytes(tmp, exe);

                    // Verify signature
                    cout.WriteLine(OutputType.Info, "Verifying digital signature...");

                    if (BitConverter.ToString(a.GetName().GetPublicKeyToken()) != BitConverter.ToString(Assembly.GetExecutingAssembly().GetName().GetPublicKeyToken()))
                    {
                        cout.Write(OutputType.Error, "Failed. The downloaded XSharper binary is signed with a different key. Please upgrade manually.");
                        return -1;
                    }
                    cout.WriteLine(OutputType.Info, "Done.");

                    byte wasVerified = 0;
                    if (!StrongNameSignatureVerificationEx(tmp, 1, ref wasVerified))
                    {
                        cout.Write(OutputType.Error, "Downloaded XSharper binary has invalid signature. Upgrade is aborted.");
                        return -1;
                    }

                    cout.WriteLine(OutputType.Info, string.Empty);
                }

                // Run it
                cout.WriteLine(OutputType.Info, "Starting update...");
                var pi = new ProcessStartInfo
                {
                    WorkingDirectory = Environment.CurrentDirectory,
                    FileName = tmp,
                    Arguments = xs.updateStage.Replace("xs.", "//") + " overwrite " + Process.GetCurrentProcess().Id + " " + Utils.QuoteArg(procName),
                    UseShellExecute = true,
                };
                Process pr = Process.Start(pi);
                if (pr != null)
                    pr.WaitForExit();

                // If the script is successful, this process will be killed and this line never executed
                throw new ScriptRuntimeException("Failed to start upgrade");
            }
            catch (Exception e)
            {
                cout.WriteLine(OutputType.Error, e.Message);
                cout.WriteLine(OutputType.Error, "Software update is cancelled.");
                return -1;
            }
            finally
            {
                if (tmp != null && File.Exists(tmp))
                    File.Delete(tmp);
            }
        }
예제 #11
0
 // Calling with local scriptcontext
 public static int Main2(string[] args)
 {
     XS.ScriptContext context = new XS.ScriptContext(AppDomainLoader.ResourceAssembly);
     return(MainWithContext(context, args));
 }
예제 #12
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="context">Script context, where to forward all output</param>
 /// <param name="outputType">Classify all output as this output type</param>
 public ContextWriter(ScriptContext context, OutputType outputType)
 {
     _context = context;
     _outputType = outputType;
 }
예제 #13
0
 private static bool isCodeGeneration(ScriptContext context)
 {
     return (context.IsSet(xs.genexe) ||
             context.IsSet(xs.genwinexe) ||
             context.IsSet(xs.genlibrary) ||
             context.IsSet(xs.gencs) ||
             context.IsSet(xs.genxsd) ||
             context.IsSet(xs.save));
 }
예제 #14
0
        private static Script getInlineScript(ScriptContext context, List<string> filteredArgs)
        {
            string name = null;
            string vn = null;
            if (context.IsSet(xs.execRest))
            {
                name = "//";
                vn = xs.execRest;
            }
            else if (context.IsSet(xs.execRestD))
            {
                name = "//#";
                vn = xs.execRestD;
            }
            else if (context.IsSet(xs.execRestP))
            {
                name = "//p";
                vn = xs.execRestP;
            }
            if (name!=null)
            {
                string c = Environment.CommandLine;
                int n = c.IndexOf("/" + name, StringComparison.OrdinalIgnoreCase);
                if (n == -1)
                    throw new ScriptRuntimeException("Invalid command line");
                string s = c.Substring(n + name.Length + 1).Trim();
                if (s.Length>0 && s[0]=='"')
                {
                    var args=context.GetArrayT<string>(vn);
                    s = args[0];
                    filteredArgs.Clear();
                    for (int i = 1; i < args.Length;++i)
                        filteredArgs.Add(args[i]);
                }
                if (context.IsSet(xs.execRestD) && s.Length > 0 && s[0] == '?')
                    s = s.Substring(1);
                if (context.IsSet(xs.execRestD))
                    return execGenerator(context, s, "c.Dump(", ")");
                if (context.IsSet(xs.execRestP))
                    return execGenerator(context, s, "c.WriteLine(", ")");
                return execGenerator(context, s, null, null);
            }
            if (context.IsSet(xs.download))
                return genDownload(context, filteredArgs);
            if (context.IsSet(xs.zip))
                return genZip(context, filteredArgs);
            if (context.IsSet(xs.unzip))
                return genUnzip(context, filteredArgs);
            if (context.GetBool(xs.version, false))
                return genVersion(context);

            return null;
        }
예제 #15
0
 /// Return value transformed
 public string GetTransformedValue(ScriptContext ctx)
 {
     return ctx.TransformStr(Value, Transform);
 }
예제 #16
0
 /// Get description of the command line argument by choosing between <see cref="Description"/> and <see cref="Var"/>
 public string GetDescription(ScriptContext ctx)
 {
     if (Description == null)
         return Var;
     return ctx.TransformStr(Description,Transform);
 }
예제 #17
0
        private static int createRemotingScriptContext(string[] args)
        {
            progress("remoteClient: createRemotingScriptContext");
            for (int i = 0; i < args.Length;++i )
                progress("remoteClient: arg"+i+": ["+args[i]+"]");
            try
            {
                progress("remoteClient: Setting up ipc client");
                Random r=new Random();
                registerChannel(args[1], args[1] + ":"+r.Next(9000,15000));
                if (!string.IsNullOrEmpty(args[2]))
                    BaseDirectory = args[2];
                RemotingCallback callback = (RemotingCallback)Activator.GetObject(typeof(RemotingCallback), "ipc://" + args[1] + "/RemotingCallback");

                progress("remoteClient: attaching console");
                uint pid = uint.Parse(args[3]);
                if (pid != 0)
                {
                    FreeConsole();
                    bool b=AttachConsole(pid);
                    if (b)
                        progress("remoteClient: attaching console was successful");
                    else
                        progress("remoteClient: attaching console failed");
                }
                progress("remoteClient: ipc setup. About to instantiate context");
                XS.ScriptContext sc = new XS.ScriptContext(ResourceAssembly);
                if (sc.IsAdministrator)
                {
                    progress(sc.GetType().FullName + " instantiated");

                    using (XS.ConsoleCtrl ctrl = new XS.ConsoleCtrl())
                    {
                        // Ignore Ctrl+C
                        ctrl.ControlEvent += delegate(object sender, XS.ConsoleCtrlEventArgs e)
                            {
                                progress("remoteClient: Ctrl+C received");
                                try
                                {
                                    sc.Abort();
                                }
                                catch
                                {

                                }
                            };
                        return callback.OnContextReady(sc);
                    }
                }
                progress("remoteClient: Administrator privileges required!");
            }
            catch (Exception e)
            {
                progress("remoteClient: " + e);
                throw;
            }

            return -1;
        }
예제 #18
0
 // Calling with local scriptcontext
 public static int Main2(string[] args)
 {
     XS.ScriptContext context = new XS.ScriptContext(AppDomainLoader.ResourceAssembly);
     return MainWithContext(context, args);
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="context">Current script context</param>
 /// <param name="inner">Inner exception</param>
 public ScriptExceptionWithStackTrace(ScriptContext context, Exception inner)
     : base(generateMessage(context.CallStack),inner)
 {
     Details = "  "+context.CallStack.Format("\n  ", "", false, false);
 }
예제 #20
0
파일: Exec.cs 프로젝트: xsharper/xsharper
        static string[] getArgs(ScriptContext context, IEnumerable<ShellArg> parameters, bool quoted)
        {
            List<string> p = new List<string>();
            foreach (ShellArg parameter in parameters)
            {
                string s = context.TransformStr(parameter.Switch, parameter.Transform);
                if (!string.IsNullOrEmpty(s))
                    p.Add(s);

                object o = context.Transform(parameter.Value, parameter.Transform);
                var arr = o as IEnumerable;
                if (arr != null && !(o is string))
                {
                    foreach (var obj in arr)
                        if (quoted)
                            p.Add(context.TransformStr(Utils.To<string>(obj), TransformRules.QuoteArg));
                        else
                            p.Add(Utils.To<string>(obj));
                }
                else if (o!=null)
                {
                    if (quoted)
                        p.Add(context.TransformStr(Utils.To<string>(o), TransformRules.QuoteArg));
                    else
                        p.Add(Utils.To<string>(o));
                }
            }
            return p.ToArray();
        }
예제 #21
0
파일: Exec.cs 프로젝트: xsharper/xsharper
 /// Create list of command line parameters, transforming and separating elements as appropriate
 public static string[] GetParams(ScriptContext context, IEnumerable<ShellArg> parameters)
 {
     return getArgs(context, parameters, false);
 }
예제 #22
0
 /// Constructor that saves the current context and sets the provided context as current
 public ScriptContextScope(ScriptContext ctx)
 {
     _old = s_current;
     _set = ctx;
     s_current = ctx;
 }
예제 #23
0
        private static Script genZip(ScriptContext context, List<string> filteredArgs)
        {
            Script script;
            script = createEmptyScript(context,"xsharper //zip");
            script.Id = "zip";
            filteredArgs.AddRange(context.GetStringArray(xs.zip));
            script.Usage.Options = UsageOptions.IfHelp | UsageOptions.IfNoArguments | UsageOptions.UsageLine | UsageOptions.AutoSuffix;
            script.Parameters.Add(new CommandLineParameter("zip", CommandLineValueCount.Single, null, null) { Required = true, Description = "archive.zip", Value = "Zip archive to create" });
            script.Parameters.Add(new CommandLineParameter("source", CommandLineValueCount.Single, ".",null) { Description = "directory", Value = "Directory to compress" });
            script.Parameters.Add(new CommandLineParameter("filter", CommandLineValueCount.Single, "*.*", null) { Description = "filter", Value = "File wildcard" });
            script.Parameters.Add(new CommandLineParameter("dirfilter", CommandLineValueCount.Single, "*", null) { Description = "directory-filter", Value = "Directory wildcard" });
            script.Parameters.Add(new CommandLineParameter(null,"zipTime", CommandLineValueCount.Single, "fileTime", null) { Synonyms="zt", Value = "What time to store in zip ( fileTime/utcFileTime/now/utcNow )" });
            script.Parameters.Add(new CommandLineParameter(null,"password", CommandLineValueCount.Single, null, null) { Synonyms = "p", Value = "Archive password" });
            script.Parameters.Add(new CommandLineParameter(null,"recursive", CommandLineValueCount.None, "0", "1") { Synonyms = "r", Value = "Recursive" });
            script.Parameters.Add(new CommandLineParameter(null, "ignore", CommandLineValueCount.None, "0", "1") { Synonyms = "i", Value = "Ignore errors" });
            script.Parameters.Add(new CommandLineParameter(null,"emptyDirectories", CommandLineValueCount.None, "0", "1") { Value = "Include empty directories" });
            script.Parameters.Add(new CommandLineParameter(null, "hidden", CommandLineValueCount.None, "0", "1") { Synonyms = "i", Value = "Extract hidden files" });

            script.Add(new PathOperation {Value = "${zip}", Operation = PathOperationType.GetFullPath, OutTo = "zip"});
            script.Add(new If(new Set( "zip", "${=Path.ChangeExtension(${zip},'.zip')}"))
                {
                    IsEmpty = "${=Path.GetExtension(${zip})}"
                });

            script.Add(new SetAttr("z", "zipTime", "${zipTime}"));
            script.Add(new SetAttr("z", "recursive", "${recursive}"));
            script.Add(new SetAttr("z", "hidden", "${hidden}"));
            script.Add(new SetAttr("z", "emptyDirectories", "${emptyDirectories}"));
            script.Add(new Print("Compressing ${source} => ${zip} ... "));
            Zip z=new Zip {
                              Id="z",
                              From = "${source}",
                              To = "${zip}",
                              Transform = TransformRules.Expand,
                              Recursive = true,
                              Syntax = FilterSyntax.Wildcard,
                              Filter = "${filter}",
                              DirectoryFilter = "${dirfilter}",
                              Password = "******"
                          };
            If oif = new If(new Print { Value = "  ${from}", OutTo = "^info" })
                        {
                             IsTrue = "${=$.IsFile}"
                         };

            If f = new If(new[] { new Print("Failed: '${}' : ${=c.CurrentException.Message}") { OutTo = "^error" } });
            f.IsTrue = "${ignore}";
            f.AddElse(new Throw());
            z.AddCatch(f);

            z.Add(oif);
            script.Add(z);
            script.Add(new Print { Value = "Completed" });
            return script;
        }
예제 #24
0
        /// <summary>
        /// Generate usage header
        /// </summary>
        /// <param name="context">Script context</param>
        /// <param name="appendValue">true, if Value should be appended to the generated text</param>
        /// <returns></returns>
        public string GenerateInfo(ScriptContext context , bool appendValue)
        {
            var title=context.TransformStr(Title, Transform);
            var value = context.TransformStr(Value, Transform);
            var copyright = context.TransformStr(Copyright, Transform);
            var version = context.TransformStr(Version, Transform);

            var sb=new StringBuilder();
            if (!string.IsNullOrEmpty(title))
            {
                sb.Append(title);
                if (!string.IsNullOrEmpty(version))
                {
                    sb.Append(" version ");
                    sb.Append(version);
                }
                if (!string.IsNullOrEmpty(copyright))
                {
                    if (sb.Length > 60)
                        sb.AppendLine();

                    sb.Append("  ");
                    sb.Append(copyright);
                }
            }
            if (appendValue && !string.IsNullOrEmpty(value))
            {
                if (sb.Length > 0)
                {
                    sb.AppendLine();
                    sb.AppendLine();
                }
                sb.Append(value);
            }
            return sb.ToString();
        }
예제 #25
0
        private static Script getSampleScript(ScriptContext context)
        {
            Script script = new Script();
            script.Id = "WAIT";
            script.VersionInfo.Title = "WAIT";
            script.VersionInfo.Value = "(Generated sample script)";
            script.EngineVersion = context.CoreVersion.ToString();
            script.Parameters.Add(
                new CommandLineParameter { Default = "2000", Value = "Number of seconds to wait", Description = "seconds", Switch = "seconds", Count = CommandLineValueCount.Single }
                );
            script.Parameters.Add(
                new CommandLineParameter { Default = "0", Value = "Display this message", Switch = "help", Synonyms = "?;helpme", Unspecified = "true" }
                );

            script.Add(new Code { Value = "Context.WriteLine(\"Hello, world!\");" });
            script.Add(new Code { Value = "Context.WriteLine(\"This script will be waiting for {0} seconds.\",c[\"seconds\"]);" });
            Timer timer = new Timer { OutTo = "execTime", Format = TimerFormat.TimeSpan };
            timer.Add(new Sleep { Timeout = "${seconds}" });
            script.AddTry(timer);
            script.AddTry(new Print { Value="Execution took ${execTime}"});

            script.AddTry(new Throw { Value = "Test error" });
            script.AddTry(new Print { Value = "This will not be printed" });
            script.AddCatch(new Print { Value = "Catched exception: ${=c.CurrentException.Message}" });
            script.AddFinally(new Print { Value = "Clean up part" });
            return script;
        }
예제 #26
0
        private static Script execGenerator(ScriptContext context, string c, string prefix, string suffix)
        {
            Script script = createEmptyScript(context,"generated");
            if (context.Compiler.DefaultNETVersion>=new Version(3,5))
            {
                // Yeah, I know it's deprecated, and it's best to use full assembly names, but
                // but I don't really want to scan GAC myself
            #pragma warning disable 618
               context.AddAssembly(Assembly.LoadWithPartialName("System.Xml.Linq"),false);
               context.AddAssembly(Assembly.LoadWithPartialName("System.Core"),false);
            #pragma warning restore 618
            }
            script.Add(new Rem { Text = "----- Generated from command line -------"+Environment.NewLine+"\t"+ c + Environment.NewLine+"\t ------------"});
            script.Parameters.Add(new CommandLineParameter("arg", CommandLineValueCount.Multiple) {Last = true, Default = "",Required = false});
            script.UnknownSwitches = true;

            c = c.Trim();
            if (c.StartsWith("\"", StringComparison.Ordinal) && c.EndsWith("\"", StringComparison.Ordinal))
                c = c.Substring(1, c.Length - 2);
            if (c == "-")
                c = Console.In.ReadToEnd();
            if (c.StartsWith("="))
            {
                prefix = "=" + prefix;
                c = "${=" + c.Substring(1) + "}";
            }
            if (prefix!=null || suffix!=null)
                c = prefix + Environment.NewLine + c + Environment.NewLine + suffix;
            c = c.Replace("`", "\"");

            AppDomainLoader.progress("Read script begin");
            using (new ScriptContextScope(context))
                script.Load(c);
            AppDomainLoader.progress("Read script end");
            return script;
        }
예제 #27
0
        private static void doCodeGeneration(ScriptContext context, Script script)
        {
            if (!isCodeGeneration(context))
                return;

            context.Compiler.AddReference(null,typeof(System.Runtime.Remoting.Channels.Ipc.IpcChannel).Assembly.FullName,false,false,null);

            if (context.IsSet(xs.save) && script != null)
            {
                context.WriteLine(OutputType.Info, string.Format("Saving script to {0} ...", context[xs.save]));
                using (new ScriptContextScope(context))
                    script.Save(context.GetString(xs.save));
                context.WriteLine(OutputType.Info, string.Format("Script file {0} saved...", context[xs.save]));
            }

            if (context.IsSet(xs.genxsd))
            {
                context.WriteLine(OutputType.Info, string.Format("Generating XML schema  ..."));

                XmlSchema x = generateSchema(context);
                string sf = context.GetString(xs.genxsd);
                sf=Path.GetFullPath((sf == "*") ? x.Id + ".xsd" : sf);
                using (StreamWriter target = new StreamWriter(sf, false))
                    x.Write(target);

                context.WriteLine(OutputType.Info, string.Format("XML schema saved to {0} ...", sf));
            }

            // Generate source code
            StringWriter source = new StringWriter();
            string entryPoint = null;
            if (script != null && (context.IsSet(xs.genlibrary) || context.IsSet(xs.genexe) || context.IsSet(xs.genwinexe) || context.IsSet(xs.gencs)))
            {
                context.WriteLine(OutputType.Info, "Generating C# source code...");
                SharpCodeGenerator codeGenerator = new SharpCodeGenerator(context.Compiler);

                if (context.IsSet(xs.@namespace))
                    codeGenerator.Namespace = context.GetString(xs.@namespace);

                string baseName = Path.GetFileNameWithoutExtension(script.Location).ToLower();
                if (script.Id!=null)
                    baseName = script.Id;
                baseName = Utils.FixFilename(baseName);

                if (context.IsSet(xs.@class))
                    codeGenerator.Class = context.GetString(xs.@class);
                else
                {
                    string cl;
                    cl = baseName;
                    if (char.IsDigit(cl[0]))
                        cl = "C" + cl;
                    if (!char.IsUpper(cl[0]))
                        cl = cl.Substring(0, 1).ToUpperInvariant() + cl.Substring(1);
                    cl = SharpCodeGenerator.ToValidName(cl);
                    if (cl == "Script" || cl == "Run")
                        cl = "C" + cl;
                    codeGenerator.Class = cl;
                }

                string pref = string.Empty;
                if (!string.IsNullOrEmpty(context.CodeOutputDirectory))
                    pref = Path.Combine(context.CodeOutputDirectory, "bin\\Debug\\");
                if (context.IsSet(xs.genexe) && context.GetString(xs.genexe) == "*")
                    context[xs.genexe] = pref+baseName + ".exe";
                if (context.IsSet(xs.genwinexe) && context.GetString(xs.genwinexe) == "*")
                    context[xs.genwinexe] = pref + baseName + ".exe";
                if (context.IsSet(xs.genlibrary) && context.GetString(xs.genlibrary) == "*")
                    context[xs.genlibrary] = pref + baseName + ".dll";
                if (context.IsSet(xs.gencs) && context.GetString(xs.gencs) == "*")
                    context[xs.gencs] = baseName + ".cs";

                GeneratorOptions options = GeneratorOptions.None;
                if (context.IsSet(xs.genexe))
                    options |= GeneratorOptions.IncludeSource | GeneratorOptions.ForExe | GeneratorOptions.CreateMain;
                if (context.IsSet(xs.genwinexe))
                    options |= GeneratorOptions.IncludeSource | GeneratorOptions.ForExe | GeneratorOptions.CreateMain | GeneratorOptions.WinExe;
                if (context.IsSet(xs.genlibrary))
                    options |= GeneratorOptions.IncludeSource | GeneratorOptions.ForExe;
                if (context.GetBool(xs.main, false))
                    options |= GeneratorOptions.CreateMain;
                if (context.GetBool(xs.forcenet20, false))
                    options |= GeneratorOptions.ForceNet20;
                if (context.CodeOutputDirectory == null && !context.IsSet(xs.gencs))
                    options |= GeneratorOptions.ForceNet20; // this is a bit faster
                if (context.GetBool(xs.noSrc, false))
                    options &= ~GeneratorOptions.IncludeSource;

                codeGenerator.Generate(context, source, script, options);
                if (context.IsSet(xs.genexe) || context.IsSet(xs.genwinexe))
                    entryPoint = codeGenerator.Namespace + "." + codeGenerator.Class + "Program";
            }

            // Save it to disk, if necessary
            string code = source.GetStringBuilder().ToString();
            if (script != null && context.IsSet(xs.gencs))
            {
                using (StreamWriter sourceDisk = new StreamWriter(context.GetString(xs.gencs), false))
                {
                    sourceDisk.Write(code);
                }
                context.WriteLine(OutputType.Info, string.Format("C# source code saved to {0} ...", context[xs.gencs]));

            }

            // Load the other part from resources
            if (script != null && (context.IsSet(xs.genexe) || context.IsSet(xs.genwinexe) || context.IsSet(xs.genlibrary)))
            {
                CompiledOutputType outType;
                string e;
                if (context.IsSet(xs.genexe))
                {
                    e = context.GetString(xs.genexe);
                    outType = CompiledOutputType.ConsoleExe;
                }
                else if (context.IsSet(xs.genwinexe))
                {
                    e = context.GetString(xs.genwinexe);
                    outType = CompiledOutputType.WindowsExe;
                }
                else
                {
                    e = context.GetString(xs.genlibrary);
                    outType = CompiledOutputType.Library;
                }

                context.WriteLine(OutputType.Info, string.Format("Compiling {0}...", e));

                var copt = new CompileOptions
                    {
                        ExtraOptions = context.GetString(xs.compilerOptions, null),
                        CodeOutputDirectory=context.CodeOutputDirectory,
                        StreamProvider=context.FindResourceMemoryStream,
                        FilesToEmbed = context.GetFilesToEmbed(),
                        EntryPoint=entryPoint,
                    };
                if (context.IsSet(xs.genexe) || context.IsSet(xs.genwinexe))
                {
                    if (script.RequireAdmin!=RequireAdminMode.User)
                    {
                        copt.Compiled = AppDomainLoader.TryLoadResourceStream(@"Manifests.requireAdministrator.res").ToArray();
                        copt.Manifest = AppDomainLoader.TryLoadResourceStream(@"Manifests.requireAdministrator.manifest").ToArray();
                    }
                    else
                    {
                        copt.Compiled = AppDomainLoader.TryLoadResourceStream(@"Manifests.asInvoker.res").ToArray();
                        copt.Manifest = AppDomainLoader.TryLoadResourceStream(@"Manifests.asInvoker.manifest").ToArray();
                    }
                    if (context.IsSet(xs.icon))
                        copt.Icon = context.ReadBytes(context.GetStr(xs.icon));
                    else
                        copt.Icon = AppDomainLoader.TryLoadResourceStream(@"Source.xsh.ico").ToArray();
                }

                // If we're building .EXE, add a reference to ZipLib. We don't want to do it
                // unnecessarily to save time, and also allow XSharper.Core use w/o ZipLib, so the reference is added only if it's loaded

                foreach (var ass in AppDomain.CurrentDomain.GetAssemblies())
                    if (ass.FullName != null && ass.FullName.Contains("ICSharpCode.SharpZipLib"))
                    {
                        context.Compiler.AddReference(null, ass.FullName, true, false,null);
                        break;
                    }

                context.Compiler.Compile(outType,code,e,copt);
                context.WriteLine(OutputType.Info, string.Format("Executable saved to {0} ...", e));
            }
        }
예제 #28
0
        private static void genDemoConfig(ConsoleWithColors consoleWithColors, ScriptContext context)
        {
            Script script = getSampleScript(context);
            if (context.IsSet(xs.gensample))
            {
                using (new ScriptContextScope(context))
                    script.Save(context.GetString(xs.gensample));
                consoleWithColors.WriteLine(OutputType.Info, string.Format("{0} created.", context[xs.gensample]));
            }

            if (!context.IsSet(xs.genconfig))
                return;
            string path = context.GetString(xs.genconfig);
            using (XmlTextWriter tw = new XmlTextWriter(path, Encoding.UTF8))
            {
                tw.Formatting = Formatting.Indented;
                tw.WriteStartDocument();
                tw.WriteStartElement("configuration");
                tw.WriteStartElement("configSections");
                tw.WriteStartElement("section");
                tw.WriteAttributeString("name", "xsharper");
                tw.WriteAttributeString("type", typeof(ScriptSectionHandler).FullName + "," + typeof(ScriptSectionHandler).Assembly.GetName().Name);
                tw.WriteEndElement();
                tw.WriteEndElement();
                tw.WriteComment("  Connection strings  ");
                tw.WriteStartElement("connectionStrings");
                tw.WriteStartElement("add");
                tw.WriteAttributeString("name", "mydb");
                tw.WriteAttributeString("connectionString", @"Data Source=localhost\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=True;");
                tw.WriteEndElement();
                tw.WriteEndElement();
                tw.WriteComment(" ** XSharper script ** ");
                using (new ScriptContextScope(context))
                    script.Save(tw);
                tw.WriteEndElement();
                tw.WriteEndDocument();
            }
            consoleWithColors.WriteLine(OutputType.Info, string.Format("{0} created.", path));
        }
예제 #29
0
        private static int createRemotingScriptContext(string[] args)
        {
            progress("remoteClient: createRemotingScriptContext");
            for (int i = 0; i < args.Length; ++i)
            {
                progress("remoteClient: arg" + i + ": [" + args[i] + "]");
            }
            try
            {
                progress("remoteClient: Setting up ipc client");
                Random r = new Random();
                registerChannel(args[1], args[1] + ":" + r.Next(9000, 15000));
                if (!string.IsNullOrEmpty(args[2]))
                {
                    BaseDirectory = args[2];
                }
                RemotingCallback callback = (RemotingCallback)Activator.GetObject(typeof(RemotingCallback), "ipc://" + args[1] + "/RemotingCallback");

                progress("remoteClient: attaching console");
                uint pid = uint.Parse(args[3]);
                if (pid != 0)
                {
                    FreeConsole();
                    bool b = AttachConsole(pid);
                    if (b)
                    {
                        progress("remoteClient: attaching console was successful");
                    }
                    else
                    {
                        progress("remoteClient: attaching console failed");
                    }
                }
                progress("remoteClient: ipc setup. About to instantiate context");
                XS.ScriptContext sc = new XS.ScriptContext(ResourceAssembly);
                if (sc.IsAdministrator)
                {
                    progress(sc.GetType().FullName + " instantiated");

                    using (XS.ConsoleCtrl ctrl = new XS.ConsoleCtrl())
                    {
                        // Ignore Ctrl+C
                        ctrl.ControlEvent += delegate(object sender, XS.ConsoleCtrlEventArgs e)
                        {
                            progress("remoteClient: Ctrl+C received");
                            try
                            {
                                sc.Abort();
                            }
                            catch
                            {
                            }
                        };
                        return(callback.OnContextReady(sc));
                    }
                }
                progress("remoteClient: Administrator privileges required!");
            }
            catch (Exception e)
            {
                progress("remoteClient: " + e);
                throw;
            }

            return(-1);
        }
예제 #30
0
        private static int updateStage(ScriptContext cout, string[] args)
        {
            string procName = Process.GetCurrentProcess().MainModule.FileName;

            try
            {
                if (args[0] == "overwrite")
                    cout.WriteLine(OutputType.Info, "XSharper update started.");

                cout.WriteLine(OutputType.Info, "Terminating parent process #" + args[1]);
                Process p = Process.GetProcessById(Utils.To<int>(args[1]));
                if (p != null)
                {
                    p.Kill();
                    p.Close();
                }

                Stopwatch sw = Stopwatch.StartNew();
                cout.Write(OutputType.Info, "Waiting for program to close...");
                for (int i = 0; i < 15; ++i)
                {
                    cout.Write(OutputType.Info, ".");
                    Thread.Sleep(1000);

                    try
                    {
                        FileInfo fi = new FileInfo(args[2]);
                        if (!fi.Exists)
                            break;
                        fi.Attributes = FileAttributes.Normal;
                        using (var q = new FileStream(fi.FullName, FileMode.Open, FileAccess.Write, FileShare.None))
                            break;
                    }
                    catch
                    {
                    }
                }
                cout.WriteLine(OutputType.Info);

                switch (args[0])
                {
                    case "overwrite":
                        cout.WriteLine(OutputType.Info, "Copying " + procName + " to " + args[2] + "...");
                        File.Copy(procName, args[2], true);
                        cout.WriteLine(OutputType.Info, "Waiting for 2 seconds...");
                        Thread.Sleep(2000);
                        ProcessStartInfo pi = new ProcessStartInfo
                        {
                            WorkingDirectory = Environment.CurrentDirectory,
                            FileName = args[2],
                            Arguments = "//" + xs.updateStage.Replace("xs.", "") + " delete " + Process.GetCurrentProcess().Id + " " + Utils.QuoteArg(procName),
                            UseShellExecute = false,
                            CreateNoWindow = false
                        };
                        cout.WriteLine(OutputType.Info, "Executing final part...");
                        Process pr = Process.Start(pi);
                        if (pr != null)
                            pr.WaitForExit();
                        return 0;

                    case "delete":
                        cout.WriteLine(OutputType.Info, "Deleting a temporary file " + args[2]);
                        File.Delete(args[2]);
                        Thread.Sleep(2000);
                        cout.WriteLine(OutputType.Info, string.Empty);
                        cout.WriteLine(OutputType.Info);
                        cout.WriteLine(OutputType.Bold, HelpHelper.GetLogo(cout));
                        cout.WriteLine(OutputType.Info, "Update successful. The program will terminate in 5 seconds.");
                        Thread.Sleep(5000);
                        return 0;
                    default:
                        return -1;
                }
            }
            catch (Exception e)
            {
                cout.WriteLine(OutputType.Error, e.Message);
                cout.WriteLine(OutputType.Error, "Software update failed. The program will terminate in 5 seconds.");
                Thread.Sleep(5000);
                return -1;
            }
        }
예제 #31
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // List all *.xsh files in App_Data
                var files = getScripts();
                if (files.Length > 0)
                {
                    cbScript.Items.Clear();
                    tbScript.Visible = false;
                    cbScript.Visible = true;

                    foreach (var file in files)
                    {
                        var name = Path.GetFileName(file);
                        var sb   = new StringBuilder("[" + name + "] ");
                        if (Path.GetExtension(file).ToUpper() == ".XSH")
                        {
                            var ctx = new XS.ScriptContext()
                            {
                                EnableCodePrecompilation = false
                            };
                            var s = ctx.LoadScript(file, false);
                            sb.Append(s.VersionInfo.Title);
                            cbScript.Items.Add(new ListItem(sb.ToString(), name));
                        }
                        else
                        {
                            var f = File.ReadAllLines(file);
                            if (f.Length > 0 && f[0].StartsWith("@rem", StringComparison.OrdinalIgnoreCase))
                            {
                                sb.Append(f[0].Substring(5));
                            }
                            else
                            {
                                sb.Append(f[0].Substring(5));
                            }
                            cbScript.Items.Add(new ListItem(sb.ToString(), name));
                        }
                    }

                    var script = Request.QueryString["id"];
                    if (script != null)
                    {
                        int?selection = null;
                        for (int i = 0; i < cbScript.Items.Count; ++i)
                        {
                            if (script.Equals(cbScript.Items[i].Value, StringComparison.OrdinalIgnoreCase))
                            {
                                selection = i;
                                break;
                            }
                            if (selection == null && cbScript.Items[i].Value.StartsWith(script, StringComparison.OrdinalIgnoreCase))
                            {
                                selection = i;
                            }
                        }
                        if (selection.HasValue)
                        {
                            cbScript.SelectedIndex = selection.Value;
                        }
                    }
                    var arg = Request.QueryString["args"];
                    if (arg != null)
                    {
                        tbArguments.Text = arg;
                    }
                }
                else
                {
                    var script = new XS.Script
                    {
                        Items = new List <XS.IScriptAction>
                        {
                            new XS.Print("Current directory: ${=.CurrentDirectory}")
                            {
                                OutTo = "^bold"
                            },
                            new XS.Print("Current user: ${=System.Security.Principal.WindowsIdentity.GetCurrent().Name}")
                            {
                                OutTo = "^bold"
                            },
                            new XS.Print("Temp directory: ${%TEMP%}")
                            {
                                OutTo = "^bold"
                            },
                            new XS.Print(),
                            new XS.Print("-- This will print 3 steps, ${=2+1} seconds one after another ---"),
                            new XS.While
                            {
                                MaxCount = "3",
                                Name     = "i",
                                Items    = new List <XS.IScriptAction>
                                {
                                    new XS.Print("Hello ")
                                    {
                                        NewLine = false
                                    },
                                    new XS.Print("World #${i}!")
                                    {
                                        OutTo = "^bold"
                                    },
                                    new XS.Sleep(3000)
                                }
                            },
                            new XS.Shell(@"@echo off

echo -- This batch file will print 10 steps, 2 seconds one after another
for /l %%f in (1 1 10) do (@echo Step #%%f) & (echo | @CHOICE /D y /T 2 2>nul 1>nul )
echo -- Completed -- 

")
                            {
                                OutTo          = "^info",
                                ErrorTo        = "^error",
                                CreateNoWindow = true,
                                IgnoreExitCode = true,
                                Mode           = XS.ShellMode.Batch
                            }
                        }
                    };
                    tbScript.Text    = script.SaveToString();
                    tbScript.Visible = true;
                    cbScript.Visible = false;
                }
            }
        }
예제 #32
0
        private static Script genUnzip(ScriptContext context, List<string> filteredArgs)
        {
            Script script;
            string[] s = context.GetStringArray(xs.unzip);
            if (s.Length < 1)
                throw new ArgumentException("Invalid arguments to " + xs.unzip + " command");

            script = createEmptyScript(context, "xsharper //unzip");
            script.Id = "unzip";
            filteredArgs.AddRange(s);

            script.Usage.Options = UsageOptions.IfHelp | UsageOptions.IfNoArguments | UsageOptions.UsageLine | UsageOptions.AutoSuffix;
            script.Parameters.Add(new CommandLineParameter("zip", CommandLineValueCount.Single, null, null) { Required = true, Description = "archive.zip", Value = "Zip archive to extract" });
            script.Parameters.Add(new CommandLineParameter("destination", CommandLineValueCount.Single, ".", null) { Description = "directory", Value = "Directory where to decompress files" });
            script.Parameters.Add(new CommandLineParameter("filter", CommandLineValueCount.Single, "*.*", null) { Description = "filter", Value = "File wildcard" });
            script.Parameters.Add(new CommandLineParameter("dirfilter", CommandLineValueCount.Single, "*", null) { Description = "directory-filter", Value = "Directory wildcard" });
            script.Parameters.Add(new CommandLineParameter(null, "zipTime", CommandLineValueCount.Single, "fileTime", null) { Synonyms = "zt", Value = "How to process time for files created in zip entries ( fileTime/utcFileTime = set to entry time, now/utcNow =ignore)" });
            script.Parameters.Add(new CommandLineParameter(null, "overwrite", CommandLineValueCount.Single, OverwriteMode.Always.ToString(), null) { Synonyms="o",Value = "Overwrite mode" });
            script.Parameters.Add(new CommandLineParameter(null, "password", CommandLineValueCount.Single, null, null) { Synonyms = "p", Value = "Archive password" });
            script.Parameters.Add(new CommandLineParameter(null, "ignore", CommandLineValueCount.None, "0", "1") { Synonyms = "i", Value = "Ignore errors" });
            script.Parameters.Add(new CommandLineParameter(null, "hidden", CommandLineValueCount.None, "0", "1") { Synonyms = "i", Value = "Extract hidden files" });

            script.Add(new PathOperation { Value = "${zip}", Operation = PathOperationType.GetFullPath, OutTo = "zip", Existence = Existence.FileExists});
            script.Add(new If(new Set("zip", "${=Path.ChangeExtension(${zip},'.zip')}"))
            {
                IsEmpty = "${=Path.GetExtension(${zip})}"
            });
            script.Add(new PathOperation { Value= "${destination}", Operation = PathOperationType.ToDirectoryInfo, Backslash = BackslashOption.Add, OutTo = "destination" });
            script.Add(new SetAttr("z", "zipTime", "${zipTime}"));
            script.Add(new SetAttr("z", "overwrite", "${overwrite}"));
            script.Add(new SetAttr("z", "hidden", "${hidden}"));

            script.Add(new Print { Value = "Extracting ${zip} => ${destination} ... " });

            Unzip z = new Unzip()
                          {
                              Id="z",
                              From = "${zip}",
                              To = "${destination}",
                              Transform = TransformRules.Expand,
                              Syntax = FilterSyntax.Auto,
                              Filter = "${filter}",
                              DirectoryFilter = "${dirfilter}",
                              Password = "******"
                          };
            z.Add(new Print { Value = "  ${to}", OutTo = "^info" });

            If f=new If(new[] { new Print("Failed: '${}' : ${=c.CurrentException.Message}") { OutTo = "^error"}});
            f.IsTrue = "${ignore}";
            f.AddElse(new Throw());
            z.AddCatch(f);

            script.Add(z);
            script.Add(new Print { Value = "Completed" });
            return script;
        }
예제 #33
0
        // Real main
        static int MainWithContext(XS.ScriptContext context, string[] args)
        {
            AppDomainLoader.progress("MainWithContext: Entering --------------------");
            XS.CommandLineParameter[] param = new XS.CommandLineParameter[] {
                new XS.CommandLineParameter(xs.quiet, XS.CommandLineValueCount.None, null, "true"),
                new XS.CommandLineParameter(xs.debug, XS.CommandLineValueCount.None, "false", "true"),
                new XS.CommandLineParameter(xs.debugc, XS.CommandLineValueCount.None, "false", "true"),
                new XS.CommandLineParameter(xs.verbose, XS.CommandLineValueCount.None, "false", "true"),
                new XS.CommandLineParameter(xs.nocolors, XS.CommandLineValueCount.None, "false", "true"),
                new XS.CommandLineParameter(xs.wait, XS.CommandLineValueCount.None, null, "true"),
                new XS.CommandLineParameter(xs.save, XS.CommandLineValueCount.Single, null, "xsharper_save.xsh"),
                new XS.CommandLineParameter(xs.log, XS.CommandLineValueCount.Single, null, "xsharper.log"),
                new XS.CommandLineParameter(xs.requireAdmin, XS.CommandLineValueCount.None, null, "true"),
                new XS.CommandLineParameter(xs.last, XS.CommandLineValueCount.None, null, "true"),
                new XS.CommandLineParameter(xs.utf8, XS.CommandLineValueCount.None, "false", "true"),
                new XS.CommandLineParameter(xs.scriptargs, null, XS.CommandLineValueCount.Multiple, null, null)
            };
            param[param.Length - 1].Last = true;
            param[param.Length - 2].Last = true;

            XS.CommandLineParameters xsParams = new XS.CommandLineParameters(param, "//", false);
            foreach (XS.CommandLineParameter a in xsParams)
            {
                if (!string.IsNullOrEmpty(a.Name) && a.Name != xs.scriptargs)
                {
                    a.Switch = a.Name.Replace("xs.", "");
                }
            }


            int exitCode = 0;

            bool utf8 = false;

            foreach (string arg in args)
            {
                if (arg.Equals(xs.utf8.Replace("xs.", "//"), StringComparison.OrdinalIgnoreCase))
                {
                    utf8 = true;
                }
            }
            using (XS.ConsoleWithColors cout = new XS.ConsoleWithColors(Environment.GetEnvironmentVariable("XSH_COLORS"), utf8))
                using (XS.CtrlCInterceptor ctrl = new XS.CtrlCInterceptor())
                {
                    context.Output += cout.OnOutput;
                    ctrl.Output     = context.Error;
                    ctrl.Abort     += delegate { context.Abort(); };

                    AppDomainLoader.progress("MainWithContext: Console ready --------------------");
                    System.Diagnostics.Stopwatch w = System.Diagnostics.Stopwatch.StartNew();

                    try
                    {
                        AppDomainLoader.progress("MainWithContext: Before parse--------------------");
                        xsParams.Parse(context, args, false);
                        AppDomainLoader.progress("MainWithContext: Before set options--------------------");
                        setOutputOptions(context, cout);

                        AppDomainLoader.progress("MainWithContext: Before load--------------------");
                        $ {
                            GENERATED_CLASS
                        } cl = new $ {
                            GENERATED_CLASS
                        } ();
                        XS.Script s = cl.Script;
                        ctrl.IgnoreCtrlC = s.IgnoreCtrlC;
                        ctrl.AbortDelay  = XS.Utils.ToTimeSpan(s.AbortDelay) ?? ctrl.AbortDelay;
                        ctrl.ExitDelay   = XS.Utils.ToTimeSpan(s.ExitDelay) ?? ctrl.ExitDelay;


                        AppDomainLoader.progress("MainWithContext: After load--------------------");
                        if (context.IsSet(xs.save))
                        {
                            using (XS.ScriptContextScope r = new XS.ScriptContextScope(context))
                                s.Save(context.GetString(xs.save));
                        }
                        else
                        {
                            context.Compiler.AddRequireAdmin(XS.Utils.To <XS.RequireAdminMode>(context.GetStr(xs.requireAdmin, XS.RequireAdminMode.User.ToString())));
                            context.Compiler.AddRequireAdmin(s.RequireAdmin);
                            if (context.Compiler.RequireAdmin != XS.RequireAdminMode.User && !context.IsAdministrator)
                            {
                                return(restartAsAdmin(context, args, context.Compiler.RequireAdmin == XS.RequireAdminMode.Hidden));
                            }

                            AppDomainLoader.progress("MainWithContext: Before initialization --------------------");
                            context.Initialize(s);
                            AppDomainLoader.progress("MainWithContext: After initialization --------------------");
                            string[] parms = null;
                            if (context.IsSet(xs.scriptargs))
                            {
                                parms = context.GetStringArray(xs.scriptargs);
                            }

                            XS.ConsoleRedirector redir = new XS.ConsoleRedirector(context);
                            try
                            {
                                AppDomainLoader.progress("MainWithContext: Before executing --------------------");
                                object r = context.ExecuteScript(s, parms, XS.CallIsolation.High);
                                ctrl.KillAbortTimer();
                                AppDomainLoader.progress("MainWithContext: After executing --------------------");
                                if (r != null)
                                {
                                    int.TryParse(r.ToString(), out exitCode);
                                }
                            }
                            finally
                            {
                                ctrl.KillAbortTimer();
                                redir.Dispose();
                            }
                        }
                    }
                    catch (ThreadAbortException ae)
                    {
                        resetAbort(context);
                        context.WriteException(ae.InnerException);
                        exitCode = -1000;
                    }
                    catch (XS.ScriptTerminateException te)
                    {
                        resetAbort(context);
                        exitCode = te.ExitCode;
                        if (te.InnerException != null)
                        {
                            context.WriteException(te.InnerException);
                        }
                    }
                    catch (Exception e)
                    {
                        resetAbort(context);
                        context.WriteException(e);
                        exitCode = -1;
                    }
                    finally
                    {
                        resetAbort(context);
                    }
                    if (context.GetBool(xs.wait, false))
                    {
                        cout.WriteLine(XS.OutputType.Info, string.Format("Completed in {0} with exit code={1}. Press Enter to close...", w.Elapsed, exitCode));
                        Console.ReadLine();
                    }
                }
            return(exitCode);
        }
예제 #34
0
        private static Script genVersion(ScriptContext context)
        {
            Script script = createEmptyScript(context, "xsharper //version"); ;
            script.Id = "version";
            script.Add(new Set("process","${=System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName}"));
            script.Add(new Set("net","${=string.Join(', ',(string[])XS.Utils.GetInstalledNETVersions())}"));
            script.Add(new Print { OutTo = "^bold", Value = HelpHelper.GetLogo(context) });
            script.Add(new Print());
            script.Add(new Print {Transform = TransformRules.Trim | TransformRules.Expand, NewLine = false, Value = @"
            Environment:
            ====================
            Operating system          : ${=Environment.OSVersion.VersionString}
            Available .NET Frameworks : ${net}
            .NET Framework            : ${=Environment.Version}
            Current directory         : ${=.CurrentDirectory}
            Privileges                : ${=.IsAdministrator?'Administrator':'Not administrator (use //requireAdmin)'}
            XSharper executable       : ${process}
            Configuration file        : ${=AppDomain.CurrentDomain.SetupInformation.ConfigurationFile} ${=File.Exists(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)?'':'(does not exist)'}

            Environment variables:
            =======================
            XSH_PATH            : ${%XSH_PATH%|''}
            XSH_REF             : ${%XSH_REF%|''}
            XSH_COLORS          : ${%XSH_COLORS%|''}"
            });
            script.Add(new Print());
            return script;
        }
예제 #35
0
        private static Script genDownload(ScriptContext context, List<string> filteredArgs)
        {
            Script script;
            script = createEmptyScript(context,"xsharper //download");
            script.Id = "download";
            filteredArgs.AddRange(context.GetStringArray(xs.download));
            script.Usage.Options = UsageOptions.IfHelp | UsageOptions.IfNoArguments | UsageOptions.UsageLine | UsageOptions.AutoSuffix;
            script.Parameters.Add(new CommandLineParameter("uri", CommandLineValueCount.Single, null, null) { Required = true,  Value = "Source URL" });
            script.Parameters.Add(new CommandLineParameter("file", CommandLineValueCount.Single, ".",null) { Value = "Destination file or directory" });
            script.Parameters.Add(new CommandLineParameter(null, "cache", CommandLineValueCount.Single, Utils.LowercaseFirstLetter(RequestCacheLevel.Default.ToString()), null) { Description = "cache-level", Value = "Cache level, one of "+Utils.AllEnumValuesToString(typeof(RequestCacheLevel)," / ") });
            script.Parameters.Add(new CommandLineParameter("passive", "activeFtp", CommandLineValueCount.None, true, false) { Value = "Use active FTP" });
            script.Parameters.Add(new CommandLineParameter("userAgent","userAgent", CommandLineValueCount.Single, null,null) { Value = "User agent string (http://)" });
            script.Parameters.Add(new CommandLineParameter("post", "post", CommandLineValueCount.Single, null, null) { Value = "HTTP Post string (evaluated as XSharper expression)"});
            script.Parameters.Add(new CommandLineParameter("postContentType", "postContentType", CommandLineValueCount.Single, null, null) { Value = "HTTP Post content type (default is application/x-www-form-urlencoded)" });
            script.Parameters.Add(new CommandLineParameter("timeout", "timeout", CommandLineValueCount.Single, null, null) { Value = "Timeout" });
            script.Parameters.Add(new CommandLineParameter("ignoreCertificateErrors", "ignoreCertificateErrors", CommandLineValueCount.None, true, false) { Value = "Ignore SSL certificate errors " });

            script.Add(new Set("oldReceived", "0"));
            script.Add(new SetAttr("d","cacheLevel","${cache}"));
            script.Add(new SetAttr("d", "passiveFtp", "${passive}"));
            script.Add(new Set("fn", "${=XS.Download.UrlToLocalFilename($uri,$file)}",TransformRules.Expand));
            script.Add(new Print { Value = "Downloading ${=XS.Utils.SecureUri($uri)} => ${fn} ... "});
            If ifs1 = new If()  {   IsTrue = "${ignoreCertificateErrors}"};

            ifs1.Add(new Code("System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };") { Dynamic = true });
            script.Add(ifs1);
            Download d = new Download
                             {
                                 Id = "d",
                                 From="${uri}",
                                 To = "${file}",
                                 UserAgent = "${userAgent|=null}",
                                 Post = "${=.Expand(${post|=null})}",
                                 PostContentType = "${postContentType|=null}",
                                 Timeout = "${timeout|=null}",
                                 Transform = TransformRules.Expand
                             };

            If ifs = new If()
                {
                    Condition = "${= $.bytesReceived/1024/100 #GT# $oldReceived/1024/100}"
                };
            ifs.Add(new Print(".") { OutTo="^info" , NewLine = false});
            d.Add(ifs);

            d.Add(new Set("oldReceived","${= $.bytesReceived}",TransformRules.Expand));

            script.Add(d);
            script.Add(new Print { Value = "Completed. ${oldReceived} bytes downloaded." });
            return script;
        }
예제 #36
0
 /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
 public void Dispose()
 {
     if (!_disposed)
     {
         if (ReferenceEquals(_set,s_current))
             s_current = _old;
         _disposed = true;
         _set = null;
         _old = null;
     }
     GC.SuppressFinalize(this);
 }
예제 #37
0
파일: Code.cs 프로젝트: xsharper/xsharper
        /// Generate source code of the snippet
        public string GenerateSourceCode(ScriptContext context,bool embedSourceCode, bool isPublic)
        {
            StringBuilder sb=new StringBuilder();
            sb.Append(
            @"        {public}class {class} : {base}
            {
            public override object Execute()
                ");
            sb  .Replace("{class}", GetClassName())
                .Replace("{public}", isPublic?"public ":"")
                .Replace("{ctxclass}", context.Compiler.GetTypeName(context.GetType()))
                .Replace("{base}", context.Compiler.GetTypeName(typeof(ExecutableScriptBase)));

            sb.AppendLine();

            string text = GetTransformedValueStr() ?? string.Empty;

            sb.AppendLine("\t\t\t// ---- User code ----- ");
            var t = text.Trim();
            if (!t.StartsWith("{", StringComparison.Ordinal))
                sb.AppendLine("{");
            sb.Append(t);
            sb.AppendLine();
            sb.AppendLine("\t\t\t// ---- End of user code ----- ");
            if (!t.StartsWith("{", StringComparison.Ordinal))
                sb.AppendLine("\t\t\t;return null;}");

            if (Methods!=null)
                foreach (IScriptAction c in Methods.Items)
                {
                    sb.AppendLine("");
                    string par = "",par2="null";
                    if (c is Sub)
                    {
                        par = "params object[] par";
                        par2 = "par";
                    }
                    sb.AppendLine("\tprivate object  " + c.Id + "(" + par + ") { return XS.ReturnValue.Unwrap(((" + GetType().FullName + ")c.CallStack.Peek().ScriptAction).ExecuteMember(XS.CallIsolation.Default,\"" + c.Id + "\", " + par2 + "));}");
                    sb.AppendLine("\tprivate object  " + c.Id + "_inline(" + par + ") { return ((" + GetType().FullName + ")c.CallStack.Peek().ScriptAction).ExecuteMember(XS.CallIsolation.None,\"" + c.Id + "\", " + par2 + ");}");
                    sb.AppendLine("\tprivate object  " + c.Id + "<T>(" + par + ") { return XS.Utils.To<T>(XS.ReturnValue.Unwrap(((" + GetType().FullName + ")c.CallStack.Peek().ScriptAction).ExecuteMember(XS.CallIsolation.None,\"" + c.Id + "\", " + par2 + ")));}");
                }
            if (embedSourceCode)
            {
                sb.AppendLine("\t\t\tpublic override string GetSourceCode() {");
                sb.Append("\t\t\t\treturn ");

                sb.Append("@\"");
                StringReader reader = new StringReader(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)));
                char[] buf = new char[80];
                int n;
                while ((n = reader.ReadBlock(buf, 0, buf.Length)) != 0)
                {
                    sb.Append(buf, 0, n);
                    if (n == buf.Length)
                    {
                        sb.AppendLine();
                        sb.Append("\t\t\t\t");
                    }
                }
                sb.Append("\"");
                sb.AppendLine("\t\t\t;}");
            }
            sb.AppendLine("\t\t}");
            return Utils.TransformStr(sb.ToString(), TransformRules.NewLineToCRLF);
        }
예제 #38
0
        private static XmlSchema generateSchema(ScriptContext context)
        {
            // Ensure that all objects are from one namespace
            string ns = null;
            foreach (var type in context.GetKnownTypes())
            {
                var na = (CustomAttributeHelper.First<XsTypeAttribute>(type));
                if (na == null)
                    continue;

                if (ns == null && na.Namespace != ScriptActionBase.XSharperNamespace)
                    ns = na.Namespace;
                else if (ns != na.Namespace && na.Namespace != ScriptActionBase.XSharperNamespace)
                    context.Info.WriteLine("Warning: Object " + na.Name + " has unexpected namespace " + na.Namespace + ". All types must use the same namespace.");
            }

            if (ns == null)
                ns = ScriptActionBase.XSharperNamespace;

            var xmlSchema = XsXsdGenerator.BuildSchema(ns, context.GetKnownTypes(), typeof(Script), new Type[] { typeof(IScriptAction) });
            xmlSchema.Id = ns == ScriptActionBase.XSharperNamespace ? "xsharper" : "custom";

            // Compile it, just to make sure it's valid
            XmlSchemaSet s = new XmlSchemaSet();
            s.Add(xmlSchema);
            s.Compile();

            return xmlSchema;
        }