示例#1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StorageConstructor"/> class.
        /// </summary>
        /// <param name="runner">The runner.</param>
        public StorageConstructor(ScriptRunner runner)
            : base(runner.Engine.Function.Prototype, "Storage", runner.Engine.Object.InstancePrototype)
        {
            this.runner = runner;

            PopulateFunctions();
        }
示例#2
0
文件: Logger.cs 项目: Alxandr/RunJS
 /// <summary>
 /// Initializes a new instance of the <see cref="LoggerConstructor"/> class.
 /// </summary>
 /// <param name="runner">The script runner.</param>
 public LoggerConstructor(ScriptRunner runner)
     : base(runner.Engine.Function.Prototype, "Logger", runner.Engine.Object.InstancePrototype)
 {
     LogManager.Configuration = runner.LogConfiguration;
     LogManager.ReconfigExistingLoggers();
     this.runner = runner;
 }
示例#3
0
        public ProgressPage(ScriptRunner runner, IScriptContinuation continuation)
        {
            if (runner == null)
                throw new ArgumentNullException("runner");

            InitializeComponent();

            switch (runner.Mode)
            {
                case ScriptRunnerMode.Install:
                    _header.Text = UILabels.Installing;
                    _header.SubText = String.Format(UILabels.InstallingSubText, runner.Environment.Config.SetupTitle);
                    break;

                case ScriptRunnerMode.Update:
                    _header.Text = UILabels.Updating;
                    _header.SubText = String.Format(UILabels.UpdatingSubText, runner.Environment.Config.SetupTitle);
                    break;

                case ScriptRunnerMode.Uninstall:
                    _header.Text = UILabels.Uninstalling;
                    _header.SubText = String.Format(UILabels.UninstallingSubText, runner.Environment.Config.SetupTitle);
                    break;
            }

            _progressListBox.Visible = false;

            continuation.Resume();
        }
示例#4
0
        public FinishPage(ScriptRunner runner, IScriptContinuation continuation)
        {
            if (runner == null)
                throw new ArgumentNullException("runner");
            if (continuation == null)
                throw new ArgumentNullException("continuation");

            _runner = runner;

            InitializeComponent();

            switch (_runner.Mode)
            {
                case ScriptRunnerMode.Install:
                    _headerLabel.Text = String.Format(UILabels.InstallComplete, runner.Environment.Config.SetupTitle);
                    _wizardLabel.Text = String.Format(UILabels.InstallCompleteSubText, runner.Environment.Config.SetupTitle);
                    break;

                case ScriptRunnerMode.Update:
                    _headerLabel.Text = String.Format(UILabels.UpdateComplete, runner.Environment.Config.SetupTitle);
                    _wizardLabel.Text = String.Format(UILabels.UpdateCompleteSubText, runner.Environment.Config.SetupTitle);
                    break;

                case ScriptRunnerMode.Uninstall:
                    _headerLabel.Text = String.Format(UILabels.UninstallComplete, runner.Environment.Config.SetupTitle);
                    _wizardLabel.Text = String.Format(UILabels.UninstallCompleteSubText, runner.Environment.Config.SetupTitle);
                    break;
            }

            continuation.Resume();
        }
示例#5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ClientConstructor"/> class.
        /// </summary>
        /// <param name="runner">The runner.</param>
        public ClientConstructor(ScriptRunner runner)
            : base(runner.Engine.Function.Prototype, "IrcClient", runner.Construct<JsEventObject>())
        {
            this.runner = runner;

            PopulateFunctions();
        }
示例#6
0
文件: JsPort.cs 项目: Alxandr/RunJS
 public JsPort(ScriptRunner runner)
     : base(runner.Engine.Object.Prototype)
 {
     this.runner = runner;
     Initialize();
     PopulateFunctions();
 }
示例#7
0
文件: Loader.cs 项目: Alxandr/RunJS
 /// <summary>
 /// Initializes a new instance of the <see cref="LoaderInstance"/> class.
 /// </summary>
 /// <param name="prototype">The prototype.</param>
 /// <param name="scriptRunner">The script runner.</param>
 public LoaderInstance(ObjectInstance prototype, ScriptRunner scriptRunner)
     : base(prototype)
 {
     this.scriptRunner = scriptRunner;
     this.webClient = new WebClient();
     this.PopulateFunctions();
 }
示例#8
0
 public static void DropTable(string connectionString)
 {
     ScriptRunner s = new ScriptRunner(Mother.DropTable(), new ScriptProcessing.SqliteScriptProcessor());
     using (var connection = new SQLiteConnection(connectionString))
     {
         var success = s.Execute(connection);
     }
 }
示例#9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="JsEventObject"/> class.
        /// </summary>
        /// <param name="prototype">The prototype.</param>
        /// <param name="runner">The runner.</param>
        public JsEventObject(ObjectInstance prototype, ScriptRunner runner)
            : base(prototype)
        {
            this.runner = runner;
            this.events = new Dictionary<string, List<FunctionInstance>>();

            PopulateFunctions(typeof(JsEventObject));
        }
 public UseItem(Battle battle, ThinkAction thinkAction)
     : base(battle)
 {
     if (thinkAction == null)
         throw new Exception("ThinkAction cannot be null");
     this.thinkAction = thinkAction;
     scriptRunner = null;
     item = null;
 }
 public void CRMNewTenancyRequestTestAW()
 {
     string startupPath = System.IO.Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.FullName+"\\Scripts";
     this.driver = DriverFactory.getIEDriver();
     //this.driver = new NavigateToURLWithAuth().navigateToURLWithAuth(this.driver,"http://srcrm51-te/MSCRMRTA08/main.aspx","florezj", "Dermnbr1");
     ScriptRunner runner = new ScriptRunner(new ClassConstructor(createPage));
     runner.OnException += onException;
     runner.RunAllScripts(startupPath);//"C:\\RTA Automation Solution\\RTA CRM Automation\\Scripts");
 }
 public void CRMNewTenancyRequestTestAWScenario1()
 {
     this.driver = DriverFactory.getIEDriver();
     //this.driver = new NavigateToURLWithAuth().navigateToURLWithAuth(this.driver,"http://srcrm51-te/MSCRMRTA08/main.aspx","florezj", "Dermnbr1");
     ScriptRunner runner = new ScriptRunner(new ClassConstructor(createPage));
     runner.OnException += onException;
     //runner.RunAllScripts("C:\\RTA Automation Solution\\RTA CRM Automation\\Scripts");
     runner.RunAllScripts("\\\\bn-s17\\Users$\\mateosp\\My Documents\\New folder\\RTA Automation Solution\\RTA CRM Automation\\Scripts");
 }
示例#13
0
 public void TestStart()
 {
     scriptRunner = new ScriptRunner();
     scriptRunner.Run();
     scriptRunner.Execute("var Storage = require('storage');");
     storage = scriptRunner.Execute("new Storage(Storage.inMemory)") as StorageInstance;
     if (storage == null)
         Assert.Ignore("Storage not found.");
     scriptRunner.Invoke((r) => r.Engine.SetGlobalValue("s", storage));
 }
示例#14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ClientInstance"/> class.
 /// </summary>
 /// <param name="prototype">The prototype.</param>
 /// <param name="runner">The runner.</param>
 public ClientInstance(ObjectInstance prototype, ScriptRunner runner)
     : base(prototype, runner)
 {
     client = new IrcClient();
     client.Message += new EventHandler<IrcMessageEventArgs>(client_Message);
     client.ChannelJoin += new EventHandler<IrcChannelEventArgs>(client_ChannelJoin);
     client.Disconnect += new EventHandler<EventArgs>(client_Disconnect);
     client.SslValidate += new EventHandler<SslValidateEventArgs>(client_SslValidate);
     PopulateFunctions();
 }
示例#15
0
        public AddInManager(ScriptRunner runner)
            : base(runner.Engine)
        {
            this.runner = runner;
            this.addins = new Dictionary<Tuple<string, string>, ClrFunction>();
            lock (addInManagers)
                addInManagers.Add(Engine, this);

            PopulateFunctions();
        }
示例#16
0
        public TimeoutHandler(ScriptRunner scriptRunner)
            : base(scriptRunner.Engine)
        {
            timeouts = new HashSet<int>();
            intervals = new HashSet<int>();
            this.scriptRunner = scriptRunner;
            timeoutHandlers.Add(Engine, this);

            PopulateFunctions();
            cancellationTokenSource = new CancellationTokenSource();
        }
示例#17
0
文件: Logger.cs 项目: Alxandr/RunJS
        /// <summary>
        /// Initializes a new instance of the <see cref="LoggerInstance"/> class.
        /// </summary>
        /// <param name="prototype">The prototype.</param>
        /// <param name="scriptRunner">The script runner.</param>
        /// <param name="logName">Name of the log.</param>
        public LoggerInstance(ObjectInstance prototype, ScriptRunner scriptRunner, string logName)
            : base(prototype)
        {
            this.scriptRunner = scriptRunner;
            logName = logName[0].ToString().ToUpper() + logName.Substring(1);
            this.logName = logName;
            this.logger = LogManager.GetLogger("JSLogger." + logName);

            classLogger.Trace("Logger {0} initialized.", logName);
            PopulateFunctions();
        }
        public void SetupFixtureWideObjects()
        {
            connectionStringMinPermissions = ConfigurationManager.ConnectionStrings["MinPermission"].ConnectionString;
            connectionStringAdditionalDb = ConfigurationManager.ConnectionStrings[SecondaryConnectionName].ConnectionString;

            scriptRunner = ScriptRunner.Get(PrimaryConnectionName);
            scriptRunner.CreateDb(SecondaryConnectionName);
            scriptRunner.Run(@"..\..\TestScripts\ExtraDB\01_Create_schema.sql");

            ParameterFactory = new SqlParameterFactory();
        }
示例#19
0
文件: Program.cs 项目: Alxandr/RunJS
        static void Main(string[] args)
        {
            if (File.Exists(Path.Combine(Environment.CurrentDirectory, "NLog.config")))
            {
                LogManager.ThrowExceptions = true;
                LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(Path.Combine(Environment.CurrentDirectory, "NLog.config"));
                LogManager.ReconfigExistingLoggers();
                logger.Info("Loaded log-config from current directory");
            }

            ScriptRunner scriptRunner = new ScriptRunner();
            scriptRunner.Run();

            scriptRunner.BeginInvoke(r =>
            {
                foreach (var s in scriptSources)
                    scriptRunner.Engine.Execute(s);

                foreach (var arg in args.Where(a => a[0] != '-'))
                    scriptRunner.Engine.ExecuteFile(arg);
            });

            if (args.Contains("--no-prompt"))
            {
                if (args.Any(arg => arg.StartsWith("--exec:")))
                {
                    foreach (var arg in args.Where(a => a.StartsWith("--exec:")).Select(a => a.Substring("--exec:".Length)))
                        scriptRunner.BeginInvoke(r => r.Execute(scriptRunner.Engine.Global[arg] as FunctionInstance));
                }
                scriptRunner.WaitForClose();
            }
            else
            {
                while (scriptRunner.Running)
                {
                    Console.Write(":> ");
                    string cmd = Console.ReadLine();

                    string result;
                    try
                    {
                        result = scriptRunner.Execute(cmd).ToString();
                    }
                    catch (JavaScriptException e)
                    {
                        result = e.ToString();
                    }

                    Console.WriteLine(result);
                    Console.WriteLine();
                }
            }
        }
