public HttpHandlerResult SaveScript(HttpRequestParams request)
        {
            var id = request.GetGuid("id");
            var name = request.GetRequiredString("name");
            var body = request.GetRequiredString("body");

            using (var session = database.OpenSession())
            {
                UserScript script;

                if (id.HasValue)
                {
                    script = session.Set<UserScript>().Single(s => s.Id == id.Value);
                }
                else
                {
                    script = new UserScript { Id = Guid.NewGuid() };
                    session.Set<UserScript>().Add(script);
                }

                script.Name = name;
                script.Body = body;
                session.SaveChanges();

                return HttpHandlerResult.Json(new { scriptId = script.Id });
            }
        }
Esempio n. 2
0
        private void CreateNewScript(string name, string type)
        {
            if (string.IsNullOrEmpty(name))
            {
                return;
            }
            if (_dbContext.UserScripts.Any(x => x.Name == name))
            {
                _dialogService.ShowMessageAsync(this, "Script Already Exists", "A script with that name already exists.");
                return;
            }

            //If there are unsaved changes, prompt to save before making a new script
            HandleUnsavedChanges();

            //test text for uniqueness
            var script = new UserScript();

            script.Name = name;

            AddStandardAssemblies(script);

            script.Code = string.Format(type == "Order"
                ? OrderScriptBase
                : TradeScriptBase, name);

            _dbContext.UserScripts.Add(script);
            Scripts.Add(script);
            SelectedScript = script;
            Code           = SelectedScript.Code;
            SaveScripts();
        }
    public void UpdateText()
    {
        UserScript[] players = GameObject.FindObjectsOfType <UserScript>();
        string       newText = "\n Player Stats \n";

        for (int i = 0; i < 3; i++)
        {
            UserScript p = players[i];

            newText += "\n" + names[p.playerNumber] + "\n";

            if (p.jailCount > 0)
            {
                newText += "JAILED!\n";
                newText += "Skips " + p.jailCount + " turns\n\n";
            }
            if (p.hasMedia)
            {
                newText += "Media Card!\n Immune to financial losses\n";
                // newText += "Skips " + p.jailCount + " turns\n\n";
            }
            newText += "Money: " + p.Money + "K\n";
            newText += "Votes: " + p.Votes + "K\n";
        }

        GetComponent <Text>().text = newText;
        GameObject.Find("PlayerStatsPanel2").GetComponent <Text>().text = newText;
    }
Esempio n. 4
0
        public object SaveScript(HttpRequestParams request)
        {
            var id   = request.GetGuid("id");
            var name = request.GetRequiredString("name");
            var body = request.GetRequiredString("body");

            using (var session = Context.Require <DatabasePlugin>().OpenSession())
            {
                UserScript script;

                if (id.HasValue)
                {
                    script = session.Set <UserScript>().Single(s => s.Id == id.Value);
                }
                else
                {
                    script = new UserScript {
                        Id = Guid.NewGuid()
                    };
                    session.Set <UserScript>().Add(script);
                }

                script.Name = name;
                script.Body = body;
                session.SaveChanges();

                return(script.Id);
            }
        }
Esempio n. 5
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSwagger();

            app.UseSwaggerUI(c => {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
            });
            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();
            app.UseAuthentication();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            using var scope   = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope();
            using var context = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>();
            if (context.Database.EnsureCreated())
            {
                var roles        = RoleScript.Roles();
                var admin        = AdministratorScript.ApplicationUser();
                var adminUser    = UserRoleScript.UserRole(roles.FirstOrDefault(x => x.NormalizedName.Equals("ADMINISTRATOR")), admin);
                var types        = TypeScript.GetTypes();
                var company      = CompanyScript.GetCompany();
                var user         = UserScript.ApplicationUser();
                var userRole     = UserRoleScript.UserRole(roles.FirstOrDefault(x => x.NormalizedName.Equals("USER")), user);
                var vehiclesList = VehicleScript.GetVehicles();

                context.Roles.AddRangeAsync(roles).Wait();

                context.ApplicationUser.Add(admin);

                context.UserRoles.Add(adminUser);

                context.Type.AddRangeAsync(types).Wait();

                context.Company.Add(company);

                context.ApplicationUser.Add(user);

                context.UserRoles.Add(userRole);

                context.UserCompany.Add(new UserCompany {
                    CompanyID = company.ID, UserID = user.Id
                });

                context.SaveChangesAsync().Wait();
            }
        }
