Exemple #1
0
        static void Main(string[] args)
        {
            var scriptLoader = new ScriptLoader();

            const string filename = @"..\..\Runtime\RuntimeScript.cs";
            const string typeName = "Diese.Scripting.Sample.Runtime.RuntimeScript";

            var stopwatch =  new Stopwatch();

            ConsoleKeyInfo key;
            do
            {
                try
                {
                    stopwatch.Restart();
                    Type type = scriptLoader.LoadTypeFromFile(filename, typeName);
                    var action = (Action)Delegate.CreateDelegate(typeof(Action), type.GetMethod("Do"));
                    action();
                    stopwatch.Stop();
                    Console.WriteLine("Time : {0} ms", stopwatch.ElapsedMilliseconds);
                }
                catch (Exception e)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(e.Message);
                    Console.ResetColor();
                }
                key = Console.ReadKey();

            } while (key.Key != ConsoleKey.Escape);
        }
        public void Should_return_sizzlejs_install_script()
        {
            // GIVEN
            var scriptLoader = new ScriptLoader();

            // WHEN
            var script = scriptLoader.GetSizzleInstallScript();

            // THEN
            Console.WriteLine(script);
            Assert.That(script, Is.Not.Null, "expected script");
            Assert.That(script, Text.Contains("Sizzle"), "expected Sizzle function");
        }
 public void LoadAndWatch()
 {
     if (!m_appServerEndPointsPath.IsNullOrBlank() && File.Exists(m_appServerEndPointsPath))
     {
         m_appServerEndPointsLoader = new ScriptLoader(SendMonitorEvent_External, m_appServerEndPointsPath);
         m_appServerEndPointsLoader.ScriptFileChanged += (s, e) => { m_appServerEndPoints = LoadAppServerEndPoints(m_appServerEndPointsLoader.GetText()); };
         m_appServerEndPoints = LoadAppServerEndPoints(m_appServerEndPointsLoader.GetText());
     }
     else
     {
         throw new ApplicationException("SIPCallDispatcherFile was passed a path to a non-existent file, " + m_appServerEndPointsPath + ".");
     }
 }
Exemple #4
0
        public void Should_return_sizzlejs_install_script()
        {
            // GIVEN
            var scriptLoader = new ScriptLoader();

            // WHEN
            var script = scriptLoader.GetSizzleInstallScript();

            // THEN
            Console.WriteLine(script);
            Assert.That(script, Is.Not.Null, "expected script");
            Assert.That(script, Text.Contains("Sizzle"), "expected Sizzle function");
        }
        private static void SetupDebugger(string[] paths)
        {
            debugger = new Debugger();

            debugger.Pause    += Debugger_Pause;
            debugger.Continue += Debugger_Continue;

            scriptLoader = new ScriptLoader(debugger);

            foreach (var path in paths)
            {
                scriptLoader.Load(path);
            }
        }
    private static void HandleEnchantScroll(GameSession session, Item item)
    {
        EnchantScrollMetadata metadata = EnchantScrollMetadataStorage.GetMetadata(item.Function.Id);

        if (metadata is null)
        {
            return;
        }

        Script script      = ScriptLoader.GetScript("Functions/ItemEnchantScroll/getSuccessRate");
        float  successRate = (float)script.RunFunction("getSuccessRate", metadata.Id).Number;

        session.Send(EnchantScrollPacket.OpenWindow(item.Uid, metadata, successRate));
    }
Exemple #7
0
        public void TheScriptLoaderLoadsSeveralScripts()
        {
            var data = CreateScriptFileWithSeveralScripts();

            var scripts = ScriptLoader.LoadScripts(data);

            scripts.Count.Should().Be(3);

            scripts.Keys.ToList().Should().BeEquivalentTo("Script 1", "Script 2", "Script 3");

            Encoding.UTF8.GetString(scripts["Script 1"].GetScriptBinary()).Should().Be("One");
            Encoding.UTF8.GetString(scripts["Script 2"].GetScriptBinary()).Should().Be("Two");
            Encoding.UTF8.GetString(scripts["Script 3"].GetScriptBinary()).Should().Be("Three");
        }