示例#20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StorageInstance"/> class.
        /// </summary>
        /// <param name="prototype">The prototype.</param>
        /// <param name="runner">The runner.</param>
        /// <param name="path">The path.</param>
        public StorageInstance(ObjectInstance prototype, ScriptRunner runner, string path)
            : base(prototype)
        {
            this.runner = runner;
            this.path = path;
            try
            {
                this.mbro = CreateMbro(path);
            }
            catch (Exception e)
            {
                throw new JavaScriptException(Engine, "Error", "Error occured in mbro creation.", e);
            }

            PopulateFunctions();
        }
        public override void Start()
        {
            Weapon weapon = thinkAction.Actor.EquippedWeapon;
            Script script;
            if (weapon == null || weapon.Data.Script == null)
                script = new Script("0.0 doDamage string:actor string:target>list>front bool:false");
            else
                script = weapon.Data.Script;
            scriptRunner = new ScriptRunner(script, Battle, thinkAction.Actor, thinkAction.Target);

            AnimationState animationState = thinkAction.Actor.BattleEntity.AnimationState;
            if (animationState.Animation.Duration <= 0.0f)
                scriptStartTime = 0.0f;
            else
                scriptStartTime = animationState.Animation.Duration - (animationState.Time % animationState.Animation.Duration);
        }
        public InstallStartMenuPage(ScriptRunner runner, PageInstallStartMenu action, IScriptContinuation continuation)
        {
            if (runner == null)
                throw new ArgumentNullException("runner");
            if (action == null)
                throw new ArgumentNullException("action");
            if (continuation == null)
                throw new ArgumentNullException("continuation");

            _runner = runner;
            _continuation = continuation;

            InitializeComponent();

            _header.SubText = String.Format(_header.SubText, runner.Environment.Config.SetupTitle);

            _container.Enabled = action.Enabled;
            _createStartMenu.Visible = action.CreateStartMenuVisible;
            _createOnDesktop.Visible = action.CreateOnDesktopVisible;

            _originalStartMenuFolder = runner.Variables.GetRequired<string>(
                Constants.ScriptVariables.StartMenuPath
            );
            _createStartMenu.Checked = runner.Variables.GetOptional(
                Constants.ScriptVariables.CreateShortcuts, true
            );
            _createOnDesktop.Checked = runner.Variables.GetOptional(
                Constants.ScriptVariables.CreateDesktopShortcuts, true
            );

            _startMenuFolder.Text = _originalStartMenuFolder;

            var startMenuFolders = new List<string>();

            AddStartMenuFolders(startMenuFolders, NativeMethods.SpecialFolderCSIDL.CSIDL_PROGRAMS);
            AddStartMenuFolders(startMenuFolders, NativeMethods.SpecialFolderCSIDL.CSIDL_COMMON_PROGRAMS);

            startMenuFolders.Sort((a, b) => String.Compare(a, b, StringComparison.OrdinalIgnoreCase));

            foreach (string directory in startMenuFolders)
            {
                _startMenuFolders.Items.Add(directory);
            }

            PageUtil.UpdateAcceptButton(_acceptButton, action.IsLast);
        }
        public InstallDestinationFolderPage(ScriptRunner runner, PageInstallDestinationFolder action, IScriptContinuation continuation)
        {
            if (runner == null)
                throw new ArgumentNullException("runner");
            if (action == null)
                throw new ArgumentNullException("action");
            if (continuation == null)
                throw new ArgumentNullException("continuation");

            _runner = runner;
            _continuation = continuation;

            InitializeComponent();

            _header.SubText = String.Format(_header.SubText, runner.Environment.Config.SetupTitle);
            _introduction.Text = String.Format(
                _introduction.Text,
                runner.Environment.Config.SetupTitle,
                action.IsLast ? UILabels.InstallContinue : UILabels.NextContinue
            );

            string targetPath = _runner.Variables.GetRequired<string>(
                Constants.ScriptVariables.TargetPath
            );

            if (!Path.IsPathRooted(targetPath))
                throw new ScriptException(UILabels.TargetPathNotRooted);
            if (!Directory.Exists(Path.GetPathRoot(targetPath)))
                throw new ScriptException(UILabels.InvalidTargetPathRoot);

            long downloadFolderSize = CalculateDownloadFolderSize(
                runner.Environment.Config.PackageFolder
            );

            _spaceRequired.Text = String.Format(_spaceRequired.Text, Util.FormatSize(downloadFolderSize));

            _originalSpaceAvailable = _spaceAvailable.Text;

            _targetPath.Text = targetPath;

            _destination.Enabled = action.Enabled;

            PageUtil.UpdateAcceptButton(_acceptButton, action.IsLast);
        }
        public void AddTableInsertDataByTransactionTest()
        {
            var ScriptRunner = new SqlScriptRunner.ScriptRunner(Mother.AddTable(),
                                                                    new ScriptProcessing.SqliteScriptProcessor());

            using (var connection = new SQLiteConnection(Mother.ConnectionString()))
            {
                var success = false;
                connection.Open();
                using (var t = connection.BeginTransaction(IsolationLevel.ReadCommitted))
                {
                    try
                    {
                        success = ScriptRunner.Execute(t.Connection, t);
                        t.Commit();
                    }
                    catch (Exception)
                    {
                        t.Rollback();
                        throw;
                    }

                }
                if (success)
                {
                    ScriptRunner = new ScriptRunner(Mother.InsertData());
                    bool s = ScriptRunner.Execute(connection);
                    Assert.IsTrue(s);

                    //make sure that the data is actually in the DB now...
                    System.Data.IDbCommand cmd = connection.CreateCommand();
                    cmd.CommandText = Mother.SelectData();
                    var data = cmd.ExecuteReader();
                    Assert.IsNotNull(data);
                    Assert.IsTrue(data.FieldCount > 0);
                    data.Read();
                    Assert.IsTrue(data[0] != null);
                    Assert.IsNotNull(data[0]);
                }
            }

            Mother.DropTable(Mother.ConnectionString());
        }
示例#25
0
        public InstallLicensePage(ScriptRunner runner, PageInstallLicense action, IScriptContinuation continuation)
        {
            if (runner == null)
                throw new ArgumentNullException("runner");
            if (action == null)
                throw new ArgumentNullException("action");
            if (continuation == null)
                throw new ArgumentNullException("continuation");

            _runner = runner;
            _continuation = continuation;

            InitializeComponent();

            _license.Text = TextUtil.FixNewlines(runner.ParseTemplate(action.Value));
            _header.SubText = String.Format(_header.SubText, runner.Environment.Config.SetupTitle);
            _agree.Text = String.Format(_agree.Text, runner.Environment.Config.SetupTitle);

            _license.Select(0, 0);
        }
        public void AddTableInsertDataTemplatedTest()
        {
            var ScriptRunner = new SqlScriptRunner.ScriptRunner(Mother.AddTable(), new ScriptProcessing.SqliteScriptProcessor());
            ScriptRunner.Parameters = new Dictionary<string, string>();

            using (var connection = new SQLiteConnection(Mother.ConnectionString()))
            {
                var success = ScriptRunner.Execute(connection);

                if (success)
                {
                    ScriptRunner = new ScriptRunner(Mother.TemplatedInsert(), new ScriptProcessing.SqliteScriptProcessor());

                    long yValue = Mother.TemplateInteger();
                    long zValue = Mother.TemplateInteger();
                    ScriptRunner.Parameters.Add("ZVALUE", zValue.ToString());
                    ScriptRunner.Parameters.Add("YVALUE", yValue.ToString());

                    bool s = ScriptRunner.Execute(connection);
                    Assert.IsTrue(s);

                    //make sure that the data is actually in the DB now...
                    System.Data.IDbCommand cmd = connection.CreateCommand();
                    cmd.CommandText = Mother.SelectDataByYValue(yValue);

                    var data = cmd.ExecuteReader();
                    Assert.IsNotNull(data);
                    Assert.IsTrue(data.FieldCount > 0);
                    data.Read();
                    long zValueDB = (long)data[2];
                    Assert.AreEqual(zValueDB, zValue);

                }

            }
            Mother.DropTable(Mother.ConnectionString());
        }
示例#27
0
        public WelcomePage(ScriptRunner runner, IScriptAction action, IScriptContinuation continuation)
        {
            if (runner == null)
                throw new ArgumentNullException("runner");
            if (continuation == null)
                throw new ArgumentNullException("continuation");

            _continuation = continuation;

            InitializeComponent();

            switch (runner.Mode)
            {
                case ScriptRunnerMode.Install:
                    _headerLabel.Text = String.Format(UILabels.InstallWelcome, runner.Environment.Config.SetupTitle);
                    _wizardLabel.Text = String.Format(UILabels.InstallWelcomeSubText, runner.Environment.Config.SetupTitle);
                    break;

                case ScriptRunnerMode.Update:
                    _headerLabel.Text = String.Format(UILabels.UpdateWelcome, runner.Environment.Config.SetupTitle);
                    _wizardLabel.Text = String.Format(UILabels.UpdateWelcomeSubText, runner.Environment.Config.SetupTitle);
                    break;

                case ScriptRunnerMode.Uninstall:
                    _headerLabel.Text = String.Format(UILabels.UninstallWelcome, runner.Environment.Config.SetupTitle);
                    _wizardLabel.Text = String.Format(UILabels.UninstallWelcomeSubText, runner.Environment.Config.SetupTitle);
                    break;
            }

            bool isLast = false;

            if (action is PageInstallWelcome)
                isLast = ((PageInstallWelcome)action).IsLast;

            PageUtil.UpdateAcceptButton(_acceptButton, isLast);
        }
示例#28
0
		internal ScriptRunnerErrorEventArgs(ScriptRunner runner, ScriptRunnerError error) : base(runner)
		{
			this.Error = error;
		}
示例#29
0
 public EventsTest2(ObjectInstance prototype, ScriptRunner runner)
     : base(prototype, runner)
 {
 }
        public void RunScript_without_scriptKey_shall_return_false([Values(null, "")] string scriptKey)
        {
            var result = ScriptRunner.RunScript(null, _module, scriptKey, uiCommands: null, revisionGrid: null);

            result.Executed.Should().BeFalse();
        }
示例#31
0
        static void Main(string[] args)
        {
            // BEFORE you checkout the example:
            // this example is not optimized, it is not intended to be used in production
            // this should be used for understanding how the Framework operates, what it
            // needs, what you can do with it and what it returns

            Framework f = new Framework(); // basic, do this or go home

            string temp      = @"M:\Projects\omod\testDLL\temp";
            string OutputDir = @"M:\Projects\omod\testDLL\output";

            // check if the temp and output dir already exist and delete them if they do
            if (Directory.Exists(temp))
            {
                DeleteDirectory(temp);
            }
            Directory.CreateDirectory(temp);
            if (Directory.Exists(OutputDir))
            {
                DeleteDirectory(OutputDir);
            }
            Directory.CreateDirectory(OutputDir);

            f.SetOBMMVersion(1, 1, 12); // latest official obmm version use this unless you know what you're doing
            f.SetTempDirectory(temp);
            // setting the dll path is mostly used for debugging or if you execute the code from somewhere else
            // better safe than sorry just do this if
            f.SetDLLPath(@"M:\Projects\OMOD-Framework\OMOD-Framework\bin\Release\erri120.OMODFramework.dll");

            // after everything is setup you can go ahead and grap the omod
            OMOD omod = new OMOD(@"M:\Projects\omod\testDLL\Robert Male Body Replacer v52 OMOD-40532-1.omod", ref f);

            // before you run the install script, extract the data files and plugins from the omod
            // ExtractDataFiles will always return something but ExtractPlugins can return null if there is no
            // plugins.crc in the OMOD
            string dataPath    = omod.ExtractDataFiles(); //extracts all data files and returns the path to them
            string pluginsPath = omod.ExtractPlugins();   //extracts all plugins and returns the path to them

            // the interface IScriptRunnerFunctions should be implemented by something that you can pass on
            // as an argument, in this case I created an internal class called ScriptFunctions that implements
            // all functions from the interface
            ScriptFunctions a = new ScriptFunctions();

            // the script runner can execute the script, return the script and/or script type
            ScriptRunner sr = new ScriptRunner(ref omod, a);

            //to get the type:
            //ScriptType scriptType = sr.GetScriptType();

            //to get the entire script without the first byte:
            //String script = sr.GetScript();

            // this will execute the script and return all information about what needs to be installed
            ScriptReturnData srd = sr.ExecuteScript();

            // after the script executed go ahead and do whatever you want with the ScriptReturnData:
            // be sure to check if the installation is canceled or you will run into issues
            if (srd.CancelInstall)
            {
                Console.WriteLine("Installation canceled");
            }

            // just for testing
            bool doPretty = true;

            if (doPretty)
            {
                // if you do not want the raw output but a more 'prettier' version, use this method
                // it will change the ScriptReturnData and will populate the InstallFiles list
                srd.Pretty(true, ref omod, ref pluginsPath, ref dataPath);

                // loop through the whole thing, do note the custom struct
                foreach (InstallFile file in srd.InstallFiles)
                {
                    string s = Path.GetDirectoryName(file.InstallTo);
                    if (!Directory.Exists(Path.Combine(OutputDir, s)))
                    {
                        Directory.CreateDirectory(Path.Combine(OutputDir, s));
                    }
                    File.Move(file.InstallFrom, Path.Combine(OutputDir, file.InstallTo));
                }
            }
            else
            {
                // in the following example I will create two lists, one for all data files and one for all
                // plugins that need to be installed
                // this may seem non-intuitive since the ScriptReturnData should return this list
                // the thing is that you have InstallAll, Install, Ignore and Copy operations
                // the install script in the omod decideds what is best for itself

                List <string> InstallPlugins   = new List <string>();
                List <string> InstallDataFiles = new List <string>();

                // start by checking if you can install all plugins
                if (srd.InstallAllPlugins)
                {
                    // simply get all plugin files from the omod and loop through them
                    // the s.Contains is just a safety check
                    foreach (string s in omod.GetPluginList())
                    {
                        if (!s.Contains("\\"))
                        {
                            InstallPlugins.Add(s);
                        }
                    }
                }
                // if you can't install everything go and check the list called InstallPlugins
                // this list gets populated when InstallAllPlugins is false
                // the Framework comes with two utility functions that helps in creating the temp list:
                // strArrayContains and strArrayRemove
                foreach (string s in srd.InstallPlugins)
                {
                    if (!Framework.strArrayContains(InstallPlugins, s))
                    {
                        InstallPlugins.Add(s);
                    }
                }
                // next up is removing all plugins that are set to be ignored:
                foreach (string s in srd.IgnorePlugins)
                {
                    Framework.strArrayRemove(InstallPlugins, s);
                }
                // last is going through the CopyPlugins list
                // in case you ask why there is a CopyPlugins list and what is does:
                // (it makes more sense with data files but whatever)
                // if the omod has eg this folder structure:
                //
                // installfiles/
                //              Option1/
                //                      Meshes/
                //                      Textures/
                //              Option2/
                //                      Meshes/
                //                      Textures/
                // this is nice for writing the installation script as you kan keep track of what option
                // has what files
                // Authors than call CopyPlugins/Data and move the files from the options folder to
                // the root folder:
                //
                // meshes/
                // textures/
                // installfiles/
                //              Option1/
                //                      Meshes/
                //                      Textures/
                //              Option2/
                //                      Meshes/
                //                      Textures/
                foreach (ScriptCopyDataFile scd in srd.CopyPlugins)
                {
                    // check if the file you want to copy actually exists
                    if (!File.Exists(Path.Combine(pluginsPath, scd.CopyFrom)))
                    {
                        return;
                    }
                    else
                    {
                        // check if the mod author didnt make a mistake
                        if (scd.CopyFrom != scd.CopyTo)
                        {
                            // unlikely but you never know
                            if (File.Exists(Path.Combine(pluginsPath, scd.CopyTo)))
                            {
                                File.Delete(Path.Combine(pluginsPath, scd.CopyTo));
                            }
                            File.Copy(Path.Combine(pluginsPath, scd.CopyFrom), Path.Combine(pluginsPath, scd.CopyTo));
                        }
                        // important to add the file to the temp list or else it will not be installed
                        if (!Framework.strArrayContains(InstallPlugins, scd.CopyTo))
                        {
                            InstallPlugins.Add(scd.CopyTo);
                        }
                    }
                }

                // now do the same for the data files :)
                if (srd.InstallAllData)
                {
                    foreach (string s in omod.GetDataFileList())
                    {
                        InstallDataFiles.Add(s);
                    }
                }
                foreach (string s in srd.InstallData)
                {
                    if (!Framework.strArrayContains(InstallDataFiles, s))
                    {
                        InstallDataFiles.Add(s);
                    }
                }
                foreach (string s in srd.IgnoreData)
                {
                    Framework.strArrayRemove(InstallDataFiles, s);
                }
                foreach (ScriptCopyDataFile scd in srd.CopyDataFiles)
                {
                    if (!File.Exists(Path.Combine(dataPath, scd.CopyFrom)))
                    {
                        return;
                    }
                    else
                    {
                        if (scd.CopyFrom != scd.CopyTo)
                        {
                            // because data files can be in subdirectories we have to check if the folder actually exists
                            string dirName = Path.GetDirectoryName(Path.Combine(dataPath, scd.CopyTo));
                            if (!Directory.Exists(dirName))
                            {
                                Directory.CreateDirectory(dirName);
                            }
                            if (File.Exists(Path.Combine(dataPath, scd.CopyTo)))
                            {
                                File.Delete(Path.Combine(dataPath, scd.CopyTo));
                            }
                            File.Copy(Path.Combine(dataPath, scd.CopyFrom), Path.Combine(dataPath, scd.CopyTo));
                        }
                        if (!Framework.strArrayContains(InstallDataFiles, scd.CopyTo))
                        {
                            InstallDataFiles.Add(scd.CopyTo);
                        }
                    }
                }

                // after everything is done some final checks
                for (int i = 0; i < InstallDataFiles.Count; i++)
                {
                    // if the files have \\ at the start than Path.Combine wont work :(
                    if (InstallDataFiles[i].StartsWith("\\"))
                    {
                        InstallDataFiles[i] = InstallDataFiles[i].Substring(1);
                    }
                    string currentFile = Path.Combine(dataPath, InstallDataFiles[i]);
                    // also check if the file we want to install exists and is not in the 5th dimension eating lunch
                    if (!File.Exists(currentFile))
                    {
                        InstallDataFiles.RemoveAt(i--);
                    }
                }

                for (int i = 0; i < InstallPlugins.Count; i++)
                {
                    if (InstallPlugins[i].StartsWith("\\"))
                    {
                        InstallPlugins[i] = InstallPlugins[i].Substring(1);
                    }
                    string currentFile = Path.Combine(pluginsPath, InstallPlugins[i]);
                    if (!File.Exists(currentFile))
                    {
                        InstallPlugins.RemoveAt(i--);
                    }
                }

                // now install
                for (int i = 0; i < InstallDataFiles.Count; i++)
                {
                    // check if the folder exists before copying
                    string s = Path.GetDirectoryName(InstallDataFiles[i]);
                    if (!Directory.Exists(Path.Combine(OutputDir, s)))
                    {
                        Directory.CreateDirectory(Path.Combine(OutputDir, s));
                    }
                    File.Move(Path.Combine(dataPath, InstallDataFiles[i]), Path.Combine(OutputDir, InstallDataFiles[i]));
                }
                for (int i = 0; i < InstallPlugins.Count; i++)
                {
                    File.Move(Path.Combine(pluginsPath, InstallPlugins[i]), Path.Combine(OutputDir, InstallPlugins[i]));
                }
            }
        }