Esempio n. 6
0
        public override void Revert()
        {
            UserScript script = (UserScript)this.PropertyInfo.GetValue(this.Object, null);

            this.mEditor.Buffer.Text =
                script.Script == null ? "" : script.Script;

            this.FireMadeClean();
        }
Esempio n. 7
0
        public async Task RunTradeScript(UserScript script, List <Trade> trades = null)
        {
            if (script.Type != UserScriptType.TradeScript)
            {
                throw new ArgumentException("Wrong type of script.");
            }

            var actions = await GetTradeScriptActions(script, trades).ConfigureAwait(false);

            await ExecuteTradeActions(actions).ConfigureAwait(false);
        }
Esempio n. 8
0
        public async Task RunOrderScript(UserScript script, List <Order> orders)
        {
            if (script.Type != UserScriptType.OrderScript)
            {
                throw new ArgumentException("Wrong type of script.");
            }

            var actions = await GetOrderScriptActions(script, orders).ConfigureAwait(false);

            await ExecuteOrderActions(actions).ConfigureAwait(false);
        }
Esempio n. 9
0
	void Start () 
    {
        user = GameObject.FindGameObjectWithTag("Network").GetComponent<UserScript>();
        network = GameObject.FindGameObjectWithTag("Network").GetComponent<SocketScript>();
        myMap = transform.GetChild(0).GetComponent<MapScript>();
        otherMap = transform.GetChild(1).GetComponent<MapScript>();
        menuPanel = Menu.GetComponent<Menu>();

		network.MapManager = this;

        InitCharacters();
	}
Esempio n. 10
0
 public override void FillModel(TileModel model, dynamic options)
 {
     try
     {
         UserScript script = GetScript(options);
         model.content   = script.Name;
         model.className = "btn-primary th-tile-icon th-tile-icon-fa fa-rocket";
     }
     catch (Exception ex)
     {
         model.content = ex.Message;
     }
 }
Esempio n. 11
0
        private void OpenScript(UserScript script)
        {
            if (SelectedScript == script)
            {
                return;
            }

            HandleUnsavedChanges();

            SelectedScript       = script;
            Code                 = SelectedScript.Code;
            ChangedSinceLastSave = false;
        }
Esempio n. 12
0
        /// <summary>
        /// Run script and get the actions it generates
        /// </summary>
        /// <param name="script"></param>
        /// <param name="trades">If trades are not provided, all open trades are used.</param>
        /// <returns></returns>
        public async Task <List <TradeScriptAction> > GetTradeScriptActions(UserScript script, List <Trade> trades = null)
        {
            var scriptToExecute = script.Code + @"
                var script = new " + script.Name + @"(Data, Logger);
                return script.GenerateActions(OpenTrades);";

            var globals = new Globals {
                Data = _data, Logger = _logger, OpenTrades = trades ?? _data.Trades.Where(x => x.Open).ToList()
            };
            var options = ScriptOptions.Default
                          .WithReferences(Assembly.GetExecutingAssembly());

            return(await CSharpScript.EvaluateAsync <List <TradeScriptAction> >(scriptToExecute, options, globals).ConfigureAwait(false));
        }
