Exemplo n.º 1
0
        private void Initialise()
        {
            if (m_script != null) return;

            try
            {
                if (m_scriptConstructor == null)
                {
                    m_script = m_scriptFactory.CreateScript(m_scriptString, m_scriptContext, false, false);
                }
                else
                {
                    m_script = m_scriptConstructor.Create(m_scriptString, m_scriptContext);
                    m_script.Line = m_scriptString;
                }
            }
            catch
            {
                if (!m_worldModel.EditMode) throw;

                m_script = new FailedScript(m_scriptString);
                if (m_scriptConstructor == null)
                {
                    m_script = new MultiScript(m_scriptFactory.WorldModel, m_script);
                }
            }
            m_script.Parent = m_parent;
            m_scriptString = null;
        }
Exemplo n.º 2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ScriptSerializer"/> class.
        /// </summary>
        /// <param name="script">The script.</param>
        public ScriptSerializer(IScript script)
        {
            if (script == null)
                throw new ArgumentNullException("script");

            m_Script = script;
        }
Exemplo n.º 3
0
 public ForEachScript(ScriptContext scriptContext, string variable, IFunctionGeneric list, IScript loopScript)
 {
     m_scriptContext = scriptContext;
     m_variable = variable;
     m_list = list;
     m_loopScript = loopScript;
 }
Exemplo n.º 4
0
        public void Execute(GameTime gameTime)
        {
            if (scriptEnumerator == null)
            {
                scriptEnumerator = script.GetEnumerator();
                sleep = scriptEnumerator.Current;
            }

            if (sleep > 0)
            {
                sleep -= (float)gameTime.ElapsedGameTime.TotalSeconds;
            }
            else
            {
                bool finished = true;

                finished = !scriptEnumerator.MoveNext();
                sleep = scriptEnumerator.Current;

                if (finished)
                {
                    script = null;
                    scriptEnumerator = null;
                }
            }
        }
Exemplo n.º 5
0
        private bool IsRemoved(IScript script, IEnumerable<IScript> currentScripts, IEnumerable<IScript> scriptLog)
        {
            bool isInLog = scriptLog.Any(s => StrCmp(script.Name, s.Name));
            bool isInCurrent = currentScripts.Any(s => StrCmp(script.Name, s.Name));

            return isInLog && !isInCurrent;
        }
 public virtual void LogBuilt(IScript script)
 {
     if (SimpleSaveExtensions.LogBuiltScripts && Logger.IsDebugEnabled)
     {
         Logger.Debug(BuildDebugMessage(script, "Built script"));
     }
 }
Exemplo n.º 7
0
 public IfScript(IFunction<bool> expression, IScript thenScript, IScript elseScript, WorldModel worldModel)
 {
     m_expression = expression;
     m_thenScript = thenScript;
     m_elseScript = elseScript;
     m_worldModel = worldModel;
 }
 public virtual void LogPostExecution(IScript script)
 {
     if (SimpleSaveExtensions.LogScriptsPostExecution)
     {
         Log(script, "Executed script");
     }
 }
Exemplo n.º 9
0
 public FunctionCallScript(GameLoader loader, string procedure, IList<IFunction> parameters, IScript paramFunction)
 {
     m_loader = loader;
     m_procedure = procedure.Replace(" ", Utility.SpaceReplacementString);
     m_parameters = new FunctionCallParameters(parameters);
     m_paramFunction = paramFunction;
 }
 public virtual void LogPostExecution(IScript script)
 {
     if (Logger.IsInfoEnabled)
     {
         Logger.Info(BuildMessage(script, "Executed script"));
     }
 }
Exemplo n.º 11
0
        public SqlPlusScript(IScript script)
        {
            _script = script;

            _wrappedScriptPath = System.IO.Path.GetTempFileName();

            var reader = new ScriptReader();

            using (var fileStream = File.OpenWrite(_wrappedScriptPath))
            {
                using (var tempFile = new StreamWriter(fileStream, UTF8.WithoutByteOrderMark))
                {
                    tempFile.WriteLine("SET ECHO ON");
                    tempFile.WriteLine("WHENEVER SQLERROR EXIT SQL.SQLCODE");

                    foreach (var scriptLine in reader.GetContents(_script.Path))
                    {
                        tempFile.WriteLine(scriptLine);
                    }

                    tempFile.WriteLine("COMMIT;");
                    tempFile.WriteLine("EXIT");
                }
            }
        }
		/// <summary>
		/// Executes the script.
		/// </summary>
		/// <param name="p_scpScript">The C# Script to execute.</param>
		/// <returns><c>true</c> if the script completes successfully;
		/// <c>false</c> otherwise.</returns>
		/// <exception cref="ArgumentException">Thrown if <paramref name="p_scpScript"/> is not a
		/// <see cref="CSharpScript"/>.</exception>
		public override bool DoExecute(IScript p_scpScript)
		{
			if (!(p_scpScript is CSharpScript))
				throw new ArgumentException("The given script must be of type CSharpScript.", "p_scpScript");

			CSharpScript cscScript = (CSharpScript)p_scpScript;

			byte[] bteScript = Compile(cscScript.Code);
			if (bteScript == null)
				return false;

			AppDomain admScript = CreateSandbox(p_scpScript);
			try
			{
				m_csfFunctions.TaskStarted += new EventHandler<EventArgs<IBackgroundTask>>(Functions_TaskStarted);
				object[] args = { m_csfFunctions };
				AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
				ScriptRunner srnRunner = null;
				try
				{
					srnRunner = (ScriptRunner)admScript.CreateInstanceFromAndUnwrap(typeof(ScriptRunner).Assembly.ManifestModule.FullyQualifiedName, typeof(ScriptRunner).FullName, false, BindingFlags.Default, null, args, null, null);
				}
				finally
				{
					AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;
				}
				return srnRunner.Execute(bteScript);
			}
			finally
			{
				m_csfFunctions.TaskStarted -= Functions_TaskStarted;
				AppDomain.Unload(admScript);
			}
		}
Exemplo n.º 13
0
 public ScriptComponent(int gameObjectId, String gameObjectkey, IScript script)
 {
     m_ComponentType = ComponentType.Instance(Constant.enumComponent.SCRIPT);
     m_Script = script;
     m_GameObjectId = gameObjectId;
     m_GameObjectkey = gameObjectkey;
 }
Exemplo n.º 14
0
 public ForEachScript(WorldModel worldModel, string variable, IFunctionGeneric list, IScript loopScript)
 {
     m_worldModel = worldModel;
     m_variable = variable;
     m_list = list;
     m_loopScript = loopScript;
 }