示例#32
0
        /// <summary>
        /// Run a sql batch for the datasource.
        /// </summary>
        /// <param name="datasource">The datasource.</param>
        /// <param name="script">The sql batch</param>
        /// <param name="doParse">parse out the statements in the sql script file.</param>
        protected static void InitScript(IDataSource datasource, string script, bool doParse)
        {
            ScriptRunner runner = new ScriptRunner();

            runner.RunScript(datasource, script, doParse);
        }
示例#33
0
        void OpenEvent(object sender, EventArgs e)
        {
            if (((TreeView)ControlDictionary["categoryTreeView"]).SelectedNode != null)
            {
                PropertyService.Set("Dialogs.NewProjectDialog.LargeImages", ((RadioButton)ControlDictionary["largeIconsRadioButton"]).Checked);
                PropertyService.Set("Dialogs.NewFileDialog.LastSelectedCategory", ((TreeView)ControlDictionary["categoryTreeView"]).SelectedNode.Text);
            }
            createdFiles.Clear();
            if (((ListView)ControlDictionary["templateListView"]).SelectedItems.Count == 1)
            {
                if (!AllPropertiesHaveAValue)
                {
                    MessageService.ShowMessage("${res:Dialog.NewFile.FillOutFirstMessage}", "${res:Dialog.NewFile.FillOutFirstCaption}");
                    return;
                }
                TemplateItem item = (TemplateItem)((ListView)ControlDictionary["templateListView"]).SelectedItems[0];
                string       fileName;
                StringParser.Properties["StandardNamespace"] = "DefaultNamespace";
                if (allowUntitledFiles)
                {
                    fileName = GenerateCurrentFileName();
                }
                else
                {
                    fileName = ControlDictionary["fileNameTextBox"].Text.Trim();
                    if (!FileUtility.IsValidFileName(fileName) ||
                        fileName.IndexOf(Path.AltDirectorySeparatorChar) >= 0 ||
                        fileName.IndexOf(Path.DirectorySeparatorChar) >= 0)
                    {
                        MessageService.ShowError(StringParser.Parse("${res:ICSharpCode.SharpDevelop.Commands.SaveFile.InvalidFileNameError}", new string[, ] {
                            { "FileName", fileName }
                        }));
                        return;
                    }
                    if (Path.GetExtension(fileName).Length == 0)
                    {
                        fileName += Path.GetExtension(item.Template.DefaultName);
                    }
                    fileName = Path.Combine(basePath, fileName);
                    fileName = Path.GetFullPath(fileName);
                    IProject project = ProjectService.CurrentProject;
                    if (project != null)
                    {
                        StringParser.Properties["StandardNamespace"] = CustomToolsService.GetDefaultNamespace(project, fileName);
                    }
                }
                StringParser.Properties["FullName"] = fileName;
                StringParser.Properties["FileName"] = Path.GetFileName(fileName);
                StringParser.Properties["FileNameWithoutExtension"] = Path.GetFileNameWithoutExtension(fileName);
                StringParser.Properties["Extension"] = Path.GetExtension(fileName);
                StringParser.Properties["Path"]      = Path.GetDirectoryName(fileName);

                StringParser.Properties["ClassName"] = GenerateValidClassName(Path.GetFileNameWithoutExtension(fileName));


                if (item.Template.WizardPath != null)
                {
                    Properties customizer = new Properties();
                    customizer.Set("Template", item.Template);
                    customizer.Set("Creator", this);
                    WizardDialog wizard = new WizardDialog("File Wizard", customizer, item.Template.WizardPath);
                    if (wizard.ShowDialog(ICSharpCode.SharpDevelop.Gui.WorkbenchSingleton.MainForm) == DialogResult.OK)
                    {
                        DialogResult = DialogResult.OK;
                    }
                }
                else
                {
                    foreach (FileDescriptionTemplate newfile in item.Template.FileDescriptionTemplates)
                    {
                        if (!IsFilenameAvailable(StringParser.Parse(newfile.Name)))
                        {
                            MessageService.ShowError("Filename " + StringParser.Parse(newfile.Name) + " is in use.\nChoose another one");
                            return;
                        }
                    }
                    ScriptRunner scriptRunner = new ScriptRunner();

                    foreach (FileDescriptionTemplate newfile in item.Template.FileDescriptionTemplates)
                    {
                        if (newfile.ContentData != null)
                        {
                            SaveFile(newfile, null, newfile.ContentData);
                        }
                        else
                        {
                            SaveFile(newfile, scriptRunner.CompileScript(item.Template, newfile), null);
                        }
                    }
                    DialogResult = DialogResult.OK;

                    // raise FileCreated event for the new files
                    foreach (KeyValuePair <string, FileDescriptionTemplate> entry in createdFiles)
                    {
                        FileService.FireFileCreated(entry.Key);
                    }
                }
            }
        }
示例#34
0
        private bool RunScriptInteractiveSub(ScriptDto scriptDto)
        {
            Console.WriteLine();



            bool isDoReturn = SubA();

            return(isDoReturn);

            bool SubA()
            {
                while (true)
                {
                    String msgPresentScript = $"Script {scriptDto.Id} :";
                    Console.WriteLine(new String('=', msgPresentScript.Length + 2));
                    Console.WriteLine($" {msgPresentScript}");
                    Console.WriteLine(new String('=', msgPresentScript.Length + 2));

                    Console.WriteLine("[0] Lancer le script");
                    Console.WriteLine("[1] Revenir en arrière");

                    Console.WriteLine();
                    Console.Write("Faites votre choix : ");
                    String choiceStr = Console.ReadLine();

                    int choice = -1;
                    if ((choice = MiscAppUtils.IntParse(choiceStr)) >= 0)
                    {
                        if (choice == 1)
                        {
                            break;
                        }
                        else
                        {
                            if (SubB())
                            {
                                return(true);
                            }
                            Console.Clear();
                        }
                    }
                }

                return(false);
            }

            bool SubB()
            {
                while (true)
                {
                    Console.WriteLine();

                    string argScript    = ScriptRunner.GetScriptArgsTpl(scriptDto);
                    int    nbArgsScript = ScriptRunner.ExtractNbArgs(argScript);

                    if (nbArgsScript == 0)
                    {
                        Console.WriteLine("Aucun argument à fournir pour ce script");
                    }
                    else
                    {
                        Console.WriteLine("Paramètres de lancement :");
                        Console.WriteLine(argScript);
                        Console.WriteLine();

                        List <String> listArgs = new List <string>(nbArgsScript);

                        for (int i = 0; i < nbArgsScript; i++)
                        {
                            Console.Write("Valorisez %1: ");
                            listArgs.Insert(i, Console.ReadLine());
                        }
                        listArgs.Insert(0, String.Join(" ", listArgs));

                        Console.WriteLine();
                        string argScriptRepl = ScriptRunner.ReplaceArgsInTpl(argScript, listArgs);
                        Console.WriteLine("Le script sera lancé avec ces paramètres :");
                        Console.WriteLine(argScriptRepl);
                        Console.WriteLine();

                        Console.WriteLine();
                        Console.Write("Voulez-vous continuer ? [o/n/a] : ");
                        String choiceStr = Console.ReadLine();

                        if (choiceStr == null || choiceStr.Equals("n", StringComparison.CurrentCultureIgnoreCase))
                        {
                            continue;
                        }
                        else if (choiceStr.Equals("a", StringComparison.CurrentCultureIgnoreCase))
                        {
                            return(false);
                        }


                        appArgs.ScriptArgsInput = listArgs;
                    }

                    try
                    {
                        ScriptRunner sRun = new ScriptRunner(scriptDto);
                        _handler += new EventHandler(sRun.HandleUnusalExit);
                        SetConsoleCtrlHandler(_handler, true);
                        sRun.Run(appArgs.ScriptArgsInput);
                    }
                    catch (Exception e)
                    {
                        Thread.Sleep(5000);
                        return(false);
                    }

                    break;
                }

                return(true);
            }
        }