Exemple #8
0
        public void doesnt_match_other(string browserType)
        {
            UseBrowser(browserType);

            ScriptLoader loader = new ScriptLoader();

            GoToResource("CssClassConstraintTest.htm");

            Thread.Sleep(TimeSpan.FromSeconds(5).Milliseconds);

            Browser.Element(Find.ById("notmatch_1").And(new CssClassConstraint("marker").Not())).WaitUntilExists(5);
            Browser.Element(Find.ById("notmatch_2").And(new CssClassConstraint("marker").Not())).WaitUntilExists(5);
            Browser.Element(Find.ById("notmatch_3").And(new CssClassConstraint("marker").Not())).WaitUntilExists(5);
        }
Exemple #9
0
        /// <summary>
        /// Handling the event of the generate button.
        /// It generates a new TwinCat configuration
        /// </summary>
        private void _BgeneratePLC_Click(object sender, EventArgs e)
        {
            //this.Open();
            //Debug.Assert(this._factory == null);
            try
            {
                OrderInfo order  = this._orders[this._fbNumber];                           // selects just the first item in the order.xml. TODO: connection with the AML SUC.
                Script    script = ScriptLoader.GetScript(order.ConfigurationInfo.Script); // get the script under AvailableConfiguration of the order item previously selected

                if (script == null)
                {
                    throw new ApplicationException(string.Format("Script '{0}' not found. Cannot start execution!", order.ConfigurationInfo.Script));
                }

                _runningScript = script;          // setting the running script with the one previously selected

                VsFactory fact = new VsFactory(); // VS factory to create the DTE Object and determine the VS version to integrate with TC

                if (_runningScript is ScriptEarlyBound)
                {
                    this._factory = new EarlyBoundFactory(fact);
                }
                else if (_runningScript is ScriptLateBound)
                {
                    this._factory = new LateBoundFactory(fact);
                }

                if (this._factory == null)
                {
                    throw new ApplicationException("Generator not found!");
                }

                OrderScriptContext context = new OrderScriptContext(this._factory, order);        // we need to set the context of the script

                _worker = new ScriptBackgroundWorker(/*this._factory,*/ _runningScript, context); // worker for asynchronous script execution

                // Showing TwinCat UI and keeping it open after the creation of the code
                _factory.IsIdeVisible     = true;
                _factory.IsIdeUserControl = true;
                _factory.SuppressUI       = true;

                // Script execution: In Workerthread.cs it does OnDoWork() which has the main functions: Initialization, Execution and Cleanup
                _worker.BeginScriptExecution();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }
Exemple #10
0
        public void CallFunction()
        {
            var testScript  = @"
using Yggdrasil.Scripting;
using Yggdrasil.Test.Scripting;

class TestScript2 : IScript, IFoobarer
{
	public bool Init()
	{
		ScriptLoaderTests.Scripts[""TestScript2""] = this;
		return true;
	}

	public int Foobar()
	{
		return 2;
	}
}
";
            var tmpFilePath = Path.GetTempFileName();

            File.WriteAllText(tmpFilePath, testScript);

            Assert.DoesNotThrow(() =>
            {
                try
                {
                    var loader = new ScriptLoader(new CSharpCodeProvider());
                    loader.LoadFromList(new[] { tmpFilePath });
                }
                catch (CompilerErrorException ex)
                {
                    foreach (var err in ex.Errors)
                    {
                        Console.WriteLine(err);
                    }
                    throw;
                }
            });

            var script = Scripts["TestScript2"] as IFoobarer;

            Assert.NotNull(script);

            Test = script.Foobar();

            Assert.Equal(2, Test);
        }
        public override void RezScriptsForObject(ObjectGroup group, int startparameter = 0)
        {
            foreach (ObjectPart part in group.Values)
            {
                foreach (ObjectPartInventoryItem item in part.Inventory.Values)
                {
                    if (item.AssetType == AssetType.LSLText)
                    {
                        AssetData assetData;
                        if (AssetService.TryGetValue(item.AssetID, out assetData))
                        {
                            try
                            {
                                bool hasState = item.ScriptState != null;
#if DEBUG
                                m_Log.DebugFormat("Instantiating script: HasState={0}", hasState);
#endif
                                item.ScriptInstance = ScriptLoader.Load(part, item, item.Owner, assetData, null, openInclude: part.OpenScriptInclude);
#if DEBUG
                                m_Log.DebugFormat("Instantiated script: IsResetRequired={0} Running={1}", item.ScriptInstance.IsResetRequired, item.ScriptInstance.IsRunning);
#endif

                                item.ScriptInstance.IsRunningAllowed = group.Scene.CanRunScript(item.Owner, part.ObjectGroup.GlobalPosition, item.AssetID);
                                if (item.ScriptInstance.IsResetRequired || !hasState)
                                {
                                    item.ScriptInstance.IsResetRequired = false;
                                    item.ScriptInstance.IsRunning       = true;
                                    item.ScriptInstance.Reset();
                                }
                                item.ScriptInstance.StartParameter = startparameter;
                                item.ScriptInstance.PostEvent(new OnRezEvent(startparameter));
                            }
                            catch (Exception e)
                            {
#if DEBUG
                                m_Log.ErrorFormat("Loading script {0} (asset {1}) for {2} ({3}) in {4} ({5}) failed: {6}: {7}\n{8}", item.Name, item.AssetID, part.Name, part.ID, part.ObjectGroup.Name, part.ObjectGroup.ID, e.GetType().FullName, e.Message, e.StackTrace);
#else
                                m_Log.ErrorFormat("Loading script {0} (asset {1}) for {2} ({3}) in {4} ({5}) failed: {6}", item.Name, item.AssetID, part.Name, part.ID, part.ObjectGroup.Name, part.ObjectGroup.ID, e.Message);
#endif
                            }
                        }
                        else
                        {
                            m_Log.ErrorFormat("Script {0} (asset {1}) is missing for {2} ({3}) in {4} ({5})", item.Name, item.AssetID, part.Name, part.ID, part.ObjectGroup.Name, part.ObjectGroup.ID);
                        }
                    }
                }
            }
        }
Exemple #12
0
        public void ReloadToTweetDeck()
        {
            #if DEBUG
            ScriptLoader.HotSwap();
            #else
            if (ModifierKeys.HasFlag(Keys.Shift))
            {
                ScriptLoader.ClearCache();
            }
            #endif

            ignoreUpdateCheckError = false;
            browser.ReloadToTweetDeck();
            AnalyticsFile.BrowserReloads.Trigger();
        }
Exemple #13
0
        private void browser_FrameLoadStart(object sender, FrameLoadStartEventArgs e)
        {
            if (e.Frame.IsMain)
            {
                if (Config.ZoomLevel != 100)
                {
                    BrowserUtils.SetZoomLevel(browser.GetBrowser(), Config.ZoomLevel);
                }

                if (BrowserUtils.IsTwitterWebsite(e.Frame))
                {
                    ScriptLoader.ExecuteFile(e.Frame, "twitter.js");
                }
            }
        }
Exemple #14
0
        public FormNotificationScreenshotable(Action callback, FormBrowser owner, PluginManager pluginManager) : base(owner, false)
        {
            this.plugins = pluginManager;

            browser.RegisterAsyncJsObject("$TD_NotificationScreenshot", new CallbackBridge(this, callback));

            browser.LoadingStateChanged += (sender, args) => {
                if (!args.IsLoading)
                {
                    using (IFrame frame = args.Browser.MainFrame){
                        ScriptLoader.ExecuteScript(frame, "window.setTimeout($TD_NotificationScreenshot.trigger, document.getElementsByTagName('iframe').length ? 267 : 67)", "gen:screenshot");
                    }
                }
            };
        }
Exemple #15
0
        public void Should_inject_script_sucessfully()
        {
            ExecuteTest(browser =>
            {
                // GIVEN
                var scriptLoader = new ScriptLoader();

                // THEN
                browser.RunScript(scriptLoader.GetSizzleInstallScript());

                // WHEN
                var eval = browser.Eval("window.Sizzle('#popupid').length;");
                Assert.That(eval, Is.EqualTo("1"));
            });
        }
Exemple #16
0
        private static void GameOnOnGameLoad(EventArgs args)
        {
            // Load all the scripts
            ScriptLoader.Init();

            // API Events
            Game.OnGameUpdate              += ApiHandler.OnGameUpdate;
            Drawing.OnDraw                 += ApiHandler.OnDraw;
            GameObject.OnCreate            += ApiHandler.OnCreateObj;
            GameObject.OnDelete            += ApiHandler.OnDeleteObj;
            Game.OnWndProc                 += ApiHandler.OnWndMsg;
            Obj_AI_Base.OnProcessSpellCast += ApiHandler.OnProcessSpellCast;
            Game.OnGameInput               += ApiHandler.OnSendChat;
            Game.OnGameSendPacket          += ApiHandler.OnSendPacket;
        }
Exemple #17
0
        private void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
        {
            if (e.Frame.IsMain && notificationJS != null && browser.Address != "about:blank" && !flags.HasFlag(NotificationFlags.DisableScripts))
            {
                e.Frame.ExecuteJavaScriptAsync(PropertyBridge.GenerateScript(PropertyBridge.Properties.ExpandLinksOnHover));
                ScriptLoader.ExecuteScript(e.Frame, notificationJS, NotificationScriptIdentifier);

                if (plugins != null && plugins.HasAnyPlugin(PluginEnvironment.Notification))
                {
                    ScriptLoader.ExecuteScript(e.Frame, pluginJS, PluginScriptIdentifier);
                    ScriptLoader.ExecuteFile(e.Frame, PluginManager.PluginGlobalScriptFile);
                    plugins.ExecutePlugins(e.Frame, PluginEnvironment.Notification, false);
                }
            }
        }
Exemple #18
0
        private static int GetFirstScriptId(ScriptLoader scriptLoader, ScriptMetadata scriptMetadata)
        {
            if (scriptLoader.Script != null)
            {
                // Usually hardcoded functions to get the first script id which
                // otherwise wouldn't be possible only with the xml data
                DynValue result = scriptLoader.Call("getFirstScriptId");
                if (result != null && result.Number != -1)
                {
                    return((int)result.Number);
                }
            }

            return(scriptMetadata.Options.First(x => x.Type == ScriptType.Script).Id);
        }
        public ShootingGame(Key key, string scriptPath)
        {
            OwnChar = new OwnCharacter(this, new Position(320.0, 400.0));
            OwnBullets = new List<Bullet>();
            Enemies = new List<Enemy>();
            EnemyBullets = new List<Bullet>();

            this.key = key;

            // スクリプト読み込み
            this.ScriptPath = scriptPath;
            var loader = new ScriptLoader(this);
            var script = loader.Load(this.ScriptPath);
            runner = new ScriptRunner(this, script);
        }
Exemple #20
0
        internal void WriteJSFile(string outputJsFile)
        {
            string       jsfile = Path.Combine(casperjsBase, outputJsFile);
            string       jquery = Path.Combine(casperjsBase, "jquery.js");
            StreamWriter sw     = new StreamWriter(jsfile, false);

            sw.Write(sb.ToString());
            sw.Close();
            if (!File.Exists(jquery))
            {
                sw = new StreamWriter(jquery, false);
                sw.Write(ScriptLoader.GetJqueryInstallScript());
                sw.Close();
            }
        }
Exemple #21
0
        public void Should_inject_script_sucessfully()
        {
            ExecuteTest(browser =>
                            {
                                // GIVEN
                                var scriptLoader = new ScriptLoader();

                                // THEN
                                browser.RunScript(scriptLoader.GetSizzleInstallScript());

                                // WHEN
                                var eval = browser.Eval("window.Sizzle('#popupid').length;");
                                Assert.That(eval, Is.EqualTo("1"));
                            });
        }
Exemple #22
0
        public static void RestoreSessionData(IFrame frame)
        {
            if (SessionData.Count > 0)
            {
                StringBuilder build = new StringBuilder().Append("window.TD_SESSION={");

                foreach (KeyValuePair <string, string> kvp in SessionData)
                {
                    build.Append(kvp.Key).Append(":'").Append(kvp.Value.Replace("'", "\\'")).Append("',");
                }

                ScriptLoader.ExecuteScript(frame, build.Append("}").ToString(), "gen:session");
                SessionData.Clear();
            }
        }
    // Use this for initialization
    void Start()
    {
        cameraController = GameObject.Find("Main Camera").GetComponent <CameraController>();


        scriptLoader = new ScriptLoader();

        Verse = new Verse();

        SpriteController spriteController = gameObject.AddComponent <SpriteController>();

        spriteController.Load();

        string pathXml = Path.Combine(Application.streamingAssetsPath, "Data/Prototypes/Parts.xml");

        Verse.registry.partRegistry.ReadPrototypes(pathXml);
        pathXml = Path.Combine(Application.streamingAssetsPath, "Data/Prototypes/Entities.xml");
        Verse.registry.entityRegistry.ReadPrototypes(pathXml);

        gameObject.AddComponent <GUIController>();
        shipController = gameObject.AddComponent <ShipController>();
        gameObject.AddComponent <InputController>();

        VerseComponent verseComponent = gameObject.AddComponent <VerseComponent>();

        Verse.register(verseComponent);

        GameObject overlay = new GameObject("Overlay");

        overlay.transform.SetParent(cameraController.transform);
        overlayComponent = overlay.AddComponent <OverlayComponent>();
        Verse.register(overlayComponent);

        galaxy = new GameObject("StarMap");
        GalaxyComponent galaxyComponent = galaxy.AddComponent <GalaxyComponent>();

        galaxyComponent.Camera           = GameObject.Find("MapCamera").GetComponent <Camera>();
        galaxyComponent.vert             = starmapVertex;
        galaxyComponent.starPathMaterial = starmapEdgeMaterial;

        Verse.Galaxy.register(galaxyComponent);

        Verse.Create();

        Verse.SetMap("Health");

        SetMode(ViewMode.Ship);
    }
        public ShootingGame(Key key, string scriptPath)
        {
            OwnChar      = new OwnCharacter(this, new Position(320.0, 400.0));
            OwnBullets   = new List <Bullet>();
            Enemies      = new List <Enemy>();
            EnemyBullets = new List <Bullet>();

            this.key = key;

            // スクリプト読み込み
            this.ScriptPath = scriptPath;
            var loader = new ScriptLoader(this);
            var script = loader.Load(this.ScriptPath);

            runner = new ScriptRunner(this, script);
        }
Exemple #25
0
        public void LoadFromList()
        {
            var testScript  = @"
using Yggdrasil.Scripting;
using Yggdrasil.Test.Scripting;

class TestScript1 : IScript
{
	public bool Init()
	{
		ScriptLoaderTests.Test = 1;
		return true;
	}
}
";
            var tmpFilePath = Path.GetTempFileName() + ".cs";

            File.WriteAllText(tmpFilePath, testScript);

            Assert.DoesNotThrow(() =>
            {
                try
                {
                    var loader = new ScriptLoader(new CSharpCodeProvider());
                    loader.LoadFromList(new[] { tmpFilePath });

                    Console.WriteLine("LoadingExceptions");
                    foreach (var err in loader.LoadingExceptions)
                    {
                        Console.WriteLine(err);
                    }
                }
                catch (CompilerErrorException ex)
                {
                    Console.WriteLine("CompilerErrorException");
                    foreach (var err in ex.Errors)
                    {
                        Console.WriteLine(err);
                    }
                    throw;
                }
            });

            Assert.Equal(1, Test);

            File.Delete(tmpFilePath);
        }
Exemple #26
0
        private void browser_LoadError(object sender, LoadErrorEventArgs e)
        {
            if (e.ErrorCode == CefErrorCode.Aborted)
            {
                return;
            }

            if (!e.FailedUrl.StartsWith("http://td/"))
            {
                string errorPage = ScriptLoader.LoadResource("pages/error.html", true);

                if (errorPage != null)
                {
                    browser.LoadHtml(errorPage.Replace("{err}", BrowserUtils.GetErrorName(e.ErrorCode)), "http://td/error");
                }
            }
        }
Exemple #27
0
                public static ScriptLoader FromBaseObject(BaseObject baseObj)
                {
                    if (baseObj == null || baseObj.NativeObject == IntPtr.Zero)
                    {
                        return(null);
                    }
                    ScriptLoader obj = baseObj as  ScriptLoader;

                    if (object.Equals(obj, null))
                    {
                        obj = new ScriptLoader(CreatedWhenConstruct.CWC_NotToCreate);
                        obj.BindNativeObject(baseObj.NativeObject, "CScriptLoader");
                        obj.IncreaseCast();
                    }

                    return(obj);
                }
Exemple #28
0
        public static ScriptLoader GetLoader()
        {
            if (scriptLoaderCached)
            {
                return(cachedScriptLoader);
            }
            scriptLoaderCached = true;

            var methods = GetMethodInfo.WithAttr <LuaScriptLoaderAttribute>().ToArray();

            if (methods.Length > 0)
            {
                var m = methods[0];
                cachedScriptLoader = (ScriptLoader)Delegate.CreateDelegate(typeof(ScriptLoader), m);
            }
            return(cachedScriptLoader);
        }
Exemple #29
0
        public void ExecutePlugins(IFrame frame, PluginEnvironment environment, bool includeDisabled)
        {
            if (includeDisabled)
            {
                ScriptLoader.ExecuteScript(frame, PluginScriptGenerator.GenerateConfig(Config), "gen:pluginconfig");
            }

            List <string> failedPlugins = new List <string>(1);

            foreach (Plugin plugin in Plugins)
            {
                string path = plugin.GetScriptPath(environment);
                if (string.IsNullOrEmpty(path) || !plugin.CanRun || (!includeDisabled && !Config.IsEnabled(plugin)))
                {
                    continue;
                }

                string script;

                try{
                    script = File.ReadAllText(path);
                }catch (Exception e) {
                    failedPlugins.Add(plugin.Identifier + " (" + Path.GetFileName(path) + "): " + e.Message);
                    continue;
                }

                int token;

                if (tokens.ContainsValue(plugin))
                {
                    token = GetTokenFromPlugin(plugin);
                }
                else
                {
                    token         = GenerateToken();
                    tokens[token] = plugin;
                }

                ScriptLoader.ExecuteScript(frame, PluginScriptGenerator.GeneratePlugin(plugin.Identifier, script, token, environment), "plugin:" + plugin);
            }

            if (Executed != null)
            {
                Executed(this, new PluginErrorEventArgs(failedPlugins));
            }
        }
Exemple #30
0
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (!DesignMode)
            {
                ScriptProxy = ClientScriptProxy.Current;

                // Use ScriptProxy to load jQuery and ww.Jquery
                if (!string.IsNullOrEmpty(jQueryScriptLocation))
                {
                    ScriptLoader.LoadjQuery(this);
                }

                ScriptProxy.LoadControlScript(this, ScriptLocation, ControlResources.WWJQUERY_SCRIPT_RESOURCE, ScriptRenderModes.Header);
            }
        }
