/// <summary> /// Activate the validation mechanism, so every request DTO with an existing validator /// will be validated. /// </summary> /// <param name="appHost">The app host</param> public void Register(IAppHost appHost) { if (TreatInfoAndWarningsAsErrors) { if (!appHost.GlobalRequestFiltersAsync.Contains(ValidationFilters.RequestFilterAsync)) { appHost.GlobalRequestFiltersAsync.Add(ValidationFilters.RequestFilterAsync); } if (!appHost.GlobalMessageRequestFiltersAsync.Contains(ValidationFilters.RequestFilterAsync)) { appHost.GlobalMessageRequestFiltersAsync.Add(ValidationFilters.RequestFilterAsync); } } else { if (!appHost.GlobalRequestFiltersAsync.Contains(ValidationFilters.RequestFilterAsyncIgnoreWarningsInfo)) { appHost.GlobalRequestFiltersAsync.Add(ValidationFilters.RequestFilterAsyncIgnoreWarningsInfo); } if (!appHost.GlobalMessageRequestFiltersAsync.Contains(ValidationFilters.RequestFilterAsyncIgnoreWarningsInfo)) { appHost.GlobalMessageRequestFiltersAsync.Add(ValidationFilters.RequestFilterAsyncIgnoreWarningsInfo); } if (!appHost.GlobalResponseFiltersAsync.Contains(ValidationFilters.ResponseFilterAsync)) { appHost.GlobalResponseFiltersAsync.Add(ValidationFilters.ResponseFilterAsync); } if (!appHost.GlobalMessageResponseFiltersAsync.Contains(ValidationFilters.ResponseFilterAsync)) { appHost.GlobalMessageResponseFiltersAsync.Add(ValidationFilters.ResponseFilterAsync); } } if (ValidationSource != null) { appHost.Register(ValidationSource); ValidationSource.InitSchema(); } var container = appHost.GetContainer(); var hasValidationSource = ValidationSource != null || container.Exists <IValidationSource>(); if (hasValidationSource && AccessRole != null) { appHost.RegisterServices(ServiceRoutes); } if (ScanAppHostAssemblies) { container.RegisterValidators(((ServiceStackHost)appHost).ServiceAssemblies.ToArray()); } appHost.AddToAppMetadata(metadata => { metadata.Plugins.Validation = new ValidationInfo { HasValidationSource = hasValidationSource.NullIfFalse(), HasValidationSourceAdmin = (container.TryResolve <IValidationSource>() is IValidationSourceAdmin).NullIfFalse(), ServiceRoutes = ServiceRoutes.ToMetadataServiceRoutes(), TypeValidators = !EnableDeclarativeValidation ? null : appHost.ScriptContext.ScriptMethods.SelectMany(x => ScriptMethodInfo.GetScriptMethods(x.GetType(), where : mi => typeof(ITypeValidator).IsAssignableFrom(mi.ReturnType))) .Map(x => x.ToScriptMethodType()), PropertyValidators = !EnableDeclarativeValidation ? null : appHost.ScriptContext.ScriptMethods.SelectMany(x => ScriptMethodInfo.GetScriptMethods(x.GetType(), where : mi => typeof(IPropertyValidator).IsAssignableFrom(mi.ReturnType))) .Map(x => x.ToScriptMethodType()), AccessRole = AccessRole, }; }); appHost.GetPlugin <MetadataFeature>()?.ExportTypes.Add(typeof(ValidationRule)); }
/// <summary> /// 编译脚本 /// </summary> /// <returns>编译是否成功</returns> public bool Compile() { if (bolClosedFlag) { return(false); } intScriptVersion++; bolDebuged = false; myScriptMethods.Clear(); myAssembly = null; bolScriptModified = false; // 生成编译用的完整的VB源代码 string ModuleName = "mdlXVBAScriptEngine"; string nsName = "NameSpaceXVBAScriptEngien"; System.Text.StringBuilder mySource = new System.Text.StringBuilder(); mySource.Append("Option Strict Off"); foreach (string import in this.mySourceImports) { mySource.Append("\r\nImports " + import); } mySource.Append("\r\nNamespace " + nsName); mySource.Append("\r\nModule " + ModuleName); mySource.Append("\r\n"); mySource.Append("sub Cal() \r\ntry \r\n"); string datTmp = mySource.ToString(); startCodeLineCount = datTmp.Split('\r').Length; mySource.Append(this.strScriptText); mySource.Append("\r\nCatch ex As Exception \r\nh.show(ex.tostring) \r\nEnd Try \r\nend sub"); mySource.Append("\r\nEnd Module"); mySource.Append("\r\nEnd Namespace"); string strRuntimeSource = mySource.ToString(); // 检查程序集缓存区 myAssembly = (System.Reflection.Assembly)myAssemblies[strRuntimeSource]; if (myAssembly == null) { // 设置编译参数 this.myCompilerParameters.GenerateExecutable = false; this.myCompilerParameters.GenerateInMemory = true; this.myCompilerParameters.IncludeDebugInformation = true; if (this.myVBCompilerImports.Count > 0) { // 添加 imports 指令 System.Text.StringBuilder opt = new System.Text.StringBuilder(); foreach (string import in this.myVBCompilerImports) { if (opt.Length > 0) { opt.Append(","); } opt.Append(import.Trim()); } opt.Insert(0, " /imports:"); for (int iCount = 0; iCount < this.myVBCompilerImports.Count; iCount++) { this.myCompilerParameters.CompilerOptions = opt.ToString(); } }//if if (this.bolOutputDebug) { // 输出调试信息 System.Diagnostics.Debug.WriteLine(" Compile VBA.NET script \r\n" + strRuntimeSource); foreach (string dll in this.myCompilerParameters.ReferencedAssemblies) { System.Diagnostics.Debug.WriteLine("Reference:" + dll); } } // 对VB.NET代码进行编译 Microsoft.VisualBasic.VBCodeProvider provider = new Microsoft.VisualBasic.VBCodeProvider(); #if DOTNET11 // 这段代码用于微软.NET1.1 ICodeCompiler compiler = provider.CreateCompiler(); CompilerResults result = compiler.CompileAssemblyFromSource( this.myCompilerParameters, strRuntimeSource); #else // 这段代码用于微软.NET2.0或更高版本 CompilerResults result = provider.CompileAssemblyFromSource( this.myCompilerParameters, strRuntimeSource); #endif // 获得编译器控制台输出文本 System.Text.StringBuilder myOutput = new System.Text.StringBuilder(); foreach (string line in result.Output) { myOutput.Append("\r\n" + line); } this.strCompilerOutput = myOutput.ToString(); if (this.bolOutputDebug) { // 输出编译结果 if (this.strCompilerOutput.Length > 0) { //System.Diagnostics.Debug.WriteLine("VBAScript Compile result" + strCompilerOutput); ////////////////////// //string strErrorMsg = "检测出 " + result.Errors.Count.ToString() + " 个错误:"; string strErrorMsg = string.Empty; int count = 0; for (int x = 0; x < result.Errors.Count; x++) { if (result.Errors[x].IsWarning) { continue; } strErrorMsg = strErrorMsg + Environment.NewLine + "第 " + (result.Errors[x].Line - (startCodeLineCount - 1)).ToString() + " 行: " + result.Errors[x].ErrorText; count++; } strErrorMsg = "检测出 " + count.ToString() + " 个错误:" + strErrorMsg; strCompilerOutput = strErrorMsg; /////////////////////// } } provider.Dispose(); if (result.Errors.HasErrors == false) { // 若没有发生编译错误则获得编译所得的程序集 this.myAssembly = result.CompiledAssembly; } if (myAssembly != null) { // 将程序集缓存到程序集缓存区中 myAssemblies[strRuntimeSource] = myAssembly; } } if (this.myAssembly != null) { // 检索脚本中定义的类型 Type ModuleType = myAssembly.GetType(nsName + "." + ModuleName); if (ModuleType != null) { System.Reflection.MethodInfo[] ms = ModuleType.GetMethods( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); foreach (System.Reflection.MethodInfo m in ms) { // 遍历类型中所有的静态方法 // 对每个方法创建一个脚本方法信息对象并添加到脚本方法列表中。 ScriptMethodInfo info = new ScriptMethodInfo(); info.MethodName = m.Name; info.MethodObject = m; info.ModuleName = ModuleType.Name; info.ReturnType = m.ReturnType; this.myScriptMethods.Add(info); if (this.bolOutputDebug) { // 输出调试信息 System.Diagnostics.Debug.WriteLine("Get vbs method \"" + m.Name + "\""); } } //foreach bolDebuged = true; } //if } //if return(bolDebuged); }
/// <summary> /// Compile script /// </summary> /// <returns>Compiler ok or not</returns> public virtual bool Compile() { strRuntimeScriptText = null; strCompilerOutput = null; myCompilerErrors = null; if (bolClosedFlag) { return(false); } if (strScriptText == null || strScriptText.Trim().Length == 0) { return(false); } intScriptVersion++; bool bolResult = false; this.ScriptMethods.Clear(); myAssembly = null; bolScriptModified = false; // Generate integrated VB.NET source code string ModuleName = "mdlXVBAScriptEngine"; string globalModuleName = "mdlXVBAScriptGlobalValues"; string nsName = "NameSpaceXVBAScriptEngien"; System.Text.StringBuilder mySource = new System.Text.StringBuilder(); mySource.Append("Option Strict Off"); foreach (string import in this.Options.ImportNamespaces) { mySource.Append("\r\nImports " + import); } mySource.Append("\r\nNamespace " + nsName); //System.Collections.Hashtable myGObjects = new Hashtable(); // Generate source code for global objects if (myGlobalObjects != null && myGlobalObjects.Count > 0) { myVBCompilerImports.Add(nsName); //mySource.Append("\r\n<Microsoft.VisualBasic.CompilerServices.StandardModule>"); mySource.Append("\r\nModule " + globalModuleName); mySource.Append("\r\n"); mySource.Append("\r\n Public myGlobalValues As Object"); foreach (XVBAScriptGlobalObject item in myGlobalObjects) { if (System.Xml.XmlReader.IsName(item.Name) == false) { if (this.ThrowException) { throw new ArgumentException("Script global object name:" + item.Name); } else { if (this.OutputDebug) { System.Diagnostics.Debug.WriteLine("Script global object name:" + item.Name); } continue; } } if (item.ValueType.Equals(typeof(object)) || item.ValueType.IsPublic == false) { mySource.Append("\r\n Public ReadOnly Property " + item.Name + "() As Object "); mySource.Append("\r\n Get"); mySource.Append("\r\n Return myGlobalValues(\"" + item.Name + "\") "); mySource.Append("\r\n End Get"); mySource.Append("\r\n End Property"); } else { string typeName = item.ValueType.FullName; typeName = typeName.Replace("+", "."); mySource.Append("\r\n Public ReadOnly Property " + item.Name + "() As " + typeName); mySource.Append("\r\n Get"); mySource.Append("\r\n Return CType( myGlobalValues(\"" + item.Name + "\") , " + typeName + ")"); mySource.Append("\r\n End Get"); mySource.Append("\r\n End Property"); } } mySource.Append("\r\nEnd Module"); } mySource.Append("\r\nModule " + ModuleName); mySource.Append("\r\n"); mySource.Append(this.strScriptText); mySource.Append("\r\nEnd Module"); mySource.Append("\r\nEnd Namespace"); strRuntimeScriptText = mySource.ToString(); myAssembly = null; if (myAssemblyBuffer != null) { // Check assembly buffer myAssembly = myAssemblyBuffer.GetAssembly(strRuntimeScriptText); } if (myAssembly == null) { // Use dynamic compile DynamicCompiler compiler = new DynamicCompiler(); compiler.Language = CompilerLanguage.VB; compiler.AppDomain = myAppDomain; compiler.PreserveAssemblyFile = false; compiler.OutputDebug = this.OutputDebug; compiler.ThrowException = this.ThrowException; compiler.SourceCode = strRuntimeScriptText; compiler.AutoLoadResultAssembly = true; // add referenced assemblies DotNetAssemblyInfoList refs = this.Options.ReferenceAssemblies.Clone(); refs.AddByType(this.GetType()); if (this.GlobalObjects.Count > 0) { foreach (XVBAScriptGlobalObject item in this.GlobalObjects) { refs.AddByType(item.ValueType); } } foreach (string asm in this.Options.InnerReferenceAssemblies) { refs.AddByName(asm); } foreach (DotNetAssemblyInfo asm in refs) { if (asm.SourceStyle == AssemblySourceStyle.Standard) { compiler.ReferenceAssemblies.Add(System.IO.Path.GetFileName(asm.FileName)); } else { compiler.ReferenceAssemblies.Add(asm.FileName); } } foreach (string ns in this.VBCompilerImports) { compiler.CompilerImports.Add(ns); } if (compiler.Compile()) { myAssembly = compiler.ResultAssembly; if (myAssemblyBuffer != null) { myAssemblyBuffer.AddAssembly( strRuntimeScriptText, myAssembly, compiler.ResultAssemblyBinary); } bolResult = true; } else { myCompilerErrors = compiler.CompilerErrors; foreach (CompilerError error in myCompilerErrors) { if (error.IsWarning == false) { // report error if (this.Errors != null) { ScriptError err = new ScriptError(this, ScriptErrorStyle.Compile, null, null); err.Message = error.ErrorText; err.ScriptText = error.ErrorText; this.Errors.Add(err); } bolResult = false; break; } } } strRuntimeScriptTextWithCompilerErrorMessage = compiler.SourceCodeWithCompilerErrorMessage; } if (this.myAssembly != null) { // set global object instance Type ModuleType = myAssembly.GetType(nsName + "." + globalModuleName); if (ModuleName != null) { System.Reflection.FieldInfo gf = ModuleType.GetField("myGlobalValues"); gf.SetValue(null, this.GlobalObjects); } // analyze script method ModuleType = myAssembly.GetType(nsName + "." + ModuleName); if (ModuleType != null) { System.Reflection.MethodInfo[] ms = ModuleType.GetMethods( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); foreach (System.Reflection.MethodInfo m in ms) { // generate script method information ScriptMethodInfo info = new ScriptMethodInfo(); info.Assembly = myAssembly; info.MethodName = m.Name; info.MethodObject = m; info.ModuleName = ModuleType.Name; info.ReturnType = m.ReturnType; info.ScriptText = (string)myMethodSciptText[info.MethodName]; this.ScriptMethods.Add(info); if (this.bolOutputDebug) { System.Diagnostics.Debug.WriteLine( string.Format(ScriptStrings.AnalyseVBMethod_Name, m.Name)); } } //foreach bolResult = true; } //if } return(bolResult); }
public bool IsMethodOnStack(ScriptMethodInfo method) { return(_stackFrames.Any(_ => _.ScriptMethod == method)); }