示例#35
0
        private static int Wain(string[] args)
        {
            var app = new CommandLineApplication(throwOnUnexpectedArg: false)
            {
                ExtendedHelpText = "Starting without a path to a CSX file or a command, starts the REPL (interactive) mode."
            };
            var file        = app.Argument("script", "Path to CSX script");
            var interactive = app.Option("-i | --interactive", "Execute a script and drop into the interactive mode afterwards.", CommandOptionType.NoValue);

            var configuration = app.Option("-c | --configuration <configuration>", "Configuration to use for running the script [Release/Debug] Default is \"Debug\"", CommandOptionType.SingleValue);

            var packageSources = app.Option("-s | --sources <SOURCE>", "Specifies a NuGet package source to use when resolving NuGet packages.", CommandOptionType.MultipleValue);

            var debugMode = app.Option(DebugFlagShort + " | " + DebugFlagLong, "Enables debug output.", CommandOptionType.NoValue);

            var verbosity = app.Option("--verbosity", " Set the verbosity level of the command. Allowed values are t[trace], d[ebug], i[nfo], w[arning], e[rror], and c[ritical].", CommandOptionType.SingleValue);

            var nocache = app.Option("--nocache", "disable DLL caching", CommandOptionType.NoValue);

            var argsBeforeDoubleHyphen = args.TakeWhile(a => a != "--").ToArray();
            var argsAfterDoubleHyphen  = args.SkipWhile(a => a != "--").Skip(1).ToArray();

            app.HelpOption("-? | -h | --help");

            app.VersionOption("-v | --version", GetVersion);

            var infoOption = app.Option("--info", "Displays environmental information", CommandOptionType.NoValue);

            app.Command("eval", c =>
            {
                c.Description = "Execute CSX code.";
                var code      = c.Argument("code", "Code to execute.");
                var cwd       = c.Option("-cwd |--workingdirectory <currentworkingdirectory>", "Working directory for the code compiler. Defaults to current directory.", CommandOptionType.SingleValue);
                c.OnExecute(async() =>
                {
                    int exitCode = 0;
                    if (!string.IsNullOrWhiteSpace(code.Value))
                    {
                        var optimizationLevel = OptimizationLevel.Debug;
                        if (configuration.HasValue() && configuration.Value().ToLower() == "release")
                        {
                            optimizationLevel = OptimizationLevel.Release;
                        }
                        var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());
                        exitCode       = await RunCode(code.Value, debugMode.HasValue(), logFactory, optimizationLevel, app.RemainingArguments.Concat(argsAfterDoubleHyphen), cwd.Value(), packageSources.Values?.ToArray());
                    }
                    return(exitCode);
                });
            });

            app.Command("init", c =>
            {
                c.Description = "Creates a sample script along with the launch.json file needed to launch and debug the script.";
                var fileName  = c.Argument("filename", "(Optional) The name of the sample script file to be created during initialization. Defaults to 'main.csx'");
                var cwd       = c.Option("-cwd |--workingdirectory <currentworkingdirectory>", "Working directory for initialization. Defaults to current directory.", CommandOptionType.SingleValue);
                c.OnExecute(() =>
                {
                    var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());
                    var scaffolder = new Scaffolder(logFactory);
                    scaffolder.InitializerFolder(fileName.Value, cwd.Value() ?? Directory.GetCurrentDirectory());
                    return(0);
                });
            });

            app.Command("new", c =>
            {
                c.Description        = "Creates a new script file";
                var fileNameArgument = c.Argument("filename", "The script file name");
                var cwd = c.Option("-cwd |--workingdirectory <currentworkingdirectory>", "Working directory the new script file to be created. Defaults to current directory.", CommandOptionType.SingleValue);
                c.OnExecute(() =>
                {
                    var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());
                    var scaffolder = new Scaffolder(logFactory);
                    if (fileNameArgument.Value == null)
                    {
                        c.ShowHelp();
                        return(0);
                    }
                    scaffolder.CreateNewScriptFile(fileNameArgument.Value, cwd.Value() ?? Directory.GetCurrentDirectory());
                    return(0);
                });
            });

            app.Command("publish", c =>
            {
                c.Description              = "Creates a self contained executable or DLL from a script";
                var fileNameArgument       = c.Argument("filename", "The script file name");
                var publishDirectoryOption = c.Option("-o |--output", "Directory where the published executable should be placed.  Defaults to a 'publish' folder in the current directory.", CommandOptionType.SingleValue);
                var dllName          = c.Option("-n |--name", "The name for the generated DLL (executable not supported at this time).  Defaults to the name of the script.", CommandOptionType.SingleValue);
                var dllOption        = c.Option("--dll", "Publish to a .dll instead of an executable.", CommandOptionType.NoValue);
                var commandConfig    = c.Option("-c | --configuration <configuration>", "Configuration to use for publishing the script [Release/Debug]. Default is \"Debug\"", CommandOptionType.SingleValue);
                var publishDebugMode = c.Option(DebugFlagShort + " | " + DebugFlagLong, "Enables debug output.", CommandOptionType.NoValue);
                var runtime          = c.Option("-r |--runtime", "The runtime used when publishing the self contained executable. Defaults to your current runtime.", CommandOptionType.SingleValue);

                c.OnExecute(() =>
                {
                    if (fileNameArgument.Value == null)
                    {
                        c.ShowHelp();
                        return(0);
                    }

                    var optimizationLevel = OptimizationLevel.Debug;
                    if (commandConfig.HasValue() && commandConfig.Value().ToLower() == "release")
                    {
                        optimizationLevel = OptimizationLevel.Release;
                    }

                    var runtimeIdentifier = runtime.Value() ?? ScriptEnvironment.Default.RuntimeIdentifier;
                    var absoluteFilePath  = Path.IsPathRooted(fileNameArgument.Value) ? fileNameArgument.Value : Path.Combine(Directory.GetCurrentDirectory(), fileNameArgument.Value);

                    // if a publish directory has been specified, then it is used directly, otherwise:
                    // -- for EXE {current dir}/publish/{runtime ID}
                    // -- for DLL {current dir}/publish
                    var publishDirectory = publishDirectoryOption.Value() ??
                                           (dllOption.HasValue() ? Path.Combine(Path.GetDirectoryName(absoluteFilePath), "publish") : Path.Combine(Path.GetDirectoryName(absoluteFilePath), "publish", runtimeIdentifier));

                    var absolutePublishDirectory = Path.IsPathRooted(publishDirectory) ? publishDirectory : Path.Combine(Directory.GetCurrentDirectory(), publishDirectory);

                    var logFactory    = CreateLogFactory(verbosity.Value(), debugMode.HasValue());
                    var compiler      = GetScriptCompiler(publishDebugMode.HasValue(), logFactory);
                    var scriptEmmiter = new ScriptEmitter(ScriptConsole.Default, compiler);
                    var publisher     = new ScriptPublisher(logFactory, scriptEmmiter);
                    var code          = SourceText.From(File.ReadAllText(absoluteFilePath));
                    var context       = new ScriptContext(code, absolutePublishDirectory, Enumerable.Empty <string>(), absoluteFilePath, optimizationLevel);

                    if (dllOption.HasValue())
                    {
                        publisher.CreateAssembly <int, CommandLineScriptGlobals>(context, logFactory, dllName.Value());
                    }
                    else
                    {
                        publisher.CreateExecutable <int, CommandLineScriptGlobals>(context, logFactory, runtimeIdentifier);
                    }

                    return(0);
                });
            });

            app.Command("exec", c =>
            {
                c.Description        = "Run a script from a DLL.";
                var dllPath          = c.Argument("dll", "Path to DLL based script");
                var commandDebugMode = c.Option(DebugFlagShort + " | " + DebugFlagLong, "Enables debug output.", CommandOptionType.NoValue);
                c.OnExecute(async() =>
                {
                    int exitCode = 0;
                    if (!string.IsNullOrWhiteSpace(dllPath.Value))
                    {
                        if (!File.Exists(dllPath.Value))
                        {
                            throw new Exception($"Couldn't find file '{dllPath.Value}'");
                        }

                        var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());

                        var absoluteFilePath = Path.IsPathRooted(dllPath.Value) ? dllPath.Value : Path.Combine(Directory.GetCurrentDirectory(), dllPath.Value);

                        var compiler = GetScriptCompiler(commandDebugMode.HasValue(), logFactory);
                        var runner   = new ScriptRunner(compiler, logFactory, ScriptConsole.Default);
                        var result   = await runner.Execute <int>(absoluteFilePath, app.RemainingArguments.Concat(argsAfterDoubleHyphen));
                        return(result);
                    }
                    return(exitCode);
                });
            });

            app.OnExecute(async() =>
            {
                int exitCode = 0;

                if (infoOption.HasValue())
                {
                    Console.Write(GetEnvironmentInfo());
                    return(0);
                }

                var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());

                if (!string.IsNullOrWhiteSpace(file.Value))
                {
                    if (Debugger.IsAttached || nocache.HasValue())
                    {
                        var optimizationLevel = OptimizationLevel.Debug;
                        if (configuration.HasValue() && configuration.Value().ToLower() == "release")
                        {
                            optimizationLevel = OptimizationLevel.Release;
                        }
                        exitCode = await RunScript(file.Value, debugMode.HasValue(), logFactory, optimizationLevel, app.RemainingArguments.Concat(argsAfterDoubleHyphen), interactive.HasValue(), packageSources.Values?.ToArray());
                    }
                    else
                    {
                        string cacheFolder = Path.Combine(Path.GetTempPath(), "dotnet-scripts");
                        // create unique folder name based on the path
                        string uniqueFolderName = "";
                        using (var sha = SHA256.Create())
                        {
                            uniqueFolderName = Convert.ToBase64String(sha.ComputeHash(Encoding.Unicode.GetBytes(file.Value))).Replace("=", String.Empty).Replace("/", string.Empty);
                        }

                        string publishDirectory = Path.Combine(cacheFolder, uniqueFolderName);
                        if (!Directory.Exists(publishDirectory))
                        {
                            Directory.CreateDirectory(publishDirectory);
                        }

                        string absoluteSourcePath;
                        SourceText code;
                        if (!File.Exists(file.Value))
                        {
                            if (IsHttpUri(file.Value))
                            {
                                var downloader     = new ScriptDownloader();
                                var rawCode        = await downloader.Download(file.Value);
                                absoluteSourcePath = Path.Combine(publishDirectory, "source.csx");
                                File.WriteAllText(absoluteSourcePath, rawCode);
                                code = SourceText.From(rawCode);
                            }
                            else
                            {
                                throw new Exception($"Couldn't find file '{file}'");
                            }
                        }
                        else
                        {
                            absoluteSourcePath = Path.IsPathRooted(file.Value) ? Path.GetFullPath(file.Value) : Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), file.Value));
                            code = SourceText.From(File.ReadAllText(absoluteSourcePath));
                        }

                        // given the path to a script we create a %temp%\dotnet-scripts\{uniqueFolderName} path
                        string pathToDll = Path.Combine(publishDirectory, Path.GetFileNameWithoutExtension(absoluteSourcePath) + ".dll");

                        // source hash is the checkSum of the code
                        string sourceHash = Convert.ToBase64String(code.GetChecksum().ToArray());

                        // get hash code from previous run
                        string hashCache = Path.Combine(publishDirectory, ".hash");
                        var compiler     = GetScriptCompiler(true, logFactory);

                        // if we don't have hash
                        if (!File.Exists(hashCache) ||
                            // or we haven't created a dll
                            !Directory.Exists(publishDirectory) ||
                            // the hashcode has changed (meaning new content)
                            File.ReadAllText(hashCache) != sourceHash)
                        {
                            // then we autopublish into the %temp%\dotnet-scripts\{uniqueFolderName} path
                            var optimizationLevel = OptimizationLevel.Debug;
                            if (configuration.HasValue() && configuration.Value().ToLower() == "release")
                            {
                                optimizationLevel = OptimizationLevel.Release;
                            }

                            var runtimeIdentifier = ScriptEnvironment.Default.RuntimeIdentifier;
                            var scriptEmmiter     = new ScriptEmitter(ScriptConsole.Default, compiler);
                            var publisher         = new ScriptPublisher(logFactory, scriptEmmiter);
                            var context           = new ScriptContext(code, publishDirectory, Enumerable.Empty <string>(), absoluteSourcePath, optimizationLevel);

                            // create the assembly in our cache folder
                            publisher.CreateAssembly <int, CommandLineScriptGlobals>(context, logFactory, Path.GetFileNameWithoutExtension(pathToDll));

                            // save sourceHash for next time, so we can know it's ok to use the generated dll next time
                            File.WriteAllText(hashCache, sourceHash);
                        }


                        // run the cached %temp%\dotnet-scripts\{uniqueFolderName}/package.dll
                        var runner = new ScriptRunner(compiler, logFactory, ScriptConsole.Default);
                        var result = await runner.Execute <int>(pathToDll, app.RemainingArguments.Concat(argsAfterDoubleHyphen));
                        return(result);
                    }
                }
                else
                {
                    await RunInteractive(debugMode.HasValue(), logFactory, packageSources.Values?.ToArray());
                }
                return(exitCode);
            });


            return(app.Execute(argsBeforeDoubleHyphen));
        }
示例#36
0
        // Start a new game.
        public void StartGame()
        {
            roomTicks = 0;

            // Setup the player beforehand so certain classes such as the HUD can reference it
            player = new Player();

            inventory                       = new Inventory(this);
            menuWeapons                     = new MenuWeapons(gameManager);
            menuSecondaryItems              = new MenuSecondaryItems(gameManager);
            menuEssences                    = new MenuEssences(gameManager);
            menuWeapons.PreviousMenu        = menuEssences;
            menuWeapons.NextMenu            = menuSecondaryItems;
            menuSecondaryItems.PreviousMenu = menuWeapons;
            menuSecondaryItems.NextMenu     = menuEssences;
            menuEssences.PreviousMenu       = menuSecondaryItems;
            menuEssences.NextMenu           = menuWeapons;

            mapDungeon = new ScreenDungeonMap(gameManager);

            GameData.LoadInventory(inventory, true);

            inventory.ObtainAmmo("ammo_ember_seeds");
            inventory.ObtainAmmo("ammo_scent_seeds");
            inventory.ObtainAmmo("ammo_pegasus_seeds");
            inventory.ObtainAmmo("ammo_gale_seeds");
            inventory.ObtainAmmo("ammo_mystery_seeds");

            hud = new HUD(this);
            hud.DynamicHealth = player.Health;

            rewardManager = new RewardManager(this);
            GameData.LoadRewards(rewardManager);
            dropManager = new DropManager(this);
            GameData.LoadDrops(dropManager, rewardManager);

            // Create the script runner.
            scriptRunner = new ScriptRunner(this);

            // Create the room control.
            roomControl = new RoomControl();
            gameManager.PushGameState(roomControl);

            // Load the world.
            //WorldFile worldFile = new WorldFile();
            //world = worldFile.Load("Content/Worlds/temp_world.zwd");

            // Begin the room state.
            if (gameManager.LaunchParameters.Length > 0)
            {
                LoadWorld(gameManager.LaunchParameters[0]);

                if (gameManager.LaunchParameters.Length > 1 && gameManager.LaunchParameters[1] == "-test")
                {
                    // Launch parameters can define player's start position.
                    int startLevel   = Int32.Parse(gameManager.LaunchParameters[2]);
                    int startRoomX   = Int32.Parse(gameManager.LaunchParameters[3]);
                    int startRoomY   = Int32.Parse(gameManager.LaunchParameters[4]);
                    int startPlayerX = Int32.Parse(gameManager.LaunchParameters[5]);
                    int startPlayerY = Int32.Parse(gameManager.LaunchParameters[6]);

                    player.SetPositionByCenter(new Point2I(startPlayerX, startPlayerY) * GameSettings.TILE_SIZE + new Point2I(8, 8));
                    player.MarkRespawn();
                    roomControl.BeginRoom(world.Levels[startLevel].Rooms[startRoomX, startRoomY]);
                }
                else
                {
                    player.SetPositionByCenter(world.StartTileLocation * GameSettings.TILE_SIZE + new Point2I(8, 8));
                    player.MarkRespawn();
                    roomControl.BeginRoom(world.StartRoom);
                }
            }
            else
            {
                //WorldFile worldFile = new WorldFile();
                //world = worldFile.Load("temp_world.zwd");
                LoadWorld(GameDebug.CreateTestWorld());
                player.SetPositionByCenter(world.StartTileLocation * GameSettings.TILE_SIZE + new Point2I(8, 8));
                player.MarkRespawn();
                roomControl.BeginRoom(world.StartRoom);
            }
            roomStateStack = new RoomStateStack(new RoomStateNormal());
            roomStateStack.Begin(this);

            if (!roomControl.Room.IsHiddenFromMap)
            {
                lastRoomOnMap = roomControl.Room;
            }

            AudioSystem.MasterVolume = 0.04f;             // The way David likes it.
        }