Exemple #31
0
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (!DesignMode)
            {
                ScriptProxy = ClientScriptProxy.Current;

                // Use ScriptProxy to load jQuery and ww.Jquery
                if (!string.IsNullOrEmpty(jQueryScriptLocation))
                {
                    ScriptLoader.LoadjQuery(this);
                }

                ScriptLoader.LoadwwjQuery(this, false);
            }
        }
        public static ScriptLoader GetLoader()
        {
            if (scriptLoaderCached)
            {
                return(cachedScriptLoader);
            }
            scriptLoaderCached = true;

            System.Collections.Generic.IEnumerable <Type> allTypes = null;
            try
            {
                allTypes = Assembly.Load("Assembly-CSharp").GetTypes().AsEnumerable();
            }
            catch
            { }
            try
            {
                var typesInPlugins = Assembly.Load("Assembly-CSharp-firstpass").GetTypes();
                if (allTypes != null)
                {
                    allTypes = allTypes.Union(typesInPlugins);
                }
                else
                {
                    allTypes = typesInPlugins;
                }
            }
            catch
            { }
            if (allTypes == null)
            {
                Config.LogError("ScritpLoader not found!");
                return(null);
            }

            var methods = allTypes.SelectMany(t => t.GetMethods(BindingFlags.Static | BindingFlags.Public))
                          .Where(m => m.GetCustomAttributes(typeof(LuaScriptLoaderAttribute), false).Length > 0)
                          .ToArray();

            if (methods.Length > 0)
            {
                var m = methods[0];
                cachedScriptLoader = (ScriptLoader)Delegate.CreateDelegate(typeof(ScriptLoader), m);
            }
            return(cachedScriptLoader);
        }
