/// <summary> Executes a D4 script. </summary> public static void ExecuteScript(string script, IServer server, SessionInfo sessionInfo) { IServerSession session = server.Connect(sessionInfo); try { IServerProcess process = session.StartProcess(new ProcessInfo(sessionInfo)); try { IServerScript localScript = process.PrepareScript(script); try { localScript.Execute(null); } finally { process.UnprepareScript(localScript); } } finally { session.StopProcess(process); } } finally { server.Disconnect(session); } }
private static void LoadScripts(Queue <IServerScript> scripts) { if (scripts.Count > 0) { IServerScript iscript = scripts.Dequeue(); ServerScript script = (ServerScript)iscript; ((ILease)script.GetLifetimeService()).Register(instance); script.timer = new ScriptTimer(script, 100, (timer) => { try { iscript.Tick(); } catch (Exception e) { instance.Print(PrintType.Error, "\"" + iscript.Name + "\"'s Tick() failed."); instance.PrintException(e); } }, true); ((ILease)script.timer.GetLifetimeService()).Register(instance); instance.Print("Creating proxy for script \"" + iscript.Name + "\"..."); script.CreateProxy(instance, scripts); } }
internal void RemoveAllEventHandlers(ServerScript caller, string eventname) { IServerScript icaller = (IServerScript)caller; lock (scripteventhandlers) { if (!scripteventhandlers.ContainsKey(icaller)) { scripteventhandlers.Add(icaller, new Dictionary <string, List <Delegate> >()); } if (!scripteventhandlers[icaller].ContainsKey(eventname)) { scripteventhandlers[icaller].Add(eventname, new List <Delegate>()); } if (EventHandlers != null && EventHandlers.ContainsKey(eventname)) { foreach (Delegate handler in scripteventhandlers[icaller][eventname]) { EventHandlers[eventname].RemoveAll(h => h == handler); } } scripteventhandlers[icaller][eventname].Clear(); } }
internal void AddEventHandler(ServerScript caller, string eventname, int args) { IServerScript icaller = (IServerScript)caller; lock (scripteventhandlers) { if (!scripteventhandlers.ContainsKey(icaller)) { scripteventhandlers.Add(icaller, new Dictionary <string, List <Delegate> >()); } if (!scripteventhandlers[icaller].ContainsKey(eventname)) { scripteventhandlers[icaller].Add(eventname, new List <Delegate>()); } if (scripteventhandlers[icaller][eventname].Any(h => h.Method.GetParameters().Length == args)) { return; } Delegate[] handlers = { new Action(() => { caller.TriggerLocalEvent(eventname); }), new Action <object>((a1) => { object[] cargs = ConvertArgsFromNLua(a1); caller.TriggerLocalEvent(eventname, cargs[0]);}), new Action <object, object>((a1, a2) =>{ object[] cargs = ConvertArgsFromNLua(a1, a2); caller.TriggerLocalEvent(eventname, cargs[0], cargs[1]); }), new Action <object, object, object>((a1, a2, a3) =>{ object[] cargs = ConvertArgsFromNLua(a1, a2, a3); caller.TriggerLocalEvent(eventname, cargs[0], cargs[1], cargs[2]); }), new Action <object, object, object, object>((a1, a2, a3, a4) =>{ object[] cargs = ConvertArgsFromNLua(a1, a2, a3, a4); caller.TriggerLocalEvent(eventname, cargs[0], cargs[1], cargs[2], cargs[3]); }), new Action <object, object, object, object, object>((a1, a2, a3, a4, a5) =>{ object[] cargs = ConvertArgsFromNLua(a1, a2, a3, a4, a5); caller.TriggerLocalEvent(eventname, cargs[0], cargs[1], cargs[2], cargs[3], cargs[4]); }), new Action <object, object, object, object, object, object>((a1, a2, a3, a4, a5, a6) =>{ object[] cargs = ConvertArgsFromNLua(a1, a2, a3, a4, a5, a6); caller.TriggerLocalEvent(eventname, cargs[0], cargs[1], cargs[2], cargs[3], cargs[4], cargs[5]); }), new Action <object, object, object, object, object, object, object>((a1, a2, a3, a4, a5, a6, a7) =>{ object[] cargs = ConvertArgsFromNLua(a1, a2, a3, a4, a5, a6, a7); caller.TriggerLocalEvent(eventname, cargs[0], cargs[1], cargs[2], cargs[3], cargs[4], cargs[5], cargs[6]); }), new Action <object, object, object, object, object, object, object, object>((a1, a2, a3, a4, a5, a6, a7, a8) =>{ object[] cargs = ConvertArgsFromNLua(a1, a2, a3, a4, a5, a6, a7, a8); caller.TriggerLocalEvent(eventname, cargs[0], cargs[1], cargs[2], cargs[3], cargs[4], cargs[5], cargs[6], cargs[7]); }), new Action <object, object, object, object, object, object, object, object, object>((a1, a2, a3, a4, a5, a6, a7, a8, a9) =>{ object[] cargs = ConvertArgsFromNLua(a1, a2, a3, a4, a5, a6, a7, a8, a9); caller.TriggerLocalEvent(eventname, cargs[0], cargs[1], cargs[2], cargs[3], cargs[4], cargs[5], cargs[6], cargs[7], cargs[8]); }), new Action <object, object, object, object, object, object, object, object, object, object>((a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) =>{ object[] cargs = ConvertArgsFromNLua(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10); caller.TriggerLocalEvent(eventname, cargs[0], cargs[1], cargs[2], cargs[3], cargs[4], cargs[5], cargs[6], cargs[7], cargs[8], cargs[9]); }), new Action <object, object, object, object, object, object, object, object, object, object, object>((a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) =>{ object[] cargs = ConvertArgsFromNLua(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11); caller.TriggerLocalEvent(eventname, cargs[0], cargs[1], cargs[2], cargs[3], cargs[4], cargs[5], cargs[6], cargs[7], cargs[8], cargs[9], cargs[10]); }), new Action <object, object, object, object, object, object, object, object, object, object, object, object>((a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12) =>{ object[] cargs = ConvertArgsFromNLua(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12); caller.TriggerLocalEvent(eventname, cargs[0], cargs[1], cargs[2], cargs[3], cargs[4], cargs[5], cargs[6], cargs[7], cargs[8], cargs[9], cargs[10], cargs[11]); }), new Action <object, object, object, object, object, object, object, object, object, object, object, object, object>((a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13) =>{ object[] cargs = ConvertArgsFromNLua(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13); caller.TriggerLocalEvent(eventname, cargs[0], cargs[1], cargs[2], cargs[3], cargs[4], cargs[5], cargs[6], cargs[7], cargs[8], cargs[9], cargs[10], cargs[11], cargs[12]); }), new Action <object, object, object, object, object, object, object, object, object, object, object, object, object, object>((a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14) =>{ object[] cargs = ConvertArgsFromNLua(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); caller.TriggerLocalEvent(eventname, cargs[0], cargs[1], cargs[2], cargs[3], cargs[4], cargs[5], cargs[6], cargs[7], cargs[8], cargs[9], cargs[10], cargs[11], cargs[12], cargs[13]); }), new Action <object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>((a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15) =>{ object[] cargs = ConvertArgsFromNLua(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15); caller.TriggerLocalEvent(eventname, cargs[0], cargs[1], cargs[2], cargs[3], cargs[4], cargs[5], cargs[6], cargs[7], cargs[8], cargs[9], cargs[10], cargs[11], cargs[12], cargs[13], cargs[14]); }), new Action <object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>((a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16) =>{ object[] cargs = ConvertArgsFromNLua(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16); caller.TriggerLocalEvent(eventname, cargs[0], cargs[1], cargs[2], cargs[3], cargs[4], cargs[5], cargs[6], cargs[7], cargs[8], cargs[9], cargs[10], cargs[11], cargs[12], cargs[13], cargs[14], cargs[15]); }) }; foreach (Delegate handler in handlers) { if (handler.Method.GetParameters().Length != args) { continue; } scripteventhandlers[icaller][eventname].Add(handler); if (eventname != "rconCommand") { AddEventHandler(eventname, handler); } } } }
private void CatalogLookupFailed(Schema.Catalog catalog, string name) { #if LOGCACHEEVENTS FSession.FServer.FInternalServer.LogMessage(String.Format("Retrieving catalog for '{0}'.", AName)); #endif // A cache miss forces the retrieval of the datatype and its dependencies from the remote server process long cacheTimeStamp; long clientCacheTimeStamp; bool cacheChanged; string stringValue = _process.GetCatalog(name, out cacheTimeStamp, out clientCacheTimeStamp, out cacheChanged); // Ensure that the local cache is consistent before adding to the cache if (cacheChanged) { try { _session._server.WaitForCacheTimeStamp(this, clientCacheTimeStamp - 1); _session._server.AcquireCacheLock(this, LockMode.Exclusive); try { _session._server.EnsureCacheConsistent(cacheTimeStamp); if (stringValue != String.Empty) { IServerScript script = ((IServerProcess)_internalProcess).PrepareScript(stringValue); try { script.Execute(null); } finally { ((IServerProcess)_internalProcess).UnprepareScript(script); } } } finally { _session._server.ReleaseCacheLock(this, LockMode.Exclusive); } } catch (Exception E) { // Notify the server that the client cache is out of sync Execute(".System.UpdateTimeStamps();", null); E = new ServerException(ServerException.Codes.CacheDeserializationError, E, clientCacheTimeStamp); _session._server._internalServer.LogError(E); throw E; } finally { _session._server.SetCacheTimeStamp(this, clientCacheTimeStamp); } } }
public void UnprepareScript(IServerScript script) { try { _process.UnprepareScript(((LocalScript)script).RemoteScript); } catch { // ignore exceptions here } ((LocalScript)script).Dispose(); }
public void RunScript(ServerProcess process, string script, string libraryName, DAE.Debug.DebugLocator locator) { if (libraryName != String.Empty) { process.ServerSession.CurrentLibrary = process.CatalogDeviceSession.ResolveLoadedLibrary(libraryName); } IServerScript localScript = ((IServerProcess)process).PrepareScript(script, locator); try { localScript.Execute(null); } finally { ((IServerProcess)process).UnprepareScript(localScript); } }
/// <summary>Executes the given script using the given process.</summary> public void ExecuteScript(IServerProcess process, string script, DAE.Runtime.DataParams paramsValue) { if (script != String.Empty) { CheckActive(); if (process == null) { process = UtilityProcess; } IServerScript localScript = process.PrepareScript(script); try { localScript.Execute(paramsValue); } finally { process.UnprepareScript(localScript); } } }
private Schema.IDataType GetDataType() { bool timeStampSet = false; try { LocalServer.WaitForCacheTimeStamp(_process, _descriptor.CacheChanged ? _descriptor.ClientCacheTimeStamp - 1 : _descriptor.ClientCacheTimeStamp); LocalServer.AcquireCacheLock(_process, _descriptor.CacheChanged ? LockMode.Exclusive : LockMode.Shared); try { if (_descriptor.CacheChanged) { LocalServer.EnsureCacheConsistent(_descriptor.CacheTimeStamp); try { if (_descriptor.Catalog != String.Empty) { IServerScript script = ((IServerProcess)_process._internalProcess).PrepareScript(_descriptor.Catalog); try { script.Execute(_params); } finally { ((IServerProcess)_process._internalProcess).UnprepareScript(script); } } } finally { LocalServer.SetCacheTimeStamp(_process, _descriptor.ClientCacheTimeStamp); timeStampSet = true; } } if (LocalServer.Catalog.ContainsName(_descriptor.ObjectName)) { Schema.Object objectValue = LocalServer.Catalog[_descriptor.ObjectName]; if (objectValue is Schema.TableVar) { _tableVar = (Schema.TableVar)objectValue; Plan plan = new Plan(_process._internalProcess); try { if (_params != null) { foreach (DataParam param in _params) { plan.Symbols.Push(new Symbol(param.Name, param.DataType)); } } foreach (DataParam param in _process._internalProcess.ProcessLocals) { plan.Symbols.Push(new Symbol(param.Name, param.DataType)); } _tableNode = (TableNode)Compiler.EmitTableVarNode(plan, _tableVar); } finally { plan.Dispose(); } _dataType = _tableVar.DataType; } else { _dataType = (Schema.IDataType)objectValue; } } else { try { Plan plan = new Plan(_process._internalProcess); try { _dataType = Compiler.CompileTypeSpecifier(plan, new DAE.Language.D4.Parser().ParseTypeSpecifier(_descriptor.ObjectName)); } finally { plan.Dispose(); } } catch { // Notify the server that the client cache is out of sync Process.Execute(".System.UpdateTimeStamps();", null); throw; } } return(_dataType); } finally { LocalServer.ReleaseCacheLock(_process, _descriptor.CacheChanged ? LockMode.Exclusive : LockMode.Shared); } } catch (Exception E) { // Notify the server that the client cache is out of sync Process.Execute(".System.UpdateTimeStamps();", null); E = new ServerException(ServerException.Codes.CacheDeserializationError, E, _descriptor.ClientCacheTimeStamp); LocalServer._internalServer.LogError(E); throw E; } finally { if (!timeStampSet) { LocalServer.SetCacheTimeStamp(_process, _descriptor.ClientCacheTimeStamp); } } }
public NativeResult Execute(string statement, NativeParam[] paramsValue, NativeExecutionOptions options) { IServerScript script = _process.PrepareScript(statement); try { if (script.Batches.Count != 1) { throw new ArgumentException("Execution statement must contain one, and only one, batch."); } IServerBatch batch = script.Batches[0]; DataParams dataParams = NativeMarshal.NativeParamsToDataParams((Server.ServerProcess)_process, paramsValue); NativeResult result = new NativeResult(); result.Params = paramsValue; if (batch.IsExpression()) { IServerExpressionPlan expressionPlan = batch.PrepareExpression(dataParams); try { if (expressionPlan.DataType is Schema.TableType) { if (options != NativeExecutionOptions.SchemaOnly) { IServerCursor cursor = expressionPlan.Open(dataParams); try { result.Value = NativeMarshal.ServerCursorToNativeValue(_process, cursor); } finally { expressionPlan.Close(cursor); } } else { result.Value = NativeMarshal.TableVarToNativeTableValue(_process, expressionPlan.TableVar); } } else { if (options != NativeExecutionOptions.SchemaOnly) { using (IDataValue tempValue = expressionPlan.Evaluate(dataParams)) { result.Value = NativeMarshal.DataValueToNativeValue(_process, tempValue); } } else { result.Value = NativeMarshal.DataTypeToNativeValue(_process, expressionPlan.DataType); } } } finally { batch.UnprepareExpression(expressionPlan); } } else { IServerStatementPlan statementPlan = batch.PrepareStatement(dataParams); try { if (options != NativeExecutionOptions.SchemaOnly) { statementPlan.Execute(dataParams); } } finally { batch.UnprepareStatement(statementPlan); } } if (options != NativeExecutionOptions.SchemaOnly) { NativeMarshal.SetNativeOutputParams(_process, result.Params, dataParams); } return(result); } finally { _process.UnprepareScript(script); } }
public static void ExecuteScript(IServerProcess process, string script, ScriptExecuteOption options, out ErrorList errors, out TimeSpan timeElapsed, ReportScriptProgressHandler reportScriptProgress, DebugLocator locator) { StringBuilder result = new StringBuilder(); errors = new ErrorList(); timeElapsed = TimeSpan.Zero; bool attemptExecute = true; DateTime startTime = DateTime.Now; try { IServerScript localScript = process.PrepareScript(script, locator); try { if (ConvertParserErrors(localScript.Messages, errors)) { foreach (IServerBatch batch in localScript.Batches) { PlanStatistics statistics = null; try { if (batch.IsExpression()) { IServerExpressionPlan plan = batch.PrepareExpression(null); try { attemptExecute &= ConvertCompilerErrors(plan.Messages, errors); if (attemptExecute) { int rowCount = ReadResult(result, plan); AppendStatistics(result, options, plan.PlanStatistics, plan.ProgramStatistics, rowCount); statistics = plan.PlanStatistics; } } finally { batch.UnprepareExpression(plan); } } else { IServerStatementPlan plan = batch.PrepareStatement(null); try { attemptExecute &= ConvertCompilerErrors(plan.Messages, errors); if (attemptExecute) { plan.Execute(null); AppendStatistics(result, options, plan.PlanStatistics, plan.ProgramStatistics, -1); statistics = plan.PlanStatistics; } } finally { batch.UnprepareStatement(plan); } } } finally { if (reportScriptProgress != null) { reportScriptProgress(statistics, result.ToString()); } result.Length = 0; } } // foreach batch... } // if (no parser errors)... } finally { process.UnprepareScript(localScript); } } catch (Exception exception) { errors.Add(exception); } timeElapsed = DateTime.Now - startTime; }
private static void Load(string path) { instance.Print("Loading scripts in \"" + path + "\"..."); foreach (string file in Directory.GetFiles(path, "*.dll")) { if (AssemblyName.GetAssemblyName(file).Name == "ServerWrapper") { instance.Print("Found ServerWrapper assembly in Scripts folder. Removing..."); try { File.Delete(file); } catch (Exception e) { instance.Print(PrintType.Warning, "Failed to remove ServerWrapper assembly from Scripts folder, this may cause issues."); instance.PrintException(e); } } } /*if (Directory.GetFiles(path, "*.cs").Length > 0) * { * string localassembly = typeof(ServerScript).Assembly.Location; * AppDomain domain = AppDomain.CreateDomain("Test"); * domain.DoCallBack(() => * { * System.CodeDom.Compiler.CompilerParameters options = new System.CodeDom.Compiler.CompilerParameters(); * options.CompilerOptions = "/optimize /unsafe"; * options.GenerateInMemory = true; * //options.GenerateInMemory = false; * options.IncludeDebugInformation = true; * options.ReferencedAssemblies.AddRange(new string[] * { * "System.dll", * "System.Core.dll", * "System.Drawing.dll", * "System.Windows.Forms.dll", * "System.XML.dll", * "System.XML.Linq.dll", * localassembly, * "System.ComponentModel.Composition.dll" * }); * * System.CodeDom.Compiler.CodeDomProvider compiler = new Microsoft.CSharp.CSharpCodeProvider(); * * foreach (string file in Directory.GetFiles(path, "*.cs")) * { * options.OutputAssembly = Path.ChangeExtension(file, ".dll"); * * System.CodeDom.Compiler.CompilerResults result = compiler.CompileAssemblyFromFile(options, file); * * if (!result.Errors.HasErrors) * { * instance.RconPrint((result.CompiledAssembly == null).ToString()); * instance.RconPrint(result.PathToAssembly); * } * else * { * string errors = ""; * * foreach (System.CodeDom.Compiler.CompilerError error in result.Errors) errors += " at line " + error.Line + ": " + error.ErrorText + "\r\n"; * * instance.RconPrint("[ERROR] Failed to compile '" + Path.GetFileName(file) + "' with " + result.Errors.Count + " error(s):\r\n" + errors.ToString()); * } * } * }); * * AppDomain.Unload(domain); * }*/ MefLoader mefLoader = SeparateAppDomain.CreateInstance <MefLoader>(path, path); mefLoader.Domain.UnhandledException += (sender, e) => { instance.Print(PrintType.Error, "Unhandled exception occured in script."); instance.PrintException((Exception)e.ExceptionObject); }; /*mefLoader.Domain.AssemblyResolve += (sender, e) => * { * * };*/ List <IServerScript> scripts = mefLoader.Load <IServerScript>(); if (scripts.Count == 0) { SeparateAppDomain.Delete(path); instance.Print("No scripts found in \"" + path + "\"."); return; } //assemblies.Clear(); _scripts.Add(path, scripts); instance.Print(scripts.Count + " script(s) found in \"" + path + "\"."); instance.Print(""); // Sorting logic from ScriptHookVDotNet Dictionary <IServerScript, List <string> > graph = new Dictionary <IServerScript, List <string> >(); Queue <IServerScript> sorted = new Queue <IServerScript>(); foreach (IServerScript script in scripts) { graph.Add(script, new List <string>(script.Dependencies)); } while (graph.Count > 0) { IServerScript s = null; foreach (var kv in graph) { if (kv.Value.Count == 0) { s = kv.Key; break; } } if (s == null) { instance.Print(PrintType.Fatal, "Detected a circular script dependency. Aborting..."); instance.Print(""); return; } sorted.Enqueue(s); graph.Remove(s); foreach (var kv in graph) { kv.Value.Remove(s.TypeName); } } if (graph.Count == 0) { LoadScripts(sorted); } }
private DataFhirServerResult Execute(IServerProcess process, string statement, DataParam[] paramsValue) { IServerScript script = process.PrepareScript(statement); try { if (script.Batches.Count != 1) { throw new ArgumentException("Execution statement must contain one, and only one, batch."); } IServerBatch batch = script.Batches[0]; DataParams dataParams = DataFhirMarshal.ParamsArrayToDataParams(process, paramsValue); DataFhirServerResult result = new DataFhirServerResult(); result.Params = paramsValue; if (batch.IsExpression()) { IServerExpressionPlan expressionPlan = batch.PrepareExpression(dataParams); try { if (expressionPlan.DataType is TableType) { IServerCursor cursor = expressionPlan.Open(dataParams); try { result.Value = DataFhirMarshal.ServerCursorToValue(process, cursor); } finally { expressionPlan.Close(cursor); } } else { using (IDataValue tempValue = expressionPlan.Evaluate(dataParams)) { result.Value = DataFhirMarshal.DataValueToValue(process, tempValue); } } } finally { batch.UnprepareExpression(expressionPlan); } } else { IServerStatementPlan statementPlan = batch.PrepareStatement(dataParams); try { statementPlan.Execute(dataParams); } finally { batch.UnprepareStatement(statementPlan); } } //DotNetMarshal.SetNativeOutputParams(process, result.Params, dataParams); return(result); } finally { process.UnprepareScript(script); } }