示例#37
0
 public FunctionBase(ScriptRunner scriptRunner) : base(scriptRunner)
 {
 }
示例#38
0
        void OpenEvent(object sender, EventArgs e)
        {
            if (categoryTreeView.SelectedNode != null)
            {
                PropertyService.Set("Dialogs.NewProjectDialog.LargeImages", ((RadioButton)ControlDictionary["largeIconsRadioButton"]).Checked);
                PropertyService.Set("Dialogs.NewFileDialog.CategoryViewState", TreeViewHelper.GetViewStateString(categoryTreeView));
                PropertyService.Set("Dialogs.NewFileDialog.LastSelectedCategory", TreeViewHelper.GetPath(categoryTreeView.SelectedNode));
            }
            createdFiles.Clear();
            if (templateListView.SelectedItems.Count == 1)
            {
                if (!AllPropertiesHaveAValue)
                {
                    MessageService.ShowMessage("${res:Dialog.NewFile.FillOutFirstMessage}", "${res:Dialog.NewFile.FillOutFirstCaption}");
                    return;
                }
                TemplateItem item = (TemplateItem)templateListView.SelectedItems[0];

                PropertyService.Set("Dialogs.NewFileDialog.LastSelectedTemplate", item.Template.Name);

                string fileName;
                StringParserPropertyContainer.FileCreation["StandardNamespace"] = "DefaultNamespace";
                if (allowUntitledFiles)
                {
                    fileName = GenerateCurrentFileName();
                }
                else
                {
                    fileName = ControlDictionary["fileNameTextBox"].Text.Trim();
                    if (!FileUtility.IsValidPath(fileName) ||
                        fileName.IndexOf(Path.AltDirectorySeparatorChar) >= 0 ||
                        fileName.IndexOf(Path.DirectorySeparatorChar) >= 0)
                    {
                        MessageService.ShowError(StringParser.Parse("${res:ICSharpCode.SharpDevelop.Commands.SaveFile.InvalidFileNameError}", new StringTagPair("FileName", fileName)));
                        return;
                    }
                    if (Path.GetExtension(fileName).Length == 0)
                    {
                        fileName += Path.GetExtension(item.Template.DefaultName);
                    }
                    fileName = Path.Combine(basePath, fileName);
                    fileName = FileUtility.NormalizePath(fileName);
                    IProject project = ProjectService.CurrentProject;
                    if (project != null)
                    {
                        StringParserPropertyContainer.FileCreation["StandardNamespace"] = CustomToolsService.GetDefaultNamespace(project, fileName);
                    }
                }
                StringParserPropertyContainer.FileCreation["FullName"] = fileName;
                StringParserPropertyContainer.FileCreation["FileName"] = Path.GetFileName(fileName);
                StringParserPropertyContainer.FileCreation["FileNameWithoutExtension"] = Path.GetFileNameWithoutExtension(fileName);
                StringParserPropertyContainer.FileCreation["Extension"] = Path.GetExtension(fileName);
                StringParserPropertyContainer.FileCreation["Path"]      = Path.GetDirectoryName(fileName);

                StringParserPropertyContainer.FileCreation["ClassName"] = GenerateValidClassOrNamespaceName(Path.GetFileNameWithoutExtension(fileName), false);

                // when adding a file to a project (but not when creating a standalone file while a project is open):
                if (ProjectService.CurrentProject != null && !this.allowUntitledFiles)
                {
                    // add required assembly references to the project
                    bool changes = false;
                    foreach (ReferenceProjectItem reference in item.Template.RequiredAssemblyReferences)
                    {
                        IEnumerable <ProjectItem> refs = ProjectService.CurrentProject.GetItemsOfType(ItemType.Reference);
                        if (!refs.Any(projItem => string.Equals(projItem.Include, reference.Include, StringComparison.OrdinalIgnoreCase)))
                        {
                            ReferenceProjectItem projItem = (ReferenceProjectItem)reference.CloneFor(ProjectService.CurrentProject);
                            ProjectService.AddProjectItem(ProjectService.CurrentProject, projItem);
                            changes = true;
                        }
                    }
                    if (changes)
                    {
                        ProjectService.CurrentProject.Save();
                    }
                }

                foreach (FileDescriptionTemplate newfile in item.Template.FileDescriptionTemplates)
                {
                    if (!IsFilenameAvailable(StringParser.Parse(newfile.Name)))
                    {
                        MessageService.ShowError(string.Format("Filename {0} is in use.\nChoose another one", StringParser.Parse(newfile.Name)));                         // TODO : translate
                        return;
                    }
                }
                ScriptRunner scriptRunner = new ScriptRunner();
                foreach (FileDescriptionTemplate newFile in item.Template.FileDescriptionTemplates)
                {
                    FileOperationResult result = FileUtility.ObservedSave(
                        () => {
                        if (!String.IsNullOrEmpty(newFile.BinaryFileName))
                        {
                            SaveFile(newFile, null, newFile.BinaryFileName);
                        }
                        else
                        {
                            SaveFile(newFile, scriptRunner.CompileScript(item.Template, newFile), null);
                        }
                    }, StringParser.Parse(newFile.Name)
                        );
                    if (result != FileOperationResult.OK)
                    {
                        return;
                    }
                }

                DialogResult = DialogResult.OK;

                // raise FileCreated event for the new files.
                foreach (KeyValuePair <string, FileDescriptionTemplate> entry in createdFiles)
                {
                    FileService.FireFileCreated(entry.Key, false);
                }
            }
        }
示例#39
0
        public static string[] Build(Arguments.IBuildArguments buildArguments, Logging.ILog log = null)
        {
            if (log == null)
            {
                log = new Logging.NoLogging();
            }
            if (string.IsNullOrEmpty(buildArguments.ScriptPath))
            {
                buildArguments.ScriptPath = System.Environment.CurrentDirectory;
            }

            if (string.IsNullOrEmpty(buildArguments.DbProviderFactory))
            {
                buildArguments.DbProviderFactory = "System.Data.SqlClient";
            }

            if (string.IsNullOrEmpty(buildArguments.ScriptProcessor))
            {
                buildArguments.ScriptProcessor = typeof(SqlScriptRunner.ScriptProcessing.SqlServerScriptProcessor).FullName;
            }

            if (string.IsNullOrEmpty(buildArguments.VersionParser))
            {
                buildArguments.VersionParser = typeof(SqlScriptRunner.Versioning.VersionDateParser).AssemblyQualifiedName;
            }


            Type t = Type.GetType(buildArguments.VersionParser);

            SqlScriptRunner.Versioning.IParseVersions versionParser =
                (Activator.CreateInstance(t) as
                 SqlScriptRunner.Versioning.IParseVersions);


            SqlScriptRunner.Versioning.Version minVersion = null;
            SqlScriptRunner.Versioning.Version maxVersion = null;

            if (string.IsNullOrEmpty(buildArguments.MinimumVersion))
            {
                minVersion = SqlScriptRunner.Versioning.Version.Min;
            }
            else
            {
                minVersion = versionParser.Parse(buildArguments.MinimumVersion);
            }

            if (string.IsNullOrEmpty(buildArguments.MaximumVersion))
            {
                maxVersion = SqlScriptRunner.Versioning.Version.Max;
            }
            else
            {
                maxVersion = versionParser.Parse(buildArguments.MaximumVersion);
            }
            log.Info("--------------------------------");
            log.Info(string.Format("Min:{0}, Max:{1}, ScriptPath:{2}, Transactional:{4}, DryRun:{5}\r\nConnectionString:{3}", minVersion, maxVersion, buildArguments.ScriptPath, buildArguments.ConnectionString, buildArguments.Transactional, buildArguments.DryRun));
            log.Info("--------------------------------");
            DbConnection connection = null;

            if (!buildArguments.DryRun)
            {
                //make sure we can connect to the database
                DbProviderFactory factory = DbProviderFactories.GetFactory(buildArguments.DbProviderFactory);
                connection = factory.CreateConnection();
                if (connection == null)
                {
                    throw new ArgumentException(
                              "Could not create a connection to the database, via the Provider Factory:" +
                              buildArguments.DbProviderFactory);
                }
                else
                {
                    connection.ConnectionString = buildArguments.ConnectionString;
                    connection.Open();
                }
            }

            SortedList <string, string> Files = SqlScriptRunner.ScriptRunner.ResolveScriptsFromPathAndVersion(buildArguments.ScriptPath, buildArguments.ScriptPattern, buildArguments.Recurse, System.Environment.CurrentDirectory, minVersion, maxVersion, versionParser);

            log.Info(string.Format("Resolved:{0} files.", Files.Count));

            foreach (var file in Files.Keys)
            {
                log.Info(file);
                if (!buildArguments.DryRun)
                {
                    try
                    {
                        log.Info("Executing");
                        string script = System.IO.File.ReadAllText(Files[file]);
                        SqlScriptRunner.ScriptRunner runner = new ScriptRunner(script, null);
                        if (buildArguments.Transactional)
                        {
                            if (connection.State == ConnectionState.Closed)
                            {
                                connection.Open();
                            }
                            System.Data.IDbTransaction transaction = null;
                            if (buildArguments.Transactional)
                            {
                                transaction = connection.BeginTransaction();
                            }
                            try
                            {
                                runner.Execute(connection, transaction);
                                if (buildArguments.Transactional)
                                {
                                    transaction.Commit();
                                }
                                log.Info("Success:" + file);
                            }
                            catch (Exception e)
                            {
                                log.Info("Fail [In Trx:" + buildArguments.Transactional + "]:" + file);
                                log.Fatal(e);
                                if (buildArguments.Transactional)
                                {
                                    transaction.Rollback();
                                }
                                throw;
                            }
                        }
                        else
                        {
                            runner.Execute(connection);
                        }
                    }
                    catch (Exception e)
                    {
                        if (buildArguments.BreakOnError)
                        {
                            throw;
                        }
                        else
                        {
                            log.Debug("There was an error with a script, since BreakOnError is false, we will continue.File:" + file, e);
                        }
                    }
                }
            }
            log.Info("Done Executing");
            return((from f in Files select f.Value).ToArray());
        }