Exemple #33
0
        protected override void OnPreRender(EventArgs e)
        {
            ClientScriptProxy = ClientScriptProxy.Current;

            if (Visible && !string.IsNullOrEmpty(Text) && DisplayTimeout > 0)
            {
                // Embed the client script library as Web Resource Link
                ScriptLoader.LoadjQuery(this);

                string Script =
                    @"setTimeout(function() { $('#" + ClientID + @"').fadeOut('slow') }," + DisplayTimeout.ToString() + ");";

                //@"window.setTimeout(""document.getElementById('" + ClientID + @"').style.display='none';""," + DisplayTimeout.ToString() + @");";

                ClientScriptProxy.RegisterStartupScript(this, typeof(ErrorDisplay), "DisplayTimeout", Script, true);
            }
            base.OnPreRender(e);
        }
    private static void HandleUseScroll(GameSession session, Item equip, Item scroll, Dictionary <StatAttribute, ItemStat> enchantStats, int enchantLevel, int scrollId)
    {
        Script script      = ScriptLoader.GetScript("Functions/ItemEnchantScroll/getSuccessRate");
        float  successRate = (float)script.RunFunction("getSuccessRate", scrollId).Number;

        int  randomValue   = Random.Shared.Next(0, 10000 + 1);
        bool scrollSuccess = successRate * 10000 >= randomValue;

        session.Player.Inventory.ConsumeItem(session, scroll.Uid, 1);

        if (scrollSuccess)
        {
            equip.EnchantLevel   = enchantLevel;
            equip.EnchantExp     = 0;
            equip.Stats.Enchants = enchantStats;
            session.Send(EnchantScrollPacket.UseScroll((short)EnchantScrollError.None, equip));
        }
    }