Exemplo n.º 15
0
 public bool ScriptStarting(IScript script)
 {
     if (AskConfirmation(String.Format("Start script '{0}'", script.Name)))
         return scriptRunner.ScriptStarting(script);
     else
         return false;
 }
        public virtual void LogExecutionTime(long executionTimeMilliseconds, IScript script)
        {
            if (executionTimeMilliseconds > SimpleSaveExtensions.ExecutionTimeWarningEmitThresholdMilliseconds)
            {
                if (Logger.IsWarnEnabled)
                {
                    Logger.Warn(string.Format(
                        @"SIMPLESAVE SCRIPT EXECUTED IN {0}ms:
{1}
CALLING STACK TRACE:
{2}",
                        executionTimeMilliseconds,
                        script.Buffer,
                        Environment.StackTrace));
                }
            }
            else
            {
                if (Logger.IsInfoEnabled)
                {
                    Logger.Info(string.Format(
                        "SimpleSave script executed in {0}ms",
                        executionTimeMilliseconds));
                }
            }
        }
 public virtual void LogBuilt(IScript script)
 {
     if (Logger.IsDebugEnabled)
     {
         Logger.Debug(BuildMessage(script, "Built script"));
     }
 }
Exemplo n.º 18
0
 public GetInputScript(ScriptContext scriptContext, IScriptFactory scriptFactory, IScript callbackScript)
 {
     m_scriptContext = scriptContext;
     m_worldModel = scriptContext.WorldModel;
     m_scriptFactory = scriptFactory;
     m_callbackScript = callbackScript;
 }
Exemplo n.º 19
0
        public void Recompile()
        {
            if (_compiling)
                return;

            _host.Reset();
            Commands.Clear();
            _script = null;
            _compiling = true;

            Send("Compiling...");

            ThreadPool.QueueUserWorkItem(a =>
            {
                try
                {
                    var type = Compile();
                    if (type == null)
                        return;

                    Send("Done!");

                    SafeInvoke(() =>
                    {
                        _script = (IScript)Activator.CreateInstance(type);
                        _script.Initialize(_host);
                    });
                }
                finally
                {
                    _compiling = false;
                }
            });
        }
Exemplo n.º 20
0
 private Step(IScript script, String name, String description, ITask task, bool required)
 {
     this.script = script;
     this.name = name;
     this.description = description;
     this.required = required;
     this.task = task;
 }
Exemplo n.º 21
0
 public AskScript(ScriptContext scriptContext, IScriptFactory scriptFactory, IFunction<string> caption, IScript callbackScript)
 {
     m_scriptContext = scriptContext;
     m_worldModel = scriptContext.WorldModel;
     m_scriptFactory = scriptFactory;
     m_caption = caption;
     m_callbackScript = callbackScript;
 }
Exemplo n.º 22
0
 public static void AddOtherwiseScript(IScript firstTimeScript, string script, IScriptFactory scriptFactory)
 {
     // Get script after "otherwise" keyword
     script = script.Substring(9).Trim();
     string otherwise = Utility.GetScript(script);
     IScript otherwiseScript = scriptFactory.CreateScript(otherwise);
     ((FirstTimeScript)firstTimeScript).SetOtherwiseScript(otherwiseScript);
 }
 private object BuildInfoMessage(IScript script, string message)
 {
     return new
     {
         message,
         sql = script.Buffer.ToString(),
     };
 }
Exemplo n.º 24
0
 public YesNoResponse ContentChanged(IScript script)
 {
     using (ColorScope.WithColor(ConsoleColor.Red))
     {
         Console.Out.WriteLine("{0,35} : *** WARNING: Content changed", script.Name);
     }
     return YesNoResponse.Yes;
 }
Exemplo n.º 25
0
 public WhileScript(ScriptContext scriptContext, IScriptFactory scriptFactory, IFunction<bool> expression, IScript loopScript)
 {
     m_scriptContext = scriptContext;
     m_worldModel = scriptContext.WorldModel;
     m_scriptFactory = scriptFactory;
     m_expression = expression;
     m_loopScript = loopScript;
 }
Exemplo n.º 26
0
 public ShowMenuScript(IScriptFactory scriptFactory, IFunction caption, IFunction options, IFunction allowCancel, IScript callbackScript)
 {
     m_scriptFactory = scriptFactory;
     m_caption = caption;
     m_options = options;
     m_allowCancel = allowCancel;
     m_callbackScript = callbackScript;
 }
Exemplo n.º 27
0
 public YesNoResponse ScriptRemoved(IScript script)
 {
     using (ColorScope.WithColor(ConsoleColor.Red))
     {
         Console.Out.WriteLine("{0,35} : *** WARNING: Script removed from disk", script.Name);
     }
     return YesNoResponse.Yes;
 }
		/// <summary>
		/// </summary>
		/// <param name="script"></param>
		/// <param name="innerException"></param>
		protected ScriptExecutionException(IScript script, Exception innerException) : base(string.Empty, innerException)
		{
			// validate arguments
			if (script == null)
				throw new ArgumentNullException("script");

			// set values
			Script = script;
		}
Exemplo n.º 29
0
 public ForScript(WorldModel worldModel, IScriptFactory scriptFactory, string variable, IFunction<int> from, IFunction<int> to, IScript loopScript)
 {
     m_worldModel = worldModel;
     m_scriptFactory = scriptFactory;
     m_variable = variable;
     m_from = from;
     m_to = to;
     m_loopScript = loopScript;
 }
 private object BuildDebugMessage(IScript script, string message)
 {
     return new
     {
         message,
         sql = script.Buffer.ToString(),
         parameters = JsonConvert.SerializeObject(script.Parameters)
     };
 }
 protected override IList <GameObject> GetEligibleGameObjects(IScript target)
 {
     return(GetDependencySources(target, typeof(GameObject)));
 }
Exemplo n.º 32
0
 public OnReadyScript(ScriptContext scriptContext, IScriptFactory scriptFactory, IScript callbackScript)
 {
     m_scriptContext  = scriptContext;
     m_worldModel     = scriptContext.WorldModel;
     m_scriptFactory  = scriptFactory;
     m_callbackScript = callbackScript;
 }
Exemplo n.º 33
0
 /// <inheritdoc/>
 public IEnumerable <string> Split(IScript script)
 {
     return(new string[] { script.Text });
 }