示例#40
0
        /// <summary>
        /// Runs the Powershell Script Engine.
        /// </summary>
        /// <param name="options">The options parameters.</param>
        /// <returns>Exit code</returns>
        public int Run(string[] options)
        {
            Console.OutputEncoding = Encoding.ASCII;
            FileVersionInfo fvi = GetFileVersionInfo();

            try
            {
                NetworkCredential credential = null;
                int          version         = 2;
                string       domain          = null;
                string       userName        = null;
                SecureString password        = null;
                string       script          = null;
                bool         isElevated      = false;
                int          schedule        = -1;
                bool         passthrough     = false;
                bool         hash            = false;
                bool         nologo          = false;
                StageType    stage           = StageType.None;

                // Gets CLI arguments.
                for (int i = 0; i < options.Length; i++)
                {
                    string arg = options[i];
                    if (arg.StartsWith("-"))
                    {
                        switch (arg.ToLowerInvariant())
                        {
                        case "-hash":
                            password = GetArgumentValue(options, ref i).ConvertToSecureString();
                            hash     = true;
                            break;

                        case "-script":
                            script = GetArgumentValue(options, ref i);
                            break;

                        case "-version":
                            version = Convert.ToInt32(GetArgumentValue(options, ref i));
                            break;

                        case "-domain":
                            domain = StringCipher.Decrypt(GetArgumentValue(options, ref i), GetUniqueIdentifier());
                            break;

                        case "-username":
                            userName = StringCipher.Decrypt(GetArgumentValue(options, ref i), GetUniqueIdentifier());
                            break;

                        case "-password":
                            password = StringCipher.Decrypt(GetArgumentValue(options, ref i), GetUniqueIdentifier()).ConvertToSecureString();
                            break;

                        case "-elevated":
                            isElevated = true;
                            break;

                        case "-schedule":
                            double s = Convert.ToDouble(GetArgumentValue(options, ref i), CultureInfo.InvariantCulture) * 60 * 1000;
                            if (s > Int32.MaxValue)
                            {
                                schedule = Int32.MaxValue;
                            }
                            else if (s == 0)
                            {
                                schedule = 500;
                            }
                            else
                            {
                                schedule = (int)s;
                            }
                            break;

                        case "-pid":
                            _processId  = Convert.ToInt32(GetArgumentValue(options, ref i));
                            passthrough = true;
                            break;

                        case "-stage":
                            stage = (StageType)Enum.Parse(typeof(StageType), GetArgumentValue(options, ref i));
                            break;

                        case "-silent":
                            _silent = true;
                            break;

                        case "-debug":
                            _debug = true;
                            break;

                        case "-nologo":
                            nologo = true;
                            break;

                        case "-help":
                            PrintHeader();
                            PrintNotice();
                            return(0);

                        default:
                            PrintHeader();
                            Console.WriteLine("Wrong argument: {0}", arg);
                            PrintWarning();
                            return(EXITCODE_KO);
                        }
                    }
                }

                Log("START " + fvi.ProductName.ToUpperInvariant() + " v" + fvi.FileVersion + " WITH PID #" + Process.GetCurrentProcess().Id);
                Log("ARGS       : " + string.Join(" ", options));

                // Script parameters is requiered !
                if (string.IsNullOrEmpty(script) && !passthrough && !hash)
                {
                    PrintHeader();
                    Console.WriteLine("Script parameter is required !");
                    PrintWarning();
                    return(EXITCODE_KO);
                }

                // Show Copyright banner.
                if (!nologo)
                {
                    PrintHeader();
                }

                // Hash password.
                if (hash)
                {
                    // Get system UID
                    string k = StringCipher.Encrypt(password.ConvertToUnsecureString(), GetUniqueIdentifier());
                    Console.WriteLine(k);
                    return(EXITCODE_OK);
                }

                // Gets user credentials
                if (!string.IsNullOrEmpty(userName))
                {
                    // WTF! .Net 3.5 does not implements the creation of ICredentials with a SecureString. MS are you serious ?
                    if (!string.IsNullOrEmpty(domain))
                    {
                        credential = new NetworkCredential(userName, password.ConvertToUnsecureString(), domain);
                    }
                    else
                    {
                        credential = new NetworkCredential(userName, password.ConvertToUnsecureString());
                    }
                }

                // Check if the current process already runs with elevated privileges
                WindowsIdentity  identity  = WindowsIdentity.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                if (isElevated)
                {
                    if (UAC.IsProcessElevated)
                    {
                        // removes elevated mode
                        options    = GetFilteredParameters(options, new[] { "-elevated" }, null).ToArray();
                        isElevated = false;
                        Log("UAC        : Elevation not needed");
                    }
                    else
                    {
                        Log("UAC        : Need elevation");
                    }
                }

                // Encode pipeline for use in PS if any.
                if (IsPipedInput() && !passthrough)
                {
                    string pipe = Console.In.ReadToEnd();
                    if (!string.IsNullOrEmpty(pipe))
                    {
                        Log("READ PIPE  :\n" + pipe);
                        StringBuilder s = new StringBuilder();
                        s.AppendFormat("\"{0}\"", Convert.ToBase64String(Encoding.Unicode.GetBytes(pipe)));
                        s.Append("|%{[System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($_))}|" + script);
                        script = s.ToString();
                    }
                }

                // Stage Logic
                if (stage == StageType.None)
                {
                    if (!string.IsNullOrEmpty(userName))
                    {
                        stage = StageType.Credential;
                    }
                    else if (isElevated)
                    {
                        stage = StageType.Elevated;
                    }
                    else
                    {
                        stage = StageType.PowerShell;
                    }
                }

                // Starts named pipes server for communication with the child process
                NamedPipeServer <String> server = null;
                if (stage != StageType.PowerShell)
                {
                    if (!passthrough)
                    {
                        server = GetNamePipeServer(script, _processId);
                        server.Start();
                    }
                }

                // Starts the child processes loop.
                do
                {
                    try
                    {
                        Log("STAGE      : " + ((int)stage).ToString() + " - " + stage.ToString());
                        Log("PASSTHRU   : " + passthrough.ToString());
                        switch (stage)
                        {
                        case StageType.Credential:
                        {
                            // Construct child process arguments
                            string[]      switchParamToRemoves  = { "-help" };
                            string[]      keyPairParamToRemoves = { "-domain", "-username", "-password", "-script", "-schedule", "-stage" };
                            List <string> param = GetFilteredParameters(options, switchParamToRemoves, keyPairParamToRemoves);

                            // Add PID identifier for named pipe communication
                            if (!passthrough)
                            {
                                param.Add("-pid");
                                param.Add(_processId.ToString());
                            }

                            Log("ARGS CHILD : " + string.Join(" ", param.ToArray()));

                            // Starts child process of myself with credentials: .Net Process class failed to start a process with custom credentials when running under LocalSystem account.
                            if (WindowsIdentity.GetCurrent().Name.ToLowerInvariant() == "nt authority\\system")
                            {
                                RunSelfProcessInLocalSystem(param, credential);
                            }
                            else
                            {
                                RunSelfProcess(param, false, credential);
                            }

                            Thread.Sleep(1000);

                            break;
                        }

                        case StageType.Elevated:
                        {
                            // Construct child process arguments
                            string[]      switchParamToRemoves  = { "-elevated", "-help" };
                            string[]      keyPairParamToRemoves = { "-script", "-schedule", "-stage" };
                            List <string> param = GetFilteredParameters(options, switchParamToRemoves, keyPairParamToRemoves);

                            // Add PID identifier
                            if (!passthrough)
                            {
                                param.Add("-pid");
                                param.Add(_processId.ToString());
                            }

                            Log("ARGS CHILD : " + string.Join(" ", param.ToArray()));

                            // Starts child process of myself with elevated privileges
                            RunSelfProcess(param, isElevated, credential);
                            Thread.Sleep(1000);

                            break;
                        }

                        case StageType.PowerShell:
                        {
                            // Starts named pipes client for communication with the parent process.
                            NamedPipeClient <String> client = null;
                            if (passthrough)
                            {
                                client = GetNamedPipeClientAndWaitForConnection(_processId, out script);
                            }

                            // Runs the PS process
                            //WindowsStationAndDesktop.GrantAccess(credential.UserName);

                            using (new PrivilegeEnabler(Process.GetCurrentProcess(), Privilege.AssignPrimaryToken, Privilege.IncreaseQuota, Privilege.TrustedComputerBase))
                                using (ScriptRunner ps = new ScriptRunner(ScriptEngine.Language.PowerShell, credential, isElevated, script))
                                {
                                    ps.OutputReceived += (o, e) =>
                                    {
                                        if (passthrough)
                                        {
                                            client.PushMessage(e.Data);
                                        }
                                        else
                                        {
                                            Console.WriteLine(e.Data);
                                        }

                                        Log("PS         : " + e.Data);
                                    };
                                    ps.ProcessExited += (o, e) =>
                                    {
                                        ExitCode = e.ExitCode;
                                        if (passthrough)
                                        {
                                            client.PushMessage(NAMEDPIPES_EXITCODE + e.ExitCode);
                                        }
                                    };

                                    ps.Run(new[] { "-V", version.ToString() });
                                }

                            Thread.Sleep(1000);

                            if (passthrough)
                            {
                                client.Stop();
                            }

                            break;
                        }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (!_silent)
                        {
                            Console.WriteLine("ERROR: {0}", ex.ToString().Replace(Environment.NewLine, " "));
                        }
                        Log("ERROR      : " + ex.ToString());
                    }

                    // Wait the schedule time
                    if (schedule != -1)
                    {
                        Thread.Sleep(schedule);
                    }
                } while (schedule != -1);

                // Stops the pipe server
                if (server != null && !passthrough)
                {
                    server.Stop();
                }
            }
            catch (Exception ex)
            {
                if (!_silent)
                {
                    Console.WriteLine("ERROR: {0}", ex.ToString().Replace(Environment.NewLine, " "));
                }
                Log("ERROR      : " + ex.ToString());
            }

            Log("EXIT CODE  : " + ExitCode);
            Log("STOP " + fvi.ProductName.ToUpperInvariant() + " v" + fvi.FileVersion + " WITH PID #" + Process.GetCurrentProcess().Id);

            return(ExitCode);
        }
示例#41
0
文件: Loader.cs 项目: Alxandr/RunJS
 /// <summary>
 /// Initializes a new instance of the <see cref="LoaderConstructor"/> class.
 /// </summary>
 /// <param name="runner">The runner.</param>
 public LoaderConstructor(ScriptRunner runner)
     : base(runner.Engine.Function.Prototype, "Loader", runner.Engine.Object.InstancePrototype)
 {
     this.runner = runner;
 }
示例#42
0
 public void StoreScript(Guid botId, ScriptRunner<object> script)
 {
     _scriptCache.AddOrUpdate(botId, script, (a, b) => script);
 }
示例#43
0
 public Roslyn(string code)
 {
     _code   = code;
     _script = CSharpScript.Create <int>(code, ScriptOptions.Default);
     _runner = _script.CreateDelegate();
 }
        public void Generate(IGeneratorArguments input)
        {
            Encoding encoding;

            //auto-convert input encoding to the correct type
            if (_config.InputEncoding != FileEncoding.Default)
            {
                encoding = _config.InputEncoding == FileEncoding.Ascii ? Encoding.ASCII : Encoding.UTF8;
                using (var r = new StreamReader(input.InputPath, detectEncodingFromByteOrderMarks: true))
                {
                    if (encoding.EncodingName != r.CurrentEncoding.EncodingName)
                    {
                        string text = r.ReadToEnd();
                        r.Dispose();
                        File.WriteAllText(input.InputPath, text, encoding);
                    }
                }
            }

            encoding = _config.OutputEncoding == FileEncoding.Ascii ? Encoding.ASCII : Encoding.UTF8;

            //Couple of assertions about PowerShell
            if (_config.Script.Type == ScriptEngine.Language.PowerShell &&
                (_config.StandardInput.Redirect || _config.Arguments.Length > 0))
            {
                throw new ApplicationException(
                          @"Currently PowerShell integration does not support input streams or arguments.
Primarily this is due to circumventing the script-signing requirements. By 
using the '-Command -' argument we avoid signing or setting ExecutionPolicy.");
            }

            using (DebuggingOutput debug = new DebuggingOutput(_config.Debug, input.WriteLine))
            {
                debug.WriteLine("ConfigDir = {0}", _config.BaseDirectory);
                input.ConfigDir = _config.BaseDirectory;

                //Inject arguments into the script
                string script = input.ReplaceVariables(Check.NotNull(_config.Script).Text.Trim());

                if (!String.IsNullOrEmpty(_config.Script.Include))
                {
                    script = File.ReadAllText(CreateFullPath(_config.Script.Include));
                }
                if (_config.Script.Type == ScriptEngine.Language.Exe)
                {
                    script = CreateFullPath(script);
                }

                StringWriter swOutput = new StringWriter();

                List <string> arguments = new List <string>();
                foreach (GeneratorArgument arg in _config.Arguments)
                {
                    arguments.Add(input.ReplaceVariables(arg.Text ?? String.Empty));
                }

                debug.WriteLine("Prepared Script:{0}{1}{0}{2}{0}{1}",
                                Environment.NewLine,
                                "---------------------------------------------",
                                script
                                );

                using (ScriptRunner scriptEngine = new ScriptRunner(_config.Script.Type, script))
                {
                    IRunner runner = scriptEngine;
                    if (input.AllowAppDomains && _config.Script.InvokeAssembly)
                    {
                        runner = AssemblyRunnerCache.Fetch(scriptEngine.ScriptEngine.Executable);
                        arguments.InsertRange(0, scriptEngine.ScriptArguments);
                    }

                    runner.WorkingDirectory = _config.BaseDirectory;
                    string lastErrorMessage           = null;
                    ProcessOutputEventHandler handler =
                        delegate(object o, ProcessOutputEventArgs args)
                    {
                        if (args.Error)
                        {
                            input.WriteLine(lastErrorMessage = args.Data);
                        }
                        else if (_config.StandardOut != null)
                        {
                            debug.WriteLine("std::out: {0}", args.Data);
                            swOutput.WriteLine(args.Data);
                        }
                        else
                        {
                            input.WriteLine(args.Data);
                        }
                    };

                    int exitCode = -1;
                    debug.WriteLine("Executing {0} {1}", runner, ArgumentList.EscapeArguments(arguments.ToArray()));
                    try
                    {
                        runner.OutputReceived += handler;
                        if (_config.StandardInput.Redirect)
                        {
                            exitCode = runner.Run(new StringReader(File.ReadAllText(input.InputPath)), arguments.ToArray());
                        }
                        else
                        {
                            exitCode = runner.Run(arguments.ToArray());
                        }
                    }
                    finally
                    {
                        debug.WriteLine("Exited = {0}", exitCode);
                        runner.OutputReceived -= handler;
                    }

                    if (_config.StandardOut != null)
                    {
                        string target = Path.ChangeExtension(input.InputPath, _config.StandardOut.Extension);
                        using (TempFile file = TempFile.FromExtension(_config.StandardOut.Extension))
                        {
                            File.WriteAllText(file.TempPath, swOutput.ToString(), encoding);
                            File.Copy(file.TempPath, target, true);
                            input.AddOutputFile(target);
                        }
                    }

                    if (exitCode != 0)
                    {
                        string message = "The script returned a non-zero result: " + exitCode;
                        input.WriteLine(message);
                        throw new ApplicationException(String.IsNullOrEmpty(lastErrorMessage) ? message : lastErrorMessage);
                    }
                }

                EnumOutputFiles(input, input.AddOutputFile);
            }
        }
示例#45
0
 private void App_OnStartup(object sender, StartupEventArgs e)
 {
     ScriptRunner.Run(new Script());
 }
 public void TestToString()
 {
     using (ScriptRunner runner = new ScriptRunner(ScriptEngine.Language.Exe, @"cmd.exe"))
         Assert.AreEqual(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "cmd.exe"), runner.ToString().Trim());
 }
示例#47
0
    static async Task Main()
    {
        const string tablePrefix = "";

        Console.Title = "Samples.MultiTenant.Receiver";

        var endpointConfiguration = new EndpointConfiguration("Samples.MultiTenant.Receiver");

        endpointConfiguration.LimitMessageProcessingConcurrencyTo(1);
        endpointConfiguration.UseTransport <LearningTransport>();

        #region DisablingOutboxCleanup

        var outboxSettings = endpointConfiguration.EnableOutbox();
        outboxSettings.DisableCleanup();

        #endregion

        var persistence = endpointConfiguration.UsePersistence <SqlPersistence>();
        persistence.SqlDialect <SqlDialect.MsSqlServer>();

        #region ConnectionFactory

        persistence.MultiTenantConnectionBuilder(tenantIdHeaderName: "tenant_id",
                                                 buildConnectionFromTenantData: tenantId =>
        {
            var connectionString = Connections.GetForTenant(tenantId);
            return(new SqlConnection(connectionString));
        });

        #endregion

        persistence.SubscriptionSettings().DisableCache();
        persistence.TablePrefix(tablePrefix);

        var pipeline = endpointConfiguration.Pipeline;

        pipeline.Register(new StoreTenantIdBehavior(), "Stores tenant ID in the session");
        pipeline.Register(new PropagateTenantIdBehavior(), "Propagates tenant ID to outgoing messages");

        var startableEndpoint = await Endpoint.Create(endpointConfiguration)
                                .ConfigureAwait(false);

        using (var connection = new SqlConnection(Connections.TenantA))
            using (var receiverDataContext = new ReceiverDataContext(connection))
            {
                await receiverDataContext.Database.EnsureCreatedAsync();
            }

        using (var connection = new SqlConnection(Connections.TenantB))
            using (var receiverDataContext = new ReceiverDataContext(connection))
            {
                await receiverDataContext.Database.EnsureCreatedAsync();
            }

        var dialect         = new SqlDialect.MsSqlServer();
        var scriptDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "NServiceBus.Persistence.Sql", "MsSqlServer");

        #region CreateSchema

        await ScriptRunner.Install(dialect, tablePrefix, () => new SqlConnection(Connections.TenantA), scriptDirectory,
                                   shouldInstallOutbox : true,
                                   shouldInstallSagas : true,
                                   shouldInstallSubscriptions : false,
                                   shouldInstallTimeouts : false);

        await ScriptRunner.Install(dialect, tablePrefix, () => new SqlConnection(Connections.TenantB), scriptDirectory,
                                   shouldInstallOutbox : true,
                                   shouldInstallSagas : true,
                                   shouldInstallSubscriptions : false,
                                   shouldInstallTimeouts : false);

        #endregion

        var endpointInstance = await startableEndpoint.Start()
                               .ConfigureAwait(false);

        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
        if (endpointInstance != null)
        {
            await endpointInstance.Stop()
            .ConfigureAwait(false);
        }
    }
 private void button1_Click(object sender, EventArgs e)
 {
     PAS.AutoTest.ScriptRunner.ScriptRunner sr = new ScriptRunner();
     sr.ExecuteScript(this.richTextBox1.Text, @"D:\test.iod");
 }