Exemple #35
0
            /// <summary>
            /// handler for scriptloader progress messages
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="mea"></param>
            private void scriptLoader_NotifyMessage(ScriptLoader sender, ScriptLoader.MessageEventArgs mea)
            {
                AsyncMethodResponse response = new AsyncMethodResponse(this.clientProxy.ClientId, this.asyncTicket);

                Dictionary <Guid, ClientProxy> targetProxyMap = new Dictionary <Guid, ClientProxy>();

                targetProxyMap.Add(clientProxy.ClientId, clientProxy);

                //send null message for tick
                if (mea.IsProgressTick == true)
                {
                    CallbackManagerImpl.Instance.PublishMessage(targetProxyMap, null, response);
                }
                else
                {
                    CallbackManagerImpl.Instance.PublishMessage(targetProxyMap, mea.Message, response);
                }
            }
Exemple #36
0
 public ScriptLoaderProxy(ScriptLoader loader)
 {
     this.Loader = loader;
 }
Exemple #37
0
 public ResponseContainer(string a_filepathtoload, string a_name)
 {
     ScriptLoader sl = new ScriptLoader();
     sl.LoadScriptToList(a_filepathtoload, responses);
     name = a_name;
 }
Exemple #38
0
 public ThreadedTextProcessing(string a_filepath)
 {
     ScriptLoader sl = new ScriptLoader();
     sl.LoadScriptToList(a_filepath, referenceStrings);
 }