Exemplo n.º 34
0
        private static void ProcessScripts(XElement updates)
        {
            try
            {
                Console.WriteLine("Searching for scripts...");

                Dictionary <string, string> scripts = new Dictionary <string, string>();
                foreach (string scriptsPath in ScriptsPaths)
                {
                    foreach (string scriptFile in Directory.GetFiles(scriptsPath, "*.boo"))
                    {
                        //Later files override earlier ones of the same name
                        scripts[Path.GetFileName(scriptFile).ToLowerInvariant()] = scriptFile;
                    }
                }

                //HACK: Remove known common files
                scripts.Remove("util.boo");
                scripts.Remove("amazon-common.boo");

                //HACK: Remove specific files that shouldn't be included
                scripts.Remove("coverlandia.boo");

                foreach (string scriptFile in scripts.Values)
                {
                    try
                    {
                        Console.Write(String.Format("Processing {0}... ", Path.GetFileName(scriptFile)));

                        using (StreamReader reader = File.OpenText(scriptFile))
                        {
                            List <string> references = new List <string>();

                            string firstLine = reader.ReadLine();
                            if (firstLine.StartsWith("# refs: ") && firstLine.Length > 8)
                            {
                                string refsText = firstLine.Substring(8);
                                references.AddRange(refsText.Split(' '));
                            }

                            BooCompiler compiler = new BooCompiler();
                            compiler.Parameters.Ducky      = true;                        //Required to allow late-binding to "coverart" parameter
                            compiler.Parameters.OutputType = CompilerOutputType.Library;
                            compiler.Parameters.Debug      = false;
                            compiler.Parameters.Pipeline   = new CompileToMemory();

                            //HACK: Add known common files and references (as each script is being compiled individually
                            compiler.Parameters.Input.Add(new FileInput(Path.Combine(Path.GetDirectoryName(scriptFile), "util.boo")));
                            compiler.Parameters.Input.Add(new FileInput(Path.Combine(Path.GetDirectoryName(scriptFile), "amazon-common.boo")));
                            references.Add("System.Web");
                            references.Add("System.Core");

                            //Console.WriteLine(String.Format("Loading references: [{0}]...", string.Join(", ", references.ToArray())));
                            foreach (string reference in references)
                            {
                                compiler.Parameters.References.Add(compiler.Parameters.LoadAssembly(reference, true));
                            }

                            compiler.Parameters.Input.Add(new FileInput(scriptFile));

                            CompilerContext compilerContext = compiler.Run();

                            bool result;
                            if (compilerContext.Errors.Count > 0)
                            {
                                Console.WriteLine("failed.");
                                result = false;                                 //faliure
                            }
                            else if (compilerContext.Warnings.Count > 0)
                            {
                                Console.WriteLine("done, but with warnings.");
                                result = true;                                 //Allow to continue
                            }
                            else
                            {
                                Console.WriteLine("done.");
                                result = true;                                 //Success
                            }

                            //Report warnings and errors
                            foreach (CompilerWarning warning in compilerContext.Warnings)
                            {
                                ReportCompilerIssue("warning", warning.LexicalInfo, warning.Code, warning.Message);
                            }
                            foreach (CompilerError error in compilerContext.Errors)
                            {
                                ReportCompilerIssue("error", error.LexicalInfo, error.Code, error.Message);
                            }

                            if (result)
                            {
                                //Find the script type
                                foreach (Type type in compilerContext.GeneratedAssembly.GetTypes())
                                {
                                    try
                                    {
                                        IScript script = null;
                                        //Check for types implementing IScript
                                        if (typeof(IScript).IsAssignableFrom(type))
                                        {
                                            if (!type.IsAbstract)
                                            {
                                                script = (IScript)Activator.CreateInstance(type);
                                            }
                                        }
                                        //Check for static scripts (for backwards compatibility)
                                        else if (type.Namespace == "CoverSources")
                                        {
                                            script = new StaticScript(type);
                                        }

                                        if (script != null)
                                        {
                                            //Obtain name and version number
                                            var scriptXml = new XElement("Script",
                                                                         new XAttribute("Name", script.Name),
                                                                         new XAttribute("URI", Path.GetFileName(scriptFile)),
                                                                         new XAttribute("Version", script.Version));

                                            //Hack: Add dependency to known dependent files
                                            if (script.Name.StartsWith("Amazon "))
                                            {
                                                scriptXml.Add(new XElement("Dependency", "amazon-common.boo"));
                                            }

                                            updates.Add(scriptXml);
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        //Skip the type. Does this need to display a user error message?
                                        Console.WriteLine(String.Format("Could not load script: {0}\n\n{1}", type.Name, e.Message));
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception fileReadingException)
                    {
                        Console.WriteLine(String.Format("Skipping unreadable file: \"{0}\"\n  {1}", scriptFile, fileReadingException.Message));
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(String.Format("\nError: {0}\n", exception.Message));
            }
        }
Exemplo n.º 35
0
        public void GetP2sh_P2wshTest(IScript script, byte witVer, NetworkType netType, string expected)
        {
            string actual = Address.GetP2sh_P2wsh(script, witVer, netType);

            Assert.Equal(expected, actual);
        }
Exemplo n.º 36
0
 protected override IList <GameObject> GetEligibleGameObjects(IScript target)
 {
     return(target.GetRoot().GetAllHierachy());
 }
Exemplo n.º 37
0
 public ScriptResult(IScript script, object thumbnail, string name, int width, int height, object fullSizeImageCallbackParameter)
     : this(script, thumbnail, name, width, height, fullSizeImageCallbackParameter, CoverType.Unknown)
 {
 }
Exemplo n.º 38
0
        public Props Build(IScript script)
        {
            var innerFactory = _factories.Single(x => x.SupportedCompetitionNames.Contains(script.ScriptType));

            return(innerFactory.Build(script));
        }
        private static IScriptField ToScript(IScript script) => script != null ? new ScriptField
        {
            Script = script
        }

                                                                                                                             : null;
Exemplo n.º 40
0
        /// <summary>
        ///   This starts the script and sets up the variables.
        /// </summary>
        /// <returns></returns>
        public bool Start(bool reupload)
        {
            DateTime StartTime = DateTime.Now.ToUniversalTime();

            Running   = true;
            Suspended = false;

            //Clear out the removing of events for this script.
            IgnoreNew = false;
            Interlocked.Increment(ref VersionID);

            //Reset this
            StartedFromSavedState = false;

            //Clear out previous errors if they were not cleaned up
            m_ScriptEngine.ScriptErrorReporter.RemoveError(ItemID);

            //Find the inventory item
            Part.TaskInventory.TryGetValue(ItemID, out InventoryItem);

            if (InventoryItem == null)
            {
                MainConsole.Instance.Warn("[ADNE]: Could not find inventory item for script " + ItemID + ", part" + Part.Name + "@" +
                                          Part.AbsolutePosition);
                return(false);
            }

            //Try to see if this was rezzed from someone's inventory
            UserInventoryItemID = Part.FromUserInventoryItemID;

            //Try to find the avatar who started this.
            IScenePresence presence = World.GetScenePresence(Part.OwnerID);


            //Now that the initial loading is complete,
            // we need to find the state save and start loading the info from it

            StateSave LastStateSave = m_ScriptEngine.StateSave.FindScriptStateSave(this);

            if (!reupload && Loading && LastStateSave != null)
            {
                //Deserialize the most important pieces first
                Source = LastStateSave.Source;
            }
            if (string.IsNullOrEmpty(Source))
            {
                AssetBase asset = Part.ParentEntity.Scene.AssetService.Get(InventoryItem.AssetID.ToString());
                if (null == asset)
                {
                    MainConsole.Instance.ErrorFormat(
                        "[ScriptData]: " +
                        "Couldn't start script {0}, {1} at {2} in {3} since asset ID {4} could not be found",
                        InventoryItem.Name, InventoryItem.ItemID, Part.AbsolutePosition,
                        Part.ParentEntity.Scene.RegionInfo.RegionName, InventoryItem.AssetID);
                    ScriptEngine.ScriptProtection.RemoveScript(this);
                    return(false);
                }
                Source = Utils.BytesToString(asset.Data);
            }
            if (string.IsNullOrEmpty(Source))
            {
                MainConsole.Instance.ErrorFormat(
                    "[ScriptData]: " +
                    "Couldn't start script {0}, {1} at {2} in {3} since asset ID {4} could not be found",
                    InventoryItem.Name, InventoryItem.ItemID, Part.AbsolutePosition,
                    Part.ParentEntity.Scene.RegionInfo.RegionName, InventoryItem.AssetID);
                ScriptEngine.ScriptProtection.RemoveScript(this);
                return(false);
            }

            #region HTML Reader

            if (ScriptEngine.ScriptProtection.AllowHTMLLinking)
            {
                //Read the URL and load it.
                if (Source.Contains("#IncludeHTML "))
                {
                    string URL  = "";
                    int    line = Source.IndexOf("#IncludeHTML ");
                    URL = Source.Remove(0, line);
                    URL = URL.Replace("#IncludeHTML ", "");
                    URL = URL.Split('\n')[0];
                    string webSite = Utilities.ReadExternalWebsite(URL);
                    Source = Source.Replace("#IncludeHTML " + URL, webSite);
                }
            }
            else
            {
                //Remove the line then
                if (Source.Contains("#IncludeHTML "))
                {
                    string URL  = "";
                    int    line = Source.IndexOf("#IncludeHTML ");
                    URL    = Source.Remove(0, line);
                    URL    = URL.Replace("#IncludeHTML ", "");
                    URL    = URL.Split('\n')[0];
                    Source = Source.Replace("#IncludeHTML " + URL, "");
                }
            }

            #endregion

            //Find the default state save
            DefaultState = m_ScriptEngine.Compiler.FindDefaultStateForScript(Source);
            State        = DefaultState;

            //If the saved state exists, if it isn't a reupload (something changed), and if the assembly exists, load the state save
            if (!reupload && Loading && LastStateSave != null &&
                File.Exists(LastStateSave.AssemblyName))
            {
                //Retrive the previous assembly
                AssemblyName = LastStateSave.AssemblyName;
            }
            else
            {
                Compiled = false;
                //if (!reupload && Loading && LastStateSave != null && !LastStateSave.Compiled)
                //    return false;//If we're trying to start up and we failed before, just give up
                if (reupload)
                {
                    LastStateSave = null;
                    //Close the previous script
                    CloseAndDispose(false);                                                //We don't want to back it up
                    Interlocked.Increment(ref VersionID);
                    m_ScriptEngine.MaintenanceThread.SetEventSchSetIgnoreNew(this, false); // accept new events
                }

                //Try to find a previously compiled script in this instance
                string PreviouslyCompiledAssemblyName =
                    ScriptEngine.ScriptProtection.TryGetPreviouslyCompiledScript(Source);
                if (PreviouslyCompiledAssemblyName != null)
                {
                    //Already exists in this instance, so we do not need to check whether it exists
                    AssemblyName = PreviouslyCompiledAssemblyName;
                }
                else
                {
                    try
                    {
                        m_ScriptEngine.Compiler.PerformScriptCompile(Source, ItemID, Part.OwnerID, out AssemblyName);

                        #region Errors and Warnings

                        #region Errors

                        string[] compileerrors = m_ScriptEngine.Compiler.GetErrors();

                        if (compileerrors.Length != 0)
                        {
                            string error = string.Empty;
                            foreach (string compileerror in compileerrors)
                            {
                                error += compileerror;
                            }
                            DisplayUserNotification(error, "compiling", reupload, true);
                            //It might have failed, but we still need to add it so that we can reuse this script data class later
                            ScriptEngine.ScriptProtection.AddNewScript(this);
                            m_ScriptEngine.StateSave.SaveStateTo(this, true);
                            return(false);
                        }

                        #endregion

                        #region Warnings

                        if (m_ScriptEngine.ShowWarnings)
                        {
                            string[] compilewarnings = m_ScriptEngine.Compiler.GetWarnings();

                            if (compilewarnings != null && compilewarnings.Length != 0)
                            {
                                string error = string.Empty;
                                foreach (string compileerror in compilewarnings)
                                {
                                    error += compileerror;
                                }
                                DisplayUserNotification(error, "compiling", reupload, false);
                                //It might have failed, but we still need to add it so that we can reuse this script data class later
                                ScriptEngine.ScriptProtection.AddNewScript(this);
                                return(false);
                            }
                        }

                        #endregion

                        #endregion
                    }
                    catch (Exception ex)
                    {
                        //LEAVE IT AS ToString() SO THAT WE GET THE STACK TRACE TOO
                        DisplayUserNotification(ex.ToString(), "(exception) compiling", reupload, true);
                        //It might have failed, but we still need to add it so that we can reuse this script data class later
                        ScriptEngine.ScriptProtection.AddNewScript(this);
                        return(false);
                    }
                }
            }

            bool useDebug = false;
            if (useDebug)
            {
                MainConsole.Instance.Debug("[" + m_ScriptEngine.ScriptEngineName + "]: Stage 1 compile: " +
                                           (DateTime.Now.ToUniversalTime() - StartTime).TotalSeconds);
            }

            //Create the app domain if needed.
            try
            {
                Script = m_ScriptEngine.AppDomainManager.LoadScript(AssemblyName, "Script.ScriptClass", out AppDomain);
                m_ScriptEngine.Compiler.FinishCompile(this, Script);
                //Add now so that we don't add it too early and give it the possibility to fail
                ScriptEngine.ScriptProtection.AddPreviouslyCompiled(Source, this);
            }
            catch (FileNotFoundException) // Not valid!!!
            {
                MainConsole.Instance.Error("[" + m_ScriptEngine.ScriptEngineName +
                                           "]: File not found in app domain creation. Corrupt state save! " + AssemblyName);
                ScriptEngine.ScriptProtection.RemovePreviouslyCompiled(Source);
                return(Start(reupload)); // Lets restart the script if this happens
            }
            catch (Exception ex)
            {
                DisplayUserNotification(ex.ToString(), "app domain creation", reupload, true);
                //It might have failed, but we still need to add it so that we can reuse this script data class later
                ScriptEngine.ScriptProtection.AddNewScript(this);
                return(false);
            }
            Source   = null; //Don't keep it in memory, we don't need it anymore
            Compiled = true; //We compiled successfully

            //ILease lease = (ILease)RemotingServices.GetLifetimeService(Script as MarshalByRefObject);
            //if (lease != null) //Its null if it is all running in the same app domain
            //    lease.Register(Script.Sponsor);

            //If its a reupload, an avatar is waiting for the script errors
            if (reupload)
            {
                m_ScriptEngine.ScriptErrorReporter.AddError(ItemID, new ArrayList(new[] { "SUCCESSFULL" }));
            }

            if (useDebug)
            {
                MainConsole.Instance.Debug("[" + m_ScriptEngine.ScriptEngineName + "]: Stage 2 compile: " +
                                           (DateTime.Now.ToUniversalTime() - StartTime).TotalSeconds);
            }

            SetApis();

            //Now do the full state save finding now that we have an app domain.
            if (LastStateSave != null)
            {
                string assy = AssemblyName;
                // don't restore the assembly name, the one we have is right (if re-compiled or not)
                m_ScriptEngine.StateSave.Deserialize(this, LastStateSave);
                AssemblyName = assy;
                if (this.State == "" && DefaultState != this.State)
                //Sometimes, "" is a valid state for other script languages
                {
                    MainConsole.Instance.Warn("BROKEN STATE SAVE!!! - " + this.Part.Name + " @ " + this.Part.AbsolutePosition);
                    this.State = DefaultState;
                    m_ScriptEngine.StateSave.SaveStateTo(this, true);
                }
                // we get new rez events on sim restart, too
                // but if there is state, then we fire the change
                // event
                StartedFromSavedState = true;

                // ItemID changes sometimes (not sure why, but observed it)
                // If so we want to clear out the old save state,
                // which would otherwise have hung around in the object forever
                if (LastStateSave.ItemID != ItemID)
                {
                    m_ScriptEngine.StateSave.DeleteFrom(Part, LastStateSave.ItemID);
                    m_ScriptEngine.StateSave.SaveStateTo(this, true);
                }
            }
            else
            {
                //Make a new state save now
                m_ScriptEngine.StateSave.SaveStateTo(this, true);
            }

            //Set the event flags
            Part.SetScriptEvents(ItemID, Script.GetStateEventFlags(State));

            // Add it to our script memstruct so it can be found by other scripts
            ScriptEngine.ScriptProtection.AddNewScript(this);

            //All done, compiled successfully
            Loading = false;

            if (MainConsole.Instance.IsDebugEnabled)
            {
                TimeSpan time = (DateTime.Now.ToUniversalTime() - StartTime);

                MainConsole.Instance.Debug("[" + m_ScriptEngine.ScriptEngineName +
                                           "]: Started Script " + InventoryItem.Name +
                                           " in object " + Part.Name + "@" + Part.ParentEntity.RootChild.AbsolutePosition +
                                           (presence != null ? " by " + presence.Name : "") +
                                           " in region " + Part.ParentEntity.Scene.RegionInfo.RegionName +
                                           " in " + time.TotalSeconds + " seconds.");
            }
            return(true);
        }
Exemplo n.º 41
0
 public void FinishCompile(IScriptModulePlugin plugin, ScriptData data, IScript Script)
 {
 }
Exemplo n.º 42
0
        /// <summary>
        ///   This closes the scrpit, removes it from any known spots, and disposes of itself.
        /// </summary>
        /// <param name = "shouldbackup">Should we back up this script and fire state_exit?</param>
        public void CloseAndDispose(bool shouldbackup)
        {
            m_ScriptEngine.MaintenanceThread.RemoveFromEventSchQueue(this, true);

            if (shouldbackup)
            {
                if (Script != null)
                {
                    /*
                     * //Fire this directly so its not closed before its fired
                     * SetEventParams("state_exit", new DetectParams[0]);
                     *
                     * m_ScriptEngine.MaintenanceThread.ProcessQIS(new QueueItemStruct()
                     * {
                     *  ID = this,
                     *  CurrentlyAt = null,
                     *  functionName = "state_exit",
                     *  param = new object[0],
                     *  llDetectParams = new DetectParams[0],
                     *  VersionID = VersionID
                     * });
                     */
                    // dont think we should fire state_exit here
                    //                    m_ScriptEngine.MaintenanceThread.DoAndWaitEventSch(this, "state_exit",
                    //                        new DetectParams[0], VersionID, EventPriority.FirstStart, new object[0]);
                    m_ScriptEngine.StateSave.SaveStateTo(this);
                }
            }
            if (Script != null)
            {
                //Fire the exit event for scripts that support it
                Exception      ex;
                EnumeratorInfo info = null;
                while ((info = Script.ExecuteEvent(State, "exit", new object[0], info, out ex))
                       != null)
                {
                }
            }
            m_ScriptEngine.MaintenanceThread.SetEventSchSetIgnoreNew(this, false);

            //Give the user back any controls we took
            ReleaseControls();

            // Tell script not to accept new requests
            //These are fine to set as the state wont be saved again
            if (shouldbackup)
            {
                Running  = false;
                Disabled = true;
            }

            // Remove from internal structure
            ScriptEngine.ScriptProtection.RemoveScript(this);
            //            if (!Silent) //Don't remove on a recompile because we'll make it under a different assembly
            //                ScriptEngine.ScriptProtection.RemovePreviouslyCompiled(Source);

            //Remove any errors that might be sitting around
            m_ScriptEngine.ScriptErrorReporter.RemoveError(ItemID);

            #region Clean out script parts

            //Only if this script changed target omega do we reset it
            if (TargetOmegaWasSet)
            {
                Part.AngularVelocity = Vector3.Zero;                  // Removed in SL
                Part.ScheduleUpdate(PrimUpdateFlags.AngularVelocity); // Send changes to client.
            }

            #endregion

            if (Script != null)
            {
                // Stop long command on script
                m_ScriptEngine.RemoveScriptFromPlugins(Part.UUID, ItemID);

                //Release the script and destroy it
                ILease lease = (ILease)RemotingServices.GetLifetimeService(Script as MarshalByRefObject);
                if (lease != null)
                {
                    lease.Unregister(Script.Sponsor);
                }

                Script.Close();
                Script = null;
            }

            MainConsole.Instance.Debug("[" + m_ScriptEngine.ScriptEngineName + "]: Closed Script " + InventoryItem.Name + " in " +
                                       Part.Name);
            if (AppDomain == null)
            {
                return;
            }

            // Tell AppDomain that we have stopped script
            m_ScriptEngine.AppDomainManager.UnloadScriptAppDomain(AppDomain);
            AppDomain = null;
        }
Exemplo n.º 43
0
        public RequireDefine(ScriptEngine scriptEngine, IScript fromScript)
        {
            _scriptEngine = scriptEngine;

            _fromScript = fromScript;
        }
Exemplo n.º 44
0
 public override void LogBuilt(IScript script)
 {
     _scripts.Add(script);
     base.LogPreExecution(script);
 }
Exemplo n.º 45
0
        public ScriptInstance(IScriptEngine engine, SceneObjectPart part,
                              UUID itemID, UUID assetID, string assembly,
                              AppDomain dom, string primName, string scriptName,
                              int startParam, bool postOnRez, StateSource stateSource,
                              int maxScriptQueue)
        {
            State      = "default";
            EventQueue = new Queue(32);

            Engine           = engine;
            LocalID          = part.LocalId;
            ObjectID         = part.UUID;
            RootLocalID      = part.ParentGroup.LocalId;
            RootObjectID     = part.ParentGroup.UUID;
            ItemID           = itemID;
            AssetID          = assetID;
            PrimName         = primName;
            ScriptName       = scriptName;
            m_Assembly       = assembly;
            StartParam       = startParam;
            m_MaxScriptQueue = maxScriptQueue;
            m_stateSource    = stateSource;
            m_postOnRez      = postOnRez;
            m_AttachedAvatar = part.ParentGroup.AttachedAvatar;
            m_RegionID       = part.ParentGroup.Scene.RegionInfo.RegionID;

            if (part != null)
            {
                lock (part.TaskInventory)
                {
                    if (part.TaskInventory.ContainsKey(ItemID))
                    {
                        ScriptTask = part.TaskInventory[ItemID];
                    }
                }
            }

            ApiManager am = new ApiManager();

            foreach (string api in am.GetApis())
            {
                m_Apis[api] = am.CreateApi(api);
                m_Apis[api].Initialize(engine, part, ScriptTask);
            }

            try
            {
                if (dom != System.AppDomain.CurrentDomain)
                {
                    m_Script = (IScript)dom.CreateInstanceAndUnwrap(
                        Path.GetFileNameWithoutExtension(assembly),
                        "SecondLife.Script");
                }
                else
                {
                    m_Script = (IScript)Assembly.Load(
                        Path.GetFileNameWithoutExtension(assembly)).CreateInstance(
                        "SecondLife.Script");
                }

                //ILease lease = (ILease)RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass);
                //RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass);
//                lease.Register(this);
            }
            catch (Exception e)
            {
                m_log.ErrorFormat(
                    "[SCRIPT INSTANCE]: Error loading assembly {0}.  Exception {1}{2}",
                    assembly, e.Message, e.StackTrace);
            }

            try
            {
                foreach (KeyValuePair <string, IScriptApi> kv in m_Apis)
                {
                    m_Script.InitApi(kv.Key, kv.Value);
                }

//                // m_log.Debug("[Script] Script instance created");

                part.SetScriptEvents(ItemID,
                                     (int)m_Script.GetStateEventFlags(State));
            }
            catch (Exception e)
            {
                m_log.ErrorFormat(
                    "[SCRIPT INSTANCE]: Error loading script instance from assembly {0}.  Exception {1}{2}",
                    assembly, e.Message, e.StackTrace);

                return;
            }

            m_SaveState = true;

            string savedState = Path.Combine(Path.GetDirectoryName(assembly),
                                             ItemID.ToString() + ".state");

            if (File.Exists(savedState))
            {
                string xml = String.Empty;

                try
                {
                    FileInfo fi   = new FileInfo(savedState);
                    int      size = (int)fi.Length;
                    if (size < 512000)
                    {
                        using (FileStream fs = File.Open(savedState,
                                                         FileMode.Open, FileAccess.Read, FileShare.None))
                        {
                            Byte[] data = new Byte[size];
                            fs.Read(data, 0, size);

                            xml = Encoding.UTF8.GetString(data);

                            ScriptSerializer.Deserialize(xml, this);

                            AsyncCommandManager.CreateFromData(Engine,
                                                               LocalID, ItemID, ObjectID,
                                                               PluginData);

//                            m_log.DebugFormat("[Script] Successfully retrieved state for script {0}.{1}", PrimName, m_ScriptName);

                            part.SetScriptEvents(ItemID,
                                                 (int)m_Script.GetStateEventFlags(State));

                            if (!Running)
                            {
                                m_startOnInit = false;
                            }

                            Running = false;

                            // we get new rez events on sim restart, too
                            // but if there is state, then we fire the change
                            // event

                            // We loaded state, don't force a re-save
                            m_SaveState             = false;
                            m_startedFromSavedState = true;
                        }
                    }
                    else
                    {
                        m_log.WarnFormat(
                            "[SCRIPT INSTANCE]: Unable to load script state file {0} for script {1} {2} in {3} {4} (assembly {5}).  Memory limit exceeded",
                            savedState, ScriptName, ItemID, PrimName, ObjectID, assembly);
                    }
                }
                catch (Exception e)
                {
                    m_log.ErrorFormat(
                        "[SCRIPT INSTANCE]: Unable to load script state file {0} for script {1} {2} in {3} {4} (assembly {5}).  XML is {6}.  Exception {7}{8}",
                        savedState, ScriptName, ItemID, PrimName, ObjectID, assembly, xml, e.Message, e.StackTrace);
                }
            }
//            else
//            {
//                ScenePresence presence = Engine.World.GetScenePresence(part.OwnerID);

//                if (presence != null && (!postOnRez))
//                    presence.ControllingClient.SendAgentAlertMessage("Compile successful", false);

//            }
        }
 public void Add(string name, IScript script) => BackingDictionary.Add(name, new ScriptField {
     Script = script
 });
Exemplo n.º 47
0
 protected override IList <object> GetEligibleDependencies(IScript target, Type dependencyType)
 {
     return(new List <object>(target.GetComponentsInChildrensParentsOrSiblings(dependencyType)));
 }
Exemplo n.º 48
0
 public ScriptRunner(IScriptExecutor executor, IScript script)
 {
     m_Executor = executor;
     m_Script   = script;
 }
Exemplo n.º 49
0
 public ITS_EDITOR(IScript script) : this()
 {
     Script = script;
     Text   = script.Deserialize();
 }
Exemplo n.º 50
0
 internal void FinishCompile(ScriptData scriptData, IScript Script)
 {
     FindConverterForScript(scriptData.Source).FinishCompile(m_scriptEngine, scriptData, Script);
 }
Exemplo n.º 51
0
 protected override IList <GameObject> GetEligibleGameObjects(IScript target)
 {
     return(target.GetAllParents());
 }
Exemplo n.º 52
0
        public ScriptInstance(IScriptEngine engine, SceneObjectPart part,
                              UUID itemID, UUID assetID, string assembly,
                              AppDomain dom, string primName, string scriptName,
                              int startParam, bool postOnRez, StateSource stateSource,
                              int maxScriptQueue)
        {
            m_Engine = engine;

            m_LocalID        = part.LocalId;
            m_ObjectID       = part.UUID;
            m_ItemID         = itemID;
            m_AssetID        = assetID;
            m_PrimName       = primName;
            m_ScriptName     = scriptName;
            m_Assembly       = assembly;
            m_StartParam     = startParam;
            m_MaxScriptQueue = maxScriptQueue;
            m_stateSource    = stateSource;
            m_postOnRez      = postOnRez;
            m_RegionID       = part.ParentGroup.Scene.RegionInfo.RegionID;

            if (part != null)
            {
                lock (part.TaskInventory)
                {
                    if (part.TaskInventory.ContainsKey(m_ItemID))
                    {
                        m_thisScriptTask = part.TaskInventory[m_ItemID];
                    }
                }
            }

            ApiManager am = new ApiManager();

            foreach (string api in am.GetApis())
            {
                m_Apis[api] = am.CreateApi(api);
                m_Apis[api].Initialize(engine, part, m_LocalID, itemID);
            }

            try
            {
                m_Script = (IScript)dom.CreateInstanceAndUnwrap(
                    Path.GetFileNameWithoutExtension(assembly),
                    "SecondLife.Script");

                // Add a sponsor to the script
//                ISponsor scriptSponsor = new ScriptSponsor();
//                ILease lease = (ILease)RemotingServices.GetLifetimeService(m_Script as MarshalByRefObject);
//                lease.Register(scriptSponsor);
                //m_ScriptSponsor = scriptSponsor;
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[Script] Error loading assembly {0}\n" + e.ToString(), assembly);
            }

            try
            {
                foreach (KeyValuePair <string, IScriptApi> kv in m_Apis)
                {
                    m_Script.InitApi(kv.Key, kv.Value);
                }

//                m_log.Debug("[Script] Script instance created");

                part.SetScriptEvents(m_ItemID,
                                     (int)m_Script.GetStateEventFlags(State));
            }
            catch (Exception e)
            {
                m_log.Error("[Script] Error loading script instance\n" + e.ToString());
                return;
            }

            m_SaveState = true;

            string savedState = Path.Combine(Path.GetDirectoryName(assembly),
                                             m_ItemID.ToString() + ".state");

            if (File.Exists(savedState))
            {
                string xml = String.Empty;

                try
                {
                    FileInfo fi   = new FileInfo(savedState);
                    int      size = (int)fi.Length;
                    if (size < 512000)
                    {
                        using (FileStream fs = File.Open(savedState,
                                                         FileMode.Open, FileAccess.Read, FileShare.None))
                        {
                            System.Text.ASCIIEncoding enc =
                                new System.Text.ASCIIEncoding();

                            Byte[] data = new Byte[size];
                            fs.Read(data, 0, size);

                            xml = enc.GetString(data);

                            ScriptSerializer.Deserialize(xml, this);

                            AsyncCommandManager.CreateFromData(m_Engine,
                                                               m_LocalID, m_ItemID, m_ObjectID,
                                                               PluginData);

//                            m_log.DebugFormat("[Script] Successfully retrieved state for script {0}.{1}", m_PrimName, m_ScriptName);

                            part.SetScriptEvents(m_ItemID,
                                                 (int)m_Script.GetStateEventFlags(State));

                            if (m_RunEvents && (!m_ShuttingDown))
                            {
                                m_RunEvents = false;
                            }
                            else
                            {
                                m_RunEvents   = false;
                                m_startOnInit = false;
                            }

                            // we get new rez events on sim restart, too
                            // but if there is state, then we fire the change
                            // event

                            // We loaded state, don't force a re-save
                            m_SaveState             = false;
                            m_startedFromSavedState = true;
                        }
                    }
                    else
                    {
                        m_log.Error("[Script] Unable to load script state: Memory limit exceeded");
                    }
                }
                catch (Exception e)
                {
                    m_log.ErrorFormat("[Script] Unable to load script state from xml: {0}\n" + e.ToString(), xml);
                }
            }
            else
            {
                ScenePresence presence = m_Engine.World.GetScenePresence(part.OwnerID);

                if (presence != null && (!postOnRez))
                {
                    presence.ControllingClient.SendAgentAlertMessage("Compile successful", false);
                }

//                m_log.ErrorFormat("[Script] Unable to load script state, file not found");
            }
        }
 public FunctionCallScript(GameLoader loader, string procedure, IList <IFunction> parameters, IScript paramFunction)
 {
     m_loader        = loader;
     m_procedure     = procedure.Replace(" ", Utility.SpaceReplacementString);
     m_parameters    = new FunctionCallParameters(parameters);
     m_paramFunction = paramFunction;
 }
Exemplo n.º 54
0
 public Executor(IScript script)
 {
     m_Script = script;
     initEventFlags();
 }
Exemplo n.º 55
0
        /// <summary>
        /// Load the script from an assembly into an AppDomain.
        /// </summary>
        /// <param name='dom'></param>
        /// <param name='assembly'></param>
        /// <param name='stateSource'></param>
        /// <returns>false if load failed, true if suceeded</returns>
        public bool Load(AppDomain dom, string assembly, StateSource stateSource)
        {
            m_Assembly    = assembly;
            m_stateSource = stateSource;

            ApiManager am = new ApiManager();

            foreach (string api in am.GetApis())
            {
                m_Apis[api] = am.CreateApi(api);
                m_Apis[api].Initialize(Engine, Part, ScriptTask, m_coopSleepHandle);
            }

            try
            {
                object[] constructorParams;

                Assembly scriptAssembly = dom.Load(Path.GetFileNameWithoutExtension(assembly));
                Type     scriptType     = scriptAssembly.GetType("SecondLife.XEngineScript");

                if (scriptType != null)
                {
                    constructorParams = new object[] { m_coopSleepHandle };
                }
                else
                {
                    m_log.ErrorFormat(
                        "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}.  You must remove all existing {6}* script DLL files before using enabling co-op termination"
                        + ", either by setting DeleteScriptsOnStartup = true in [XEngine] for one run"
                        + " or by deleting these files manually.",
                        ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, assembly);

                    return(false);
                }

//                m_log.DebugFormat(
//                    "[SCRIPT INSTANCE]: Looking to load {0} from assembly {1} in {2}",
//                    scriptType.FullName, Path.GetFileNameWithoutExtension(assembly), Engine.World.Name);

                if (dom != System.AppDomain.CurrentDomain)
                {
                    m_Script
                        = (IScript)dom.CreateInstanceAndUnwrap(
                              Path.GetFileNameWithoutExtension(assembly),
                              scriptType.FullName,
                              false,
                              BindingFlags.Default,
                              null,
                              constructorParams,
                              null,
                              null);
                }
                else
                {
                    m_Script
                        = (IScript)scriptAssembly.CreateInstance(
                              scriptType.FullName,
                              false,
                              BindingFlags.Default,
                              null,
                              constructorParams,
                              null,
                              null);
                }

                //ILease lease = (ILease)RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass);
                //RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass);
//                lease.Register(this);
            }
            catch (Exception e)
            {
                m_log.ErrorFormat(
                    "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}.  Error loading assembly {6}.  Exception {7}{8}",
                    ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, assembly, e.Message, e.StackTrace);

                return(false);
            }

            try
            {
                foreach (KeyValuePair <string, IScriptApi> kv in m_Apis)
                {
                    m_Script.InitApi(kv.Key, kv.Value);
                }

//                // m_log.Debug("[Script] Script instance created");

                Part.SetScriptEvents(ItemID,
                                     (int)m_Script.GetStateEventFlags(State));
            }
            catch (Exception e)
            {
                m_log.ErrorFormat(
                    "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}.  Error initializing script instance.  Exception {6}{7}",
                    ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, e.Message, e.StackTrace);

                return(false);
            }

            m_SaveState = true;

            string savedState = Path.Combine(Path.GetDirectoryName(assembly),
                                             ItemID.ToString() + ".state");

            if (File.Exists(savedState))
            {
                string xml = String.Empty;

                try
                {
                    FileInfo fi   = new FileInfo(savedState);
                    int      size = (int)fi.Length;
                    if (size < 512000)
                    {
                        using (FileStream fs = File.Open(savedState,
                                                         FileMode.Open, FileAccess.Read, FileShare.None))
                        {
                            Byte[] data = new Byte[size];
                            fs.Read(data, 0, size);

                            xml = Encoding.UTF8.GetString(data);

                            ScriptSerializer.Deserialize(xml, this);

                            AsyncCommandManager.CreateFromData(Engine,
                                                               LocalID, ItemID, ObjectID,
                                                               PluginData);

//                            m_log.DebugFormat("[Script] Successfully retrieved state for script {0}.{1}", PrimName, m_ScriptName);

                            Part.SetScriptEvents(ItemID,
                                                 (int)m_Script.GetStateEventFlags(State));

                            if (!Running)
                            {
                                m_startOnInit = false;
                            }

                            Running = false;

                            // we get new rez events on sim restart, too
                            // but if there is state, then we fire the change
                            // event

                            // We loaded state, don't force a re-save
                            m_SaveState             = false;
                            m_startedFromSavedState = true;
                        }
                    }
                    else
                    {
                        m_log.WarnFormat(
                            "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}.  Unable to load script state file {6}.  Memory limit exceeded.",
                            ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, savedState);
                    }
                }
                catch (Exception e)
                {
                    m_log.ErrorFormat(
                        "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}.  Unable to load script state file {6}.  XML is {7}.  Exception {8}{9}",
                        ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, savedState, xml, e.Message, e.StackTrace);
                }
            }
//            else
//            {
//                ScenePresence presence = Engine.World.GetScenePresence(part.OwnerID);

//                if (presence != null && (!postOnRez))
//                    presence.ControllingClient.SendAgentAlertMessage("Compile successful", false);

//            }

            return(true);
        }
Exemplo n.º 56
0
 public BaseScriptSetUpper(IScript script)
 {
     Script = script;
 }
Exemplo n.º 57
0
 public ShowMenuScript(ScriptContext scriptContext, IScriptFactory scriptFactory, IFunction <string> caption, IFunctionGeneric options, IFunction <bool> allowCancel, IScript callbackScript)
 {
     m_scriptContext  = scriptContext;
     m_worldModel     = scriptContext.WorldModel;
     m_scriptFactory  = scriptFactory;
     m_caption        = caption;
     m_options        = options;
     m_allowCancel    = allowCancel;
     m_callbackScript = callbackScript;
 }
Exemplo n.º 58
0
        public static ILanguageTag Parse(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return(Empty);
            }

            ILanguage primaryLanguage  = null;
            string    extendedLanguage = null;
            IScript   script           = null;
            ICountry  country          = null;
            var       regionCode       = -1;
            IRegion   region           = null;
            var       variants         = new List <string>();
            var       extensions       = new List <string>();
            string    privateUse       = null;

            var lower = value.ToLower();

            if (grandfatheredTags.ContainsKey(lower))
            {
                primaryLanguage = grandfatheredTags[lower].Item1;
                country         = grandfatheredTags[lower].Item2;
                return(new LanguageTag(primaryLanguage, country));
            }

            var count     = 1;
            var singleton = string.Empty;

            foreach (var token in value.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries))
            {
                if (count == 1)
                {
                    primaryLanguage = Language.GetLanguageByCode(token);
                }
                else
                {
                    if (string.IsNullOrEmpty(singleton))
                    {
                        switch (token.Length)
                        {
                        case 1:
                            singleton = token;
                            break;

                        case 2:
                        {
                            if (token.IsMixedAlphaNumeric())
                            {
                                variants.Add(token);
                            }
                            else
                            {
                                country = Geography.Country.GetCountryByCode(token);
                            }
                            break;
                        }

                        case 3:
                        {
                            if (token.IsMixedAlphaNumeric())
                            {
                                variants.Add(token);
                            }
                            else
                            {
                                if (int.TryParse(token, out regionCode))
                                {
                                    region = Geography.Region.GetRegionByCode(regionCode);
                                }
                                else
                                {
                                    extendedLanguage = token;
                                }
                            }
                            break;
                        }

                        case 4:
                        {
                            if (token.IsMixedAlphaNumeric())
                            {
                                variants.Add(token);
                            }
                            else
                            {
                                script = Culture.Script.GetScriptByCode(token);
                            }
                            break;
                        }

                        case 5:
                        case 6:
                        case 7:
                        case 8:
                        {
                            variants.Add(token);
                            break;
                        }
                        }
                    }
                    else
                    {
                        if (singleton.ToLower() == "x")
                        {
                            if (token.Length >= 1 && token.Length <= 8)
                            {
                                privateUse = string.Format("{0}-{1}", singleton, token);
                            }
                        }
                        else if (token.Length >= 2 && token.Length <= 8)
                        {
                            extensions.Add(string.Format("{0}-{1}", singleton, token));
                        }
                        singleton = string.Empty;
                    }
                }

                count++;
            }

            return((primaryLanguage != null) ? new LanguageTag(primaryLanguage, extendedLanguage, script, country, region, variants, extensions, privateUse) : Empty);
        }
Exemplo n.º 59
0
        public void GetP2shTest(IScript script, NetworkType netType, string expected)
        {
            string actual = Address.GetP2sh(script, netType);

            Assert.Equal(actual, expected);
        }
 /// <summary>
 /// creates a new <see cref="ExternalScriptMethod"/>
 /// </summary>
 /// <param name="name">name of script</param>
 /// <param name="script"></param>
 public ExternalScriptMethod(string name, IScript script)
 {
     this.script = script;
     Name        = name;
 }