示例#49
0
        public void TabWindow()
        {
            ScriptRunner.RunScriptAsync(new ParameterDic()
            {
                { "StartupPath", OpenPath },
                { "GlobalEvents", _events },
                { "WindowManager", _windowManager },
                { "EnableDrag", _enableDrag },
                { "EnableDrop", _enableDrop },
                { "EnableContextMenu", _enableContextMenu },
                { "EnableBookmark", _enableBookmark },
                { "EnableMultiSelect", _enableMultiSelect },
                { "EnableTabsWhenOneTab", _showTabsWhenOneTab }
            },
                                        IOScriptCommands.ExplorerNewTabWindow(_profiles, RootModels.ToArray(), "{TabbedExplorer}"));


            //var tabVM = new TabbedExplorerViewModel(_windowManager, _events);
            //tabVM.Initializer = new ScriptCommandInitializer()
            //{
            //    Events = _events,
            //    WindowManager = _windowManager,
            //    OnModelCreated = ScriptCommands.RunScriptCommand("{OnModelCreated}"),
            //    OnViewAttached = ScriptCommands.RunScriptCommand("{OnViewAttached}"),
            //    StartupParameters = new FileExplorer.ParameterDic()
            //    {
            //        {"TabbedExplorer", tabVM },
            //        {"Profiles", _profiles },
            //        {"RootDirectories", RootModels.ToArray() },
            //        {"OnModelCreated", IOInitializeHelpers.Explorer_Initialize_Default },
            //        {"OnViewAttached", UIScriptCommands.ExplorerGotoStartupPathOrFirstRoot() },
            //    }
            //};


            //_windowManager.ShowWindow(tabVM);


            //ScriptRunner.RunScriptAsync(new ParameterDic() {
            //        { "StartupPath", OpenPath },
            //        { "GlobalEvents", _events },
            //        { "WindowManager", _windowManager },
            //        { "EnableDrag", _enableDrag },
            //        { "EnableDrop", _enableDrop },
            //        { "EnableMultiSelect", _enableMultiSelect},
            //    },
            //   IOScriptCommands.ExplorerShow(_profiles, RootModels.ToArray()));


            //var profiles = new IProfile[] {
            //    _profileEx, _profileSkyDrive, _profileDropBox, _profileGoogleDrive
            //};

            //var initializer = getInitializer(_windowManager, _events, RootModels.ToArray(),
            //    ExplorerInitializers.Parameter(new FileListParameters() { ViewMode = "Icon", ItemSize = 100 }),
            //    ExplorerInitializers.Parameter(new ExplorerParameters() { UIScale = 1.1f, FileListSize = "3*", NavigationSize = 45 }),
            //    new BasicParamInitalizers(_expandRootDirectories, _enableMultiSelect, _enableDrag, _enableDrop),
            //    new ColumnInitializers(),
            //    new ScriptCommandsInitializers(_windowManager, _events, profiles),
            //    new ToolbarCommandsInitializers(_windowManager));

            //var initializer =

            //var tabVM = new TabbedExplorerViewModel(initializer);

            //var windowManager = new TabbedAppWindowManager(tabVM);


            //_windowManager.ShowWindow(tabVM);
        }
 private void button3_Click(object sender, EventArgs e)
 {
     PAS.AutoTest.ScriptRunner.ScriptRunner sr = new ScriptRunner();
     sr.Run(@"D:\test.cod", @"D:\test.iod", 1000);
 }
示例#51
0
 private void App_OnStartup(object sender, StartupEventArgs e)
 {
     // Note: EsapiEssentials and EsapiEssentials.PluginRunner must be referenced,
     // as well as the project that contains the Script class
     ScriptRunner.Run(new Script());
 }
示例#52
0
    public static void Run(Notebook notebook, ScriptEnv env, ScriptRunner runner, Ast.ImportXlsStmt stmt)
    {
        var importer = new ImportXlsStmtRunner(notebook, env, runner, stmt);

        SqlUtil.WithTransaction(notebook, importer.Import);
    }
 public ExecutionContext(ScriptRunner scriptRunner)
 {
     ScriptRunner = scriptRunner;
 }
示例#54
0
    private ImportXlsStmtRunner(Notebook notebook, ScriptEnv env, ScriptRunner runner, Ast.ImportXlsStmt stmt)
    {
        _notebook = notebook;
        _env      = env;
        _runner   = runner;
        _stmt     = stmt;

        _filePath = _runner.EvaluateExpr <string>(_stmt.FilenameExpr, _env);
        if (!File.Exists(_filePath))
        {
            throw new Exception($"The specified XLS/XLSX file was not found: \"{_filePath}\"");
        }

        if (_stmt.WhichSheetExpr != null)
        {
            _whichSheet = _runner.EvaluateExpr(_stmt.WhichSheetExpr, _env);
        }

        int?index;

        foreach (var option in _stmt.OptionsList.GetOptionKeys())
        {
            switch (option)
            {
            case "FIRST_ROW":
                _firstRowIndex = _stmt.OptionsList.GetOptionInt(option, _runner, _env, 1, minValue: 1) - 1;
                break;

            case "LAST_ROW":
                var lastRowNum = _stmt.OptionsList.GetOptionInt(option, _runner, _env, 0, minValue: 0);
                if (lastRowNum == 0)
                {
                    _lastRowIndex = null;
                }
                else
                {
                    _lastRowIndex = lastRowNum - 1;
                }
                break;

            case "FIRST_COLUMN":
                index = XlsUtil.ColumnRefToIndex(_stmt.OptionsList.GetOption <object>(option, _runner, _env, null));
                if (index.HasValue)
                {
                    _firstColumnIndex = index.Value;
                }
                else
                {
                    throw new Exception($"The {option} option must be a valid column number or string.");
                }
                break;

            case "LAST_COLUMN":
                var lastColumnValue = _stmt.OptionsList.GetOption <object>(option, _runner, _env, null);
                if (lastColumnValue is long b && b == 0)
                {
                    _lastColumnIndex = null;
                    break;
                }
                index = XlsUtil.ColumnRefToIndex(lastColumnValue);
                if (index.HasValue)
                {
                    _lastColumnIndex = index.Value;
                }
                else
                {
                    throw new Exception($"The {option} option must be a valid column number or string.");
                }
                break;

            case "HEADER_ROW":
                _headerRow = _stmt.OptionsList.GetOptionBool(option, _runner, _env, true);
                break;

            case "TRUNCATE_EXISTING_TABLE":
                _truncateExistingTable = _stmt.OptionsList.GetOptionBool(option, _runner, _env, false);
                break;

            case "TEMPORARY_TABLE":
                _temporaryTable = _stmt.OptionsList.GetOptionBool(option, _runner, _env, false);
                break;

            case "IF_CONVERSION_FAILS":
                _ifConversionFails = (IfConversionFails)_stmt.OptionsList.GetOptionLong(
                    option, _runner, _env, 1, minValue: 1, maxValue: 3);
                break;

            case "STOP_AT_FIRST_BLANK_ROW":
                _stopAtFirstBlankRow = _stmt.OptionsList.GetOptionBool(option, _runner, _env, true);
                break;

            case "BLANK_VALUES":
                _blankValuesMethod = (BlankValuesOption)_stmt.OptionsList.GetOptionLong(
                    option, _runner, _env, 2, minValue: 1, maxValue: 3);
                break;

            default:
                throw new Exception($"\"{option}\" is not a recognized option name.");
            }
        }
    }