Exemple #39
0
    public ThreadedTextProcessing(string a_filepath, string a_name)
    {
        ScriptLoader sl = new ScriptLoader();
        sl.LoadScriptToList(a_filepath, referenceStrings);

        name = a_name;

        Debug.Log(name + " Threaded Processing Module Loaded");
    }
Exemple #40
0
        public SIPProxyCore(
            SIPMonitorLogDelegate proxyLogger,
            SIPTransport sipTransport,
            string scriptPath,
            string appServerEndPointsPath)
        {
            try
            {
                m_proxyLogger = proxyLogger ?? m_proxyLogger;
                m_scriptPath = scriptPath;
                m_sipTransport = sipTransport;

                if (!appServerEndPointsPath.IsNullOrBlank() && File.Exists(appServerEndPointsPath))
                {
                    m_sipCallDispatcherFile = new SIPCallDispatcherFile(SendMonitorEvent, appServerEndPointsPath);
                    m_sipCallDispatcherFile.LoadAndWatch();
                }
                else
                {
                    logger.Warn("No call dispatcher file specified for SIP Proxy.");
                }

                m_proxyDispatcher = new SIPProxyDispatcher(new SIPMonitorLogDelegate(SendMonitorEvent));
                GetAppServerDelegate getAppServer = (m_sipCallDispatcherFile != null) ? new GetAppServerDelegate(m_sipCallDispatcherFile.GetAppServer) : null;
                m_proxyScriptFacade = new SIPProxyScriptFacade(
                    new SIPMonitorLogDelegate(SendMonitorEvent),         // Don't use the m_proxyLogger delegate directly here as doing so caused stack overflow exceptions in the IronRuby engine.
                    sipTransport,
                    m_proxyDispatcher,
                    getAppServer);

                m_scriptLoader = new ScriptLoader(SendMonitorEvent, m_scriptPath);
                m_scriptLoader.ScriptFileChanged += (s, e) => { m_compiledScript = m_scriptLoader.GetCompiledScript(); };
                m_compiledScript = m_scriptLoader.GetCompiledScript();

                // Events that pass the SIP requests and responses onto the Stateless Proxy Core.
                m_sipTransport.SIPTransportRequestReceived += GotRequest;
                m_sipTransport.SIPTransportResponseReceived += GotResponse;
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPProxyCore (ctor). " + excp.Message);
                throw excp;
            }
        }
 /**
  * Notice that automatic compression doesn't work!
  */
 protected void Page_Load(object sender, EventArgs e)
 {
     _scriptloader = new ScriptLoader(type, directive, updateManagerDisabled);
 }
        private List<string> m_workerSIPEndPoints = new List<string>();                             // Allow quick lookups to determine whether a remote end point is that of a worker process.

        public SIPCallDispatcher(
            SIPMonitorLogDelegate logDelegate, 
            SIPTransport sipTransport, 
            XmlNode callDispatcherNode,
            SIPEndPoint outboundProxy,
            string dispatcherScriptPath) {

            if (callDispatcherNode == null || callDispatcherNode.ChildNodes.Count == 0) {
                throw new ArgumentNullException("A SIPCallDispatcher cannot be created with an empty configuration node.");
            }

            SIPMonitorLogEvent_External = logDelegate;
            m_sipTransport = sipTransport;
            m_callDispatcherNode = callDispatcherNode;
            m_outboundProxy = outboundProxy;
            m_dispatcherScriptPath = dispatcherScriptPath;

            m_scriptLoader = new ScriptLoader(SIPMonitorLogEvent_External, m_dispatcherScriptPath);
            m_scriptLoader.ScriptFileChanged += (s, e) => { m_compiledScript = m_scriptLoader.GetCompiledScript(); };
            m_compiledScript = m_scriptLoader.GetCompiledScript();

            try {
                CallManagerPassThruServiceInstanceProvider callManagerPassThruSvcInstanceProvider = new CallManagerPassThruServiceInstanceProvider(this);
                m_callManagerPassThruSvcHost = new ServiceHost(typeof(CallManagerPassThruService));
                m_callManagerPassThruSvcHost.Description.Behaviors.Add(callManagerPassThruSvcInstanceProvider);
                m_callManagerPassThruSvcHost.Open();

                logger.Debug("SIPCallDispatcher CallManagerPassThru hosted service successfully started on " + m_callManagerPassThruSvcHost.BaseAddresses[0].AbsoluteUri + ".");
            }
            catch (Exception excp) {
                logger.Warn("Exception starting SIPCallDispatcher CallManagerPassThru hosted service. " + excp.Message);
            }

            foreach (XmlNode callDispatcherWorkerNode in callDispatcherNode.ChildNodes) {
                SIPCallDispatcherWorker callDispatcherWorker = new SIPCallDispatcherWorker(callDispatcherWorkerNode);
                m_callDispatcherWorkers.Add(callDispatcherWorker);
                m_workerSIPEndPoints.Add(callDispatcherWorker.AppServerEndpoint.ToString());
                dispatcherLogger.Debug(" SIPCallDispatcher worker added for " + callDispatcherWorker.AppServerEndpoint.ToString() + " and " + callDispatcherWorker.CallManagerAddress.ToString() + ".");
            }

            ThreadPool.QueueUserWorkItem(delegate { SpawnWorkers(); });
            ThreadPool.QueueUserWorkItem(delegate { ProbeWorkers(); });
        }
Exemple #43
0
 void LoadResponses()
 {
     ScriptLoader sl = new ScriptLoader();
     string filepath = Application.dataPath + "/txt/";
     sl.LoadScriptToList(filepath + "responseNeutral.txt", neutralResponses);
     sl.LoadScriptToList(filepath + "responseNegative1.txt", negativeResponsesOne);
     sl.LoadScriptToList(filepath + "responseNoKeyword.txt", noKeywordResponses);
     sl.LoadScriptToList(filepath + "responsePositive.txt", positiveResponses);
 }