Esempio n. 13
0
        public async Task <List <OrderScriptAction> > GetOrderScriptActions(UserScript script, List <Order> orders)
        {
            var scriptToExecute = script.Code + @"
                var script = new " + script.Name + @"(Data, Logger);
                return script.GenerateActions(Orders);";

            var globals = new Globals {
                Data = _data, Orders = orders, Logger = _logger
            };
            var options = ScriptOptions.Default
                          .WithReferences(Assembly.GetExecutingAssembly());

            return(await CSharpScript.EvaluateAsync <List <OrderScriptAction> >(scriptToExecute, options, globals).ConfigureAwait(false));
        }
        public override string ExecuteAction(object options)
        {
            try
            {
                UserScript script = GetScript(options);

                Context.GetPlugin <ScriptsPlugin>().ExecuteScript(script);
                return(null);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Esempio n. 15
0
        public static void LoadScript(string id, string code, bool enabled = false, string runspec = "")
        {
            string completeCode = code;

            UserScript newScript;

            newScript = new UserScript(id, completeCode, runspec, true)
            {
                Enabled = enabled
            };
            newScript.CompileError   += HandleCompileError;
            newScript.ScriptExecuted += HandleScriptExecutedEvent;
            newScript.ScriptError    += HandleScriptErrorEvent;
            _scripts.Add(id, newScript);
        }
Esempio n. 16
0
        public object AddScript(dynamic args)
        {
            var name = args.name;
            var body = args.body;

            using (var session = Context.OpenSession())
            {
                var guid   = Guid.NewGuid();
                var script = new UserScript {
                    Id = guid, Name = name, Body = body
                };
                session.Save(script);
                session.Flush();

                return(guid);
            }
        }
Esempio n. 17
0
        private static void ExecuteScript(UserScript script, ScriptHost scriptHost, Logger logger, object[] args)
        {
            try
            {
                //var engine = new JScriptEngine(WindowsScriptEngineFlags.EnableDebugging);
                var engine = new JScriptEngine();
                engine.AddHostObject("host", scriptHost);

                string initArgsScript = string.Format("var arguments = {0};", args.ToJson());
                engine.Execute(initArgsScript);
                engine.Execute(script.Body);
            }
            catch (Exception ex)
            {
                var messge = string.Format("Error in user script {0}", script.Name);
                logger.ErrorException(messge, ex);
            }
        }
Esempio n. 18
0
        private static bool RunScript(UserScript script, string type)
        {
            try {
                ScriptCall call = script.Call;
                if (call == null)
                {
                    return(false);
                }

                call();
            } catch (Exception e) {
                Console.WriteLine("Exception executing the {0} script:", type);
                Console.WriteLine(e.ToString());
                return(false);
            }

            return(true);
        }
Esempio n. 19
0
        private void AddStandardAssemblies(UserScript script)
        {
            script.ReferencedAssemblies.Add("mscorlib.dll");
            script.ReferencedAssemblies.Add("System.dll");
            script.ReferencedAssemblies.Add("System.Collections.dll");
            script.ReferencedAssemblies.Add("System.Core.dll");

            string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;

            script.ReferencedAssemblies.Add(exePath);
            string entityModelDllPath = Path.Combine(Path.GetDirectoryName(exePath), "EntityModel.dll");

            script.ReferencedAssemblies.Add(entityModelDllPath);
            string qpasCommonPath = Path.Combine(Path.GetDirectoryName(exePath), "QPAS.Common.dll");

            script.ReferencedAssemblies.Add(qpasCommonPath);
            string nlogPath = Path.Combine(Path.GetDirectoryName(exePath), "NLog.dll");

            script.ReferencedAssemblies.Add(nlogPath);
        }
Esempio n. 20
0
        public override void Apply()
        {
            UserScript script = (UserScript)this.PropertyInfo.GetValue(this.Object, null);

            this.mEditor.Buffer.RemoveTag(this.mErrorTag,
                                          this.mEditor.Buffer.StartIter,
                                          this.mEditor.Buffer.EndIter);

            this.mErrorLabel.Hide();

            script.Script = this.mEditor.Buffer.Text;
            try {
                script.Recompile();
            } catch (ScriptCompileException ex) {
                TextIter start, end;

                if (ex.Position == -1)
                {
                    start = this.mEditor.Buffer.StartIter;
                    end   = this.mEditor.Buffer.EndIter;
                }
                else
                {
                    start = this.mEditor.Buffer.GetIterAtOffset(ex.Position);

                    end = start;
                    if (!end.ForwardChar())
                    {
                        start.BackwardChar();
                    }
                }

                this.mEditor.Buffer.ApplyTag(this.mErrorTag, start, end);

                this.mErrorLabel.Text = ex.Message;
                this.mErrorLabel.Show();
            }

            this.FireApplied();
            this.FireMadeClean();
        }
Esempio n. 21
0
	// Use this for initialization
	void Start () 
    {
        user = GameObject.FindGameObjectWithTag("Network").GetComponent<UserScript>();
	}
Esempio n. 22
0
 /// <summary>
 /// Запуск скриптов (для плагинов)
 /// </summary>
 /// <param name="script"></param>
 /// <param name="args"></param>
 public void ExecuteScript(UserScript script, params object[] args)
 {
     ExecuteScript(script, scriptHost, Logger, args);
 }
    void Start()
    {
        userScript = User.GetComponent <UserScript>();

        clockVelocity = new Vector3(0, 0, 0);
    }
        public BrowserWindow(Data.SessionInfo session, bool keepDebugWindow = false)
        {
            GM = new GMApi.GM_API_Handler(session.UUID, this);
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            this.Text = session.SessionName + " - " + Properties.Settings.Default.Title;
            webBro    = new ChromiumWebBrowser();

            logger.AppendText("脚本加载器任务:准备脚本数据\n\n正在预加载脚本...\n");

            webBro.RequestContext = Data.CM.GetContext(session.UUID).context;
            browserLayoutPanel.Controls.Add(webBro);
            webBro.Dock            = DockStyle.Fill;
            webBro.LifeSpanHandler = new Common.Control.CefSharpOpenPageSelf();
            webBro.AddressChanged += onAddrChange;
            webBro.JavascriptObjectRepository.Settings.LegacyBindingEnabled = true;
            webBro.JavascriptObjectRepository.Register("GM", GM, false);

            this.session = session;
            sUUID        = session.UUID;
            Task t = Task.Run(async() =>
            {
                List <string> Uscripts = Data.VDB.GetSessionRelatedScripts(session.UUID);
                scripts.Clear();
                int cnt = 0;
                foreach (string urlstr in Uscripts)
                {
                    if (urlstr.Length < 1)
                    {
                        continue;
                    }
                    try
                    {
                        logger.AppendText("加载:" + urlstr + "\n");
                        if (this.IsDisposed)
                        {
                            return;
                        }
                        UserScript script = null;
                        Uri url           = new Uri(urlstr);
                        if (url.Scheme == "localscript")
                        {
                            script = new LocalUserScriptHandler(session).GetLocalUserScript(url.Host);
                        }
                        else if (url.Scheme == "globalscript")
                        {
                            script = LocalUserScriptHandler.GetUserScript(url.Host);
                        }
                        else
                        {
                            var code = Data.ScriptFetchEngine.GetScriptContent(urlstr, session);
                            script   = new UserScript(code);
                        }
                        if (script == null ||
                            script.conf.Name == null ||
                            script.conf.Name == "")
                        {
                            continue;
                        }
                        logger.AppendText("正在准备预定义资源...\n");
                        foreach (KeyValuePair <string, string> kvp in script.conf.Resources)
                        {
                            if (this.IsDisposed)
                            {
                                return;
                            }
                            logger.AppendText("[" + kvp.Key + "]\t" + kvp.Value + " \t");
                            try
                            {
                                GM.storage.preLoadResources.Add(kvp.Key, new GMApi.StorageSystem.Resource()
                                {
                                    content = ScriptFetchEngine.GetScriptContent(kvp.Value),
                                    url     = kvp.Value
                                });
                                logger.AppendText("Done. Len=" +
                                                  GM.storage.preLoadResources[kvp.Key].content.Length
                                                  + "\n");
                            }
                            catch
                            {
                                GM.storage.preLoadResources.Add(kvp.Key, new GMApi.StorageSystem.Resource()
                                {
                                    content = "",
                                    url     = kvp.Value
                                });
                                logger.AppendText("Fail.\n");
                            }
                        }
                        scripts.Add(script);
                        logger.AppendText("当前脚本完成。\n\n");
                        cnt++;
                        this.Text = session.SessionName + "(Script*" + cnt + ") - " + Properties.Settings.Default.Title;
                    }
                    catch (Exception err)
                    {
                        logger.AppendText("脚本加载出现问题:" + err.Message + "\n调用栈:\n");
                        logger.AppendText(err.StackTrace + "\n");
                    }
                }
                if (this.IsDisposed)
                {
                    return;
                }
                logger.AppendText("预加载完成,开始载入网页。\n");
                await Task.Delay(1000);
                if (this.IsDisposed)
                {
                    return;
                }
                if (!keepDebugWindow)
                {
                    logger.Hide();
                }
                webBro.FrameLoadEnd += onFrameLoadEnd;
                webBro.Load(session.Url);
            });
        }
Esempio n. 25
0
    public void populateOptions(UserScript currentPlayer)
    {
        currentPlayerObj = currentPlayer;
        cl = currentPlayer.getLocationAt(currentPlayer.currentML);

        int me = (currentPlayer.playerNumber + 1);

        int Votes = (cl.Population / 4);
        int Cost  = (cl.Demands / 4);

        int CalledFor = (cl.Status1 + cl.Status2 + cl.Status3);
        int Occupied  = CalledFor;
        int TxCost    = 0;

        switch (me)
        {
        case 1: { CalledFor -= cl.Status1; break; }

        case 2: { CalledFor -= cl.Status2; break; }

        case 3: { CalledFor -= cl.Status3; break; }
        }

        if (CalledFor > 0)
        {
            TxCost = cl.RallyMoney;
        }

        string name = "";

        if (cl.Status1 > 0 && me != 1 && (Cost + TxCost <= currentPlayer.Money))
        {
            name = "AAP";
            string toPay = "To buy 25% [" + Votes + "K Votes] from " + name + " you need to pay " + Cost + "K INR with Rally Cost: " + TxCost + "K INR";
            GameObject.Find("PayAAPButton").GetComponent <Button>().interactable = true;
            GameObject.Find("PayAAPButton").GetComponent <Button>().onClick.AddListener(() => ButtonHandler(Votes, name, Cost, TxCost));
            GameObject.Find("PayAAPButton").GetComponentInChildren <Text>().text = toPay;
            // enable button to pay to Aap
        }
        else
        {
            GameObject.Find("PayAAPButton").GetComponent <Button>().interactable = false;
        }

        if (cl.Status2 > 0 && me != 2 && (Cost + TxCost <= currentPlayer.Money))
        {
            name = "BJP";
            string toPay = "To buy 25% [" + Votes + "K Votes] from " + name + " you need to pay " + Cost + "K INR with Rally Cost: " + TxCost + "K INR";
            GameObject.Find("PayBJPButton").GetComponent <Button>().interactable = true;
            GameObject.Find("PayBJPButton").GetComponent <Button>().onClick.AddListener(() => ButtonHandler(Votes, name, Cost, TxCost));
            GameObject.Find("PayBJPButton").GetComponentInChildren <Text>().text = toPay;
            // enable button to pay to BJP
        }
        else
        {
            GameObject.Find("PayBJPButton").GetComponent <Button>().interactable = false;
        }

        if (cl.Status3 > 0 && me != 3 && (Cost + TxCost <= currentPlayer.Money))
        {
            name = "INC";
            string toPay = "To buy 25% [" + Votes + "K Votes] from " + name + " you need to pay " + Cost + "K INR with Rally Cost: " + TxCost + "K INR";
            GameObject.Find("PayINCButton").GetComponent <Button>().interactable = true;

            GameObject.Find("PayINCButton").GetComponent <Button>().onClick.AddListener(() => ButtonHandler(Votes, name, Cost, TxCost));

            GameObject.Find("PayINCButton").GetComponentInChildren <Text>().text = toPay;
            // enable button to pay to INC
        }
        else
        {
            GameObject.Find("PayINCButton").GetComponent <Button>().interactable = false;
        }

        if (CalledFor < 100 && Occupied != 100 && (Cost + TxCost <= currentPlayer.Money))
        {
            name = "Independent";
            string toPay = "To buy 25% [" + Votes + "K Votes] from " + name + " you need to pay " + Cost + "K INR with Rally Cost: " + TxCost + "K INR";
            GameObject.Find("BuyButton").GetComponent <Button>().interactable = true;
            GameObject.Find("BuyButton").GetComponent <Button>().onClick.AddListener(() => ButtonHandler(Votes, name, Cost, TxCost));

            GameObject.Find("BuyButton").GetComponentInChildren <Text>().text = toPay;
            // enable button to pay to Independent
        }
        else
        {
            GameObject.Find("BuyButton").GetComponent <Button>().interactable = false;
        }
    }
Esempio n. 26
0
 public void GetUserScript(UserScript user)
 {
     userScript = user;
 }
Esempio n. 27
0
 public object ExecuteScript(UserScript script, params object[] args)
 {
     return(CreateScriptDelegate(script.Name, script.Body)(args));
 }
Esempio n. 28
0
 void Start()
 {
     PickButton.isEnabled = false;
     Network = GameObject.FindGameObjectWithTag("Network").GetComponent<SocketScript>();
     User = GameObject.FindGameObjectWithTag("Network").GetComponent<UserScript>();
 }