示例#55
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AddScriptTriggerPage"/> class.
        /// </summary>
        /// <param name="scriptRunner">Script runner to add trigger to.</param>
        public AddScriptTriggerPage(ScriptRunner scriptRunner)
        {
            _scriptRunner = scriptRunner;

            Title = "Add Trigger";

            var enabledProbes = _scriptRunner.Probe.Protocol.Probes.Where(p => p != _scriptRunner.Probe && p.Enabled).ToArray();

            if (!enabledProbes.Any())
            {
                Content = new Label {
                    Text = "No enabled probes. Please enable them before creating triggers.", FontSize = 20
                };

                return;
            }

            var contentLayout = new StackLayout
            {
                Orientation     = StackOrientation.Vertical,
                VerticalOptions = LayoutOptions.FillAndExpand
            };

            var probeLabel = new Label {
                Text = "Probe:", FontSize = 20
            };

            Picker probePicker = new Picker {
                Title = "Select Probe", HorizontalOptions = LayoutOptions.FillAndExpand
            };

            foreach (Probe enabledProbe in enabledProbes)
            {
                probePicker.Items.Add(enabledProbe.DisplayName);
            }

            contentLayout.Children.Add(new StackLayout
            {
                Orientation       = StackOrientation.Horizontal,
                HorizontalOptions = LayoutOptions.FillAndExpand,
                Children          = { probeLabel, probePicker }
            });

            StackLayout triggerDefinitionLayout = new StackLayout
            {
                Orientation     = StackOrientation.Vertical,
                VerticalOptions = LayoutOptions.Start
            };

            contentLayout.Children.Add(triggerDefinitionLayout);

            Switch     changeSwitch         = new Switch();
            Switch     regexSwitch          = new Switch();
            Switch     fireRepeatedlySwitch = new Switch();
            TimePicker startTimePicker      = new TimePicker {
                HorizontalOptions = LayoutOptions.FillAndExpand
            };
            TimePicker endTimePicker = new TimePicker {
                HorizontalOptions = LayoutOptions.FillAndExpand
            };

            probePicker.SelectedIndexChanged += (o, e) =>
            {
                _selectedProbe         = null;
                _selectedDatumProperty = null;
                _conditionValue        = null;

                triggerDefinitionLayout.Children.Clear();

                if (probePicker.SelectedIndex < 0)
                {
                    return;
                }

                _selectedProbe = enabledProbes[probePicker.SelectedIndex];

                PropertyInfo[] datumProperties = _selectedProbe.DatumType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttributes <ProbeTriggerProperty>().Any()).ToArray();

                if (datumProperties.Length == 0)
                {
                    return;
                }

                #region datum property picker
                Label datumPropertyLabel = new Label
                {
                    Text     = "Property:",
                    FontSize = 20
                };

                Picker datumPropertyPicker = new Picker {
                    Title = "Select Datum Property", HorizontalOptions = LayoutOptions.FillAndExpand
                };
                foreach (PropertyInfo datumProperty in datumProperties)
                {
                    var triggerProperty = datumProperty.GetCustomAttributes <ProbeTriggerProperty>().First();
                    datumPropertyPicker.Items.Add(triggerProperty.Name ?? datumProperty.Name);
                }

                triggerDefinitionLayout.Children.Add(new StackLayout
                {
                    Orientation       = StackOrientation.Horizontal,
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    Children          = { datumPropertyLabel, datumPropertyPicker }
                });
                #endregion

                #region condition picker (same for all datum types)
                Label conditionLabel = new Label
                {
                    Text     = "Condition:",
                    FontSize = 20
                };

                Picker conditionPicker = new Picker {
                    Title = "Select Condition", HorizontalOptions = LayoutOptions.FillAndExpand
                };
                TriggerValueCondition[] conditions = Enum.GetValues(typeof(TriggerValueCondition)) as TriggerValueCondition[];
                foreach (TriggerValueCondition condition in conditions)
                {
                    conditionPicker.Items.Add(condition.ToString());
                }

                conditionPicker.SelectedIndexChanged += (oo, ee) =>
                {
                    if (conditionPicker.SelectedIndex < 0)
                    {
                        return;
                    }

                    _selectedCondition = conditions[conditionPicker.SelectedIndex];
                };

                triggerDefinitionLayout.Children.Add(new StackLayout
                {
                    Orientation       = StackOrientation.Horizontal,
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    Children          = { conditionLabel, conditionPicker }
                });
                #endregion

                #region condition value for comparison, based on selected datum property -- includes change calculation (for double datum) and regex (for string datum)
                StackLayout conditionValueStack = new StackLayout
                {
                    Orientation       = StackOrientation.Vertical,
                    HorizontalOptions = LayoutOptions.FillAndExpand
                };

                triggerDefinitionLayout.Children.Add(conditionValueStack);

                datumPropertyPicker.SelectedIndexChanged += (oo, ee) =>
                {
                    _selectedDatumProperty = null;
                    _conditionValue        = null;

                    conditionValueStack.Children.Clear();

                    if (datumPropertyPicker.SelectedIndex < 0)
                    {
                        return;
                    }

                    _selectedDatumProperty = datumProperties[datumPropertyPicker.SelectedIndex];

                    ProbeTriggerProperty datumTriggerAttribute = _selectedDatumProperty.GetCustomAttribute <ProbeTriggerProperty>();

                    View conditionValueStackView = null;
                    bool allowChangeCalculation  = false;
                    bool allowRegularExpression  = false;

                    if (datumTriggerAttribute is ListProbeTriggerProperty)
                    {
                        Picker conditionValuePicker = new Picker {
                            Title = "Select Condition Value", HorizontalOptions = LayoutOptions.FillAndExpand
                        };
                        object[] items = (datumTriggerAttribute as ListProbeTriggerProperty).Items;
                        foreach (object item in items)
                        {
                            conditionValuePicker.Items.Add(item.ToString());
                        }

                        conditionValuePicker.SelectedIndexChanged += (ooo, eee) =>
                        {
                            if (conditionValuePicker.SelectedIndex < 0)
                            {
                                return;
                            }

                            _conditionValue = items[conditionValuePicker.SelectedIndex];
                        };

                        conditionValueStackView = conditionValuePicker;
                    }
                    else if (datumTriggerAttribute is DoubleProbeTriggerProperty)
                    {
                        Entry entry = new Entry
                        {
                            Keyboard          = Keyboard.Numeric,
                            HorizontalOptions = LayoutOptions.FillAndExpand
                        };

                        entry.TextChanged += (ooo, eee) =>
                        {
                            double value;
                            if (double.TryParse(eee.NewTextValue, out value))
                            {
                                _conditionValue = value;
                            }
                        };

                        conditionValueStackView = entry;
                        allowChangeCalculation  = true;
                    }
                    else if (datumTriggerAttribute is StringProbeTriggerProperty)
                    {
                        Entry entry = new Entry
                        {
                            Keyboard          = Keyboard.Default,
                            HorizontalOptions = LayoutOptions.FillAndExpand
                        };

                        entry.TextChanged += (ooo, eee) => _conditionValue = eee.NewTextValue;

                        conditionValueStackView = entry;
                        allowRegularExpression  = true;
                    }
                    else if (datumTriggerAttribute is BooleanProbeTriggerProperty)
                    {
                        Switch booleanSwitch = new Switch();

                        booleanSwitch.Toggled += (ooo, eee) => _conditionValue = eee.Value;

                        conditionValueStackView = booleanSwitch;
                    }

                    Label conditionValueStackLabel = new Label
                    {
                        Text     = "Value:",
                        FontSize = 20
                    };

                    conditionValueStack.Children.Add(new StackLayout
                    {
                        Orientation       = StackOrientation.Horizontal,
                        HorizontalOptions = LayoutOptions.FillAndExpand,
                        Children          = { conditionValueStackLabel, conditionValueStackView }
                    });

                    #region change calculation
                    if (allowChangeCalculation)
                    {
                        Label changeLabel = new Label
                        {
                            Text     = "Change:",
                            FontSize = 20
                        };

                        changeSwitch.IsToggled = false;

                        conditionValueStack.Children.Add(new StackLayout
                        {
                            Orientation       = StackOrientation.Horizontal,
                            HorizontalOptions = LayoutOptions.FillAndExpand,
                            Children          = { changeLabel, changeSwitch }
                        });
                    }
                    #endregion

                    #region regular expression
                    if (allowRegularExpression)
                    {
                        Label regexLabel = new Label
                        {
                            Text     = "Regular Expression:",
                            FontSize = 20
                        };

                        regexSwitch.IsToggled = false;

                        conditionValueStack.Children.Add(new StackLayout
                        {
                            Orientation       = StackOrientation.Horizontal,
                            HorizontalOptions = LayoutOptions.FillAndExpand,
                            Children          = { regexLabel, regexSwitch }
                        });
                    }
                    #endregion
                };

                datumPropertyPicker.SelectedIndex = 0;
                #endregion

                #region fire repeatedly
                Label fireRepeatedlyLabel = new Label
                {
                    Text     = "Fire Repeatedly:",
                    FontSize = 20
                };

                fireRepeatedlySwitch.IsToggled = false;

                triggerDefinitionLayout.Children.Add(new StackLayout
                {
                    Orientation       = StackOrientation.Horizontal,
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    Children          = { fireRepeatedlyLabel, fireRepeatedlySwitch }
                });
                #endregion

                #region start/end times
                Label startTimeLabel = new Label
                {
                    Text     = "Start Time:",
                    FontSize = 20
                };

                startTimePicker.Time = new TimeSpan(0, 0, 0);

                triggerDefinitionLayout.Children.Add(new StackLayout
                {
                    Orientation       = StackOrientation.Horizontal,
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    Children          = { startTimeLabel, startTimePicker }
                });

                Label endTimeLabel = new Label
                {
                    Text     = "End Time:",
                    FontSize = 20
                };

                endTimePicker.Time = new TimeSpan(23, 59, 59);

                triggerDefinitionLayout.Children.Add(new StackLayout
                {
                    Orientation       = StackOrientation.Horizontal,
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    Children          = { endTimeLabel, endTimePicker }
                });
                #endregion
            };

            probePicker.SelectedIndex = 0;

            Button okButton = new Button
            {
                Text            = "OK",
                FontSize        = 20,
                VerticalOptions = LayoutOptions.Start
            };

            okButton.Clicked += async(o, e) =>
            {
                try
                {
                    _scriptRunner.Triggers.Add(new Probes.User.Scripts.Trigger(_selectedProbe, _selectedDatumProperty, _selectedCondition, _conditionValue, changeSwitch.IsToggled, fireRepeatedlySwitch.IsToggled, regexSwitch.IsToggled, startTimePicker.Time, endTimePicker.Time));
                    await Navigation.PopAsync();
                }
                catch (Exception ex)
                {
                    await SensusServiceHelper.Get().FlashNotificationAsync($"Failed to add trigger:  {ex.Message}");

                    SensusServiceHelper.Get().Logger.Log($"Failed to add trigger:  {ex.Message}", LoggingLevel.Normal, GetType());
                }
            };

            contentLayout.Children.Add(okButton);

            Content = new ScrollView
            {
                Content = contentLayout
            };
        }
示例#56
0
 public override void Initialize(ScriptRunner runner)
 {
     _expression = runner.GetNode(NodeData.Expression.NodeId);
     _true       = runner.GetNode(NodeData.True.NodeId);
     _false      = runner.GetNode(NodeData.False.NodeId);
 }
示例#57
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 async void MenuItemCallback(object sender, EventArgs e)
 {
     await ScriptRunner.RunScripts(LastSelectedScripts);
 }
 public ConstantWrapperContext(ScriptRunner scriptRunner, VarBase constant) : base(scriptRunner)
 {
     Constant = constant;
 }
示例#59
0
 public override void Initialize(ScriptRunner runner)
 {
     _level   = runner.GetNode(NodeData.Level.NodeId);
     _message = runner.GetNode(NodeData.Message.NodeId);
     _next    = runner.GetNode(NodeData.Next.NodeId);
 }
示例#60
0
        static void SubMain(string[] args)
        {
            Console.WriteLine($"Larry Build {BuildVersion.Version} ({BuildVersion.Date} UTC)");

            using (var directoryChanger = new DirectoryChanger()) // DirectoryChanger automatically resets the working directory upon Dispose
            {
                int    port        = 11929;
                bool   isServer    = false;
                string address     = string.Empty;
                string username    = string.Empty;
                string password    = string.Empty;
                int    paramIndex  = 0;
                var    filesToSend = new List <FileSendObject>();
                ShowTimesInMessages = true;
#if DEBUG
                EnableDebugMessages = true;
#else // DEBUG
                EnableDebugMessages = false;
#endif // DEBUG

                for (int i = 0; i < args.Length; ++i)
                {
                    if (args[i] == "--server")
                    {
                        isServer = true;
                    }
                    else if (args[i] == "--script")
                    {
                        if (i + 1 >= args.Length)
                        {
                            throw new ArgumentNotProvidedException("Script filename");
                        }

                        using (var scriptRunner = new ScriptRunner())
                        {
                            scriptRunner.Run(args[i + 1]);
                        }

                        return;
                    }
                    else if (args[i] == "-p")
                    {
                        if (i + 1 >= args.Length)
                        {
                            throw new ArgumentNotProvidedException("Port");
                        }

                        port = int.Parse(args[++i]);
                    }
                    else if (args[i] == "-d" ||
                             args[i] == "--directory")
                    {
                        if (i + 1 >= args.Length)
                        {
                            throw new ArgumentNotProvidedException("Directory");
                        }

                        directoryChanger.Change(args[++i]);
                    }
                    else if (args[i] == "--debug")
                    {
                        EnableDebugMessages = true;
                    }
                    else if (args[i] == "--no-time")
                    {
                        ShowTimesInMessages = false;
                    }
                    else
                    {
                        switch (paramIndex++)
                        {
                        case 0:
                            address = args[i];
                            break;

                        default:
                        {
                            var match = Regex.Match(args[i], "^([^=]+)=([^=]+)$");
                            if (!match.Success)
                            {
                                throw new MessageException("One or more files to send in parameters were invalid.");
                            }

                            if (!System.IO.File.Exists(match.Groups[1].Value))
                            {
                                throw new MessageException("Local file not found: {0}", match.Groups[1].Value);
                            }

                            filesToSend.Add(new FileSendObject(match.Groups[1].Value, match.Groups[2].Value));
                        }
                        break;
                        }
                    }
                }

                Logger.Log(LogType.Normal, "Platform: " + Environment.OSVersion.Platform);

                if (isServer)
                {
                    if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                    {
                        Console.Title = "Build Server";
                    }

                    using (var server = new BuildServer())
                    {
                        if (server.Start(port))
                        {
                            Logger.Log(LogType.Normal, "Build Server running on port {0}", port);

                            while (true)
                            {
                                // ...
                                if (Console.KeyAvailable)
                                {
                                    var key = Console.ReadKey(true);
                                    if (key.Key == ConsoleKey.Escape)
                                    {
                                        break;
                                    }
                                }

                                server.Process();
                                Thread.Sleep(SleepTime);
                            }
                        }
                        else
                        {
                            Logger.Log(LogType.Error, "Failed to start server. Make sure that port {0} is not in use.", port);
                        }
                    }

                    return;
                }

                if (string.IsNullOrEmpty(address))
                {
                    throw new MessageException("<address> was not provided.");
                }

                if (filesToSend.Count == 0)
                {
                    throw new MessageException("There are no files to send.");
                }

                // run client
                using (var client = new BuildClient(false))
                {
                    if (client.Connect(address, port))
                    {
                        //client.AddFileTransmission(FileTransmission.CreateFromFile("output\\myos.bin", "isodir\\boot\\myos.bin")); // path is normalized in linux
                        //client.AddFileTransmission(FileTransmission.CreateFromFile("src\\grub.cfg", "isodir\\boot\\grub\\grub.cfg"));

                        foreach (var file in filesToSend)
                        {
                            client.AddFileTransmission(FileTransmission.CreateFromFile(
                                                           file.LocalPath,
                                                           file.RemotePath));
                        }

                        using (var source = new CancellationTokenSource())
                        {
                            while (!client.IsFinished)
                            {
                                client.Process(source.Token);
                                Thread.Sleep(SleepTime);
                            }
                        }
                    }
                    else
                    {
                        Logger.Log(LogType.Error, "Failed to connect to {0}:{1}", address, port);
                    }
                }
            }
        }