public StateContext(string jobId, MethodData methodData) { if (String.IsNullOrEmpty(jobId)) throw new ArgumentNullException("jobId"); JobId = jobId; MethodData = methodData; }
private static IEnumerable<MethodData> GetBaseAndImplementedMethodsForMethod(MethodData method) { var bases = Inheritance.GetBaseMethods(method); var implements = Inheritance.GetImplementedMethods(method); return Enumerable.Concat(bases, implements); }
public void ToCode_given_ConstructorDataWithoutParameters_should_ReturnDefaultConstructorCode() { // # Arrange. var sut = new MethodData(); sut.Comment = new CommentData("Default constructor."); sut.IsConstructor = true; sut.Scope = Common.VisibilityScope.Public; sut.Name = "MyClassName"; // # Act. var res = sut.ToCode(); // # Assert. Assert.AreEqual(5, res.Count); CollectionAssert.AreEqual( new[] { "/// <summary> Default constructor.", "/// </summary>", "public MyClassName()", "{", "}", }, res.ToList()); }
public static IEnumerable<MethodData> GetBaseAndImplementedMethods(MethodData method) { if (!(method.Inner is MethodInfo)) // constructor return Enumerable.Empty<MethodData>(); return Inheritance.GetBaseAndImplementedMethodsForMethod(method); }
/// <summary> /// Sets up an errored execute setup. /// </summary> /// <param name="methodData">The method data.</param> /// <returns>A <see cref="Func{T}"/> returning an errored <see cref="Task"/> setup with the <see cref="Exception"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="methodData"/> parameter is <see langword="null"/>.</exception> Func<Task> IExecutionSetup.Setup(MethodData methodData) { if (methodData == null) throw new ArgumentNullException("methodData"); return Execute; }
public static string JobType(MethodData methodData) { if (methodData == null) { return "Could not find the target method."; } return methodData.Type.FullName; }
public JobAsMethodPerformStrategy( MethodData methodData, string[] arguments) { if (methodData == null) throw new ArgumentNullException("methodData"); if (arguments == null) throw new ArgumentNullException("arguments"); _methodData = methodData; _arguments = arguments; }
public void Ctor_CorrectlySets_PropertyValues() { var type = typeof (TestJob); var methodInfo = type.GetMethod("Perform"); var method = new MethodData(type, methodInfo); Assert.Equal(type, method.Type); Assert.Equal(methodInfo, method.MethodInfo); Assert.False(method.OldFormat); }
public static string DisplayMethod(MethodData methodData) { if (methodData == null) { return null; } var separator = methodData.MethodInfo.IsStatic ? "." : "::"; return String.Format("{0}{1}{2}", methodData.Type.Name, separator, methodData.MethodInfo.Name); }
public JobAsClassPerformStrategy( MethodData methodData, Dictionary<string, string> arguments) { if (methodData == null) throw new ArgumentNullException("methodData"); if (arguments == null) throw new ArgumentNullException("arguments"); _methodData = methodData; _arguments = arguments; }
public virtual IEnumerable<JobFilter> GetFilters(MethodData methodData) { var typeFilters = GetTypeAttributes(methodData) .Select(attr => new JobFilter(attr, JobFilterScope.Type, null)); var methodFilters = GetMethodAttributes(methodData) .Select(attr => new JobFilter(attr, JobFilterScope.Method, null)); return typeFilters.Union(methodFilters).ToList(); }
public static IEnumerable<MethodData> GetImplementedMethods(MethodData method) { var type = method.DeclaringType; if (type.Inner.IsInterface) return Enumerable.Empty<MethodData>(); return from implementation in type.ImplementedInterfaces from map in implementation.Members.AsEnumerable() where map.Value == method select (MethodData)map.Key; }
public ApplyStateContextFacts() { _methodData = MethodData.FromExpression(() => Console.WriteLine()); _newStateMock = new Mock<State>(); _newStateMock.Setup(x => x.Name).Returns(NewState); _transaction = new Mock<IWriteOnlyTransaction>(); _filters = new List<IApplyStateFilter>(); _handlers = new StateHandlerCollection(); }
/// <summary> /// Sets up a reflected asynchronous <see cref="MethodBase"/> execution. /// </summary> /// <param name="methodData">The method data.</param> /// <returns>A reflected asynchronous <see cref="MethodBase"/> execution.</returns> /// <exception cref="ArgumentNullException">The <paramref name="methodData"/> parameter is <see langword="null"/>.</exception> Func<Task> IExecutionSetup.Setup(MethodData methodData) { if (methodData == null) throw new ArgumentNullException("methodData"); _methodUnderTest = methodData.MethodUnderTest; _parameters = methodData.Parameters; _sut = methodData.InstanceUnderTest; return Execute; }
public static IEnumerable<MethodData> GetBaseMethods(MethodData method) { var lastBaseMethod = method; var baseMethod = method.Base; while (lastBaseMethod != baseMethod) { yield return baseMethod; lastBaseMethod = baseMethod; baseMethod = baseMethod.Base; } }
private void CollectDirectlyUsedBy(MethodData method) { method.GetReferencedMethods().Cast<IMemberData>().ForEach(this.Collect); this.methodsByBases[method].Cast<IMemberData>().ForEach(this.Collect); var generic = method.GetGenericDefinition(); if (generic != null) this.Collect(generic); var propertyOrEvent = method.DeclaringMember; if (propertyOrEvent != null) this.Collect(propertyOrEvent); }
public async Task SetupThrowingExecution( [Frozen(Matching.DirectBaseType)] ApplicationException expected, ErroredExecutionSetup sut, MethodData methodData) { // Act Func<Task> execute = ((IExecutionSetup) sut).Setup(methodData); // Executing method should not throw but return a faulted task. Task task = execute(); // Assert Assert.True(task.IsFaulted); ApplicationException actual = await Assert.ThrowsAsync<ApplicationException>(() => task); Assert.Same(expected, actual); }
public void ToCode_given_ConstructorDataWithBody_should_ReturnProper() { // # Arrange. const string ClassName = "Customer"; var sut = new MethodData { IsConstructor = true, Scope = Common.VisibilityScope.Internal, Name = ClassName, Parameters = new List<ParameterData> { new ParameterData { Name=ClassName, SystemTypeString = ClassName } }, Body = new BodyData { Lines= new List<string> { "this.CustomerId = customer.CustomerId;", "this.CustomerName = customer.CustomerName;" } } }; // # Act. var res = sut.ToCode(); // # Assert. CollectionAssert.AreEqual( new[] { "internal Customer( Customer customer )", "{", "\tthis.CustomerId = customer.CustomerId;", "\tthis.CustomerName = customer.CustomerName;", "}" }, res.ToList()); }
void drawThreadDestroy(Graphics g, MethodData d, float startY, float endY) { String threadID = d.methodEvent.ThreadID; float x = d.getColumnLeftX() + methodBodyWidth * zoomScale * 0.25f; Pen pen = new Pen(getThreadColor(threadID), 2 * zoomScale); Brush brush = new SolidBrush(getThreadColor(threadID)); float[] dashValues = { 4, 1 }; pen.DashPattern = dashValues; float arrowWidth = 5 * zoomScale; g.DrawLine(pen, x, startY, x, endY); g.DrawLine(pen, 0, endY, x, endY); g.DrawLine(pen, 0, endY, arrowWidth, endY - arrowWidth); g.DrawLine(pen, 0, endY, arrowWidth, endY + arrowWidth); }
public new bool ShouldSelect(MethodData method, ISelectionContext context) { return(base.ShouldSelect(method, context)); }
public X86Codes ConvertIL(MethodData md, ILCode il) { string mne = il.OpCode.Name; if (mne == null) { return(null); } X86Codes ret = new X86Codes(); ret.Address = il.Address; ret.IsBrTarget = il.IsBrTarget; if (il.Operand is byte) { ret.Comment = string.Format("{0} {1:X2}", mne, il.Operand); } else if (il.Operand is short) { ret.Comment = string.Format("{0} {1:X4}", mne, il.Operand); } else if (il.Operand is int) { ret.Comment = string.Format("{0} {1:X8}", mne, il.Operand); } else { ret.Comment = mne; } int mne_last = mne.Length < 1 ? 0 : (int)(mne[mne.Length - 1] - '0'); int nOp = Util.GetOperandValue(il); switch (mne) { case "ldc.i4": case "ldc.i4.s": case "ldc.i4.0": case "ldc.i4.1": case "ldc.i4.2": case "ldc.i4.3": case "ldc.i4.4": case "ldc.i4.5": case "ldc.i4.6": case "ldc.i4.7": case "ldc.i4.8": ret.Codes.Add(new X86Code("mov", "ax", nOp.ToString())); ret.Codes.Add(new X86Code("push", "ax")); break; case "ldloc": case "ldloc.s": case "ldloc.0": case "ldloc.1": case "ldloc.2": case "ldloc.3": ret.Codes.Add(new X86Code("push", string.Format("word [ss:bp-{0}]", (nOp + 1) * 2))); break; case "ldloca": case "ldloca.s": ret.Codes.Add(new X86Code("mov", "ax", "bp")); ret.Codes.Add(new X86Code("sub", string.Format("ax, {0}", (nOp + 1) * 2))); ret.Codes.Add(new X86Code("push", "ax")); break; case "stloc": case "stloc.s": case "stloc.0": case "stloc.1": case "stloc.2": case "stloc.3": ret.Codes.Add(new X86Code("pop", string.Format("word [ss:bp-{0}]", (nOp + 1) * 2))); break; case "ldarg": case "ldarg.s": case "ldarg.0": case "ldarg.1": case "ldarg.2": case "ldarg.3": ret.Codes.Add(new X86Code("push", string.Format("word [ss:bp+{0}]", Util.GetArgPos(md, nOp, this.optimize)))); break; case "starg": case "starg.s": ret.Codes.Add(new X86Code("pop", string.Format("word [ss:bp+{0}]", Util.GetArgPos(md, nOp, this.optimize)))); break; case "ldstr": { int us = ((int)il.Operand) & 0xffffff; if (!this.listUS.Contains(us)) { this.listUS.Add(us); } ret.Codes.Add(new X86Code("mov", "ax", string.Format("US_{0:X8}", us))); ret.Codes.Add(new X86Code("push", "ax")); break; } case "ldsfld": { TableBase tb = this.pedata.idxm.GetTable((int)il.Operand); ret.Codes.Add(new X86Code("push", string.Format("word [cs:{0}]", MangleField(tb as FieldTable)))); break; } case "stsfld": { TableBase tb = this.pedata.idxm.GetTable((int)il.Operand); ret.Codes.Add(new X86Code("pop", string.Format("word [cs:{0}]", MangleField(tb as FieldTable)))); break; } case "pop": ret.Codes.Add(new X86Code("pop", "ax")); break; case "br": case "br.s": ret.Codes.Add(new X86Code("jmp", string.Format("PE_{0:X8}", Girl.PEAnalyzer.Util.GetBrTarget(il)))); if (this.optimize > 0 && nOp == 0) { ret.Ignore(); } break; case "beq": case "beq.s": ret.Codes.Add(new X86Code("pop", "ax")); ret.Codes.Add(new X86Code("pop", "dx")); ret.Codes.Add(new X86Code("cmp", "ax", "dx")); ret.Codes.Add(new X86Code("je", string.Format("PE_{0:X8}", Girl.PEAnalyzer.Util.GetBrTarget(il)))); if (this.optimize > 0 && nOp == 0) { ret.Ignore(); } break; case "bne.un": case "bne.un.s": ret.Codes.Add(new X86Code("pop", "ax")); ret.Codes.Add(new X86Code("pop", "dx")); ret.Codes.Add(new X86Code("cmp", "ax", "dx")); ret.Codes.Add(new X86Code("jne", string.Format("PE_{0:X8}", Girl.PEAnalyzer.Util.GetBrTarget(il)))); if (this.optimize > 0 && nOp == 0) { ret.Ignore(); } break; case "bgt": case "bgt.s": ret.Codes.Add(new X86Code("pop", "ax")); ret.Codes.Add(new X86Code("pop", "dx")); ret.Codes.Add(new X86Code("cmp", "ax", "dx")); ret.Codes.Add(new X86Code("jc", string.Format("PE_{0:X8}", Girl.PEAnalyzer.Util.GetBrTarget(il)))); if (this.optimize > 0 && nOp == 0) { ret.Ignore(); } break; case "blt": case "blt.s": ret.Codes.Add(new X86Code("pop", "ax")); ret.Codes.Add(new X86Code("pop", "dx")); ret.Codes.Add(new X86Code("cmp", "dx", "ax")); ret.Codes.Add(new X86Code("jc", string.Format("PE_{0:X8}", Girl.PEAnalyzer.Util.GetBrTarget(il)))); if (this.optimize > 0 && nOp == 0) { ret.Ignore(); } break; case "ble": case "ble.s": ret.Codes.Add(new X86Code("pop", "ax")); ret.Codes.Add(new X86Code("pop", "dx")); ret.Codes.Add(new X86Code("cmp", "ax", "dx")); ret.Codes.Add(new X86Code("jnc near", string.Format("PE_{0:X8}", Girl.PEAnalyzer.Util.GetBrTarget(il)))); if (this.optimize > 0 && nOp == 0) { ret.Ignore(); } break; case "bge": case "bge.s": ret.Codes.Add(new X86Code("pop", "ax")); ret.Codes.Add(new X86Code("pop", "dx")); ret.Codes.Add(new X86Code("cmp", "dx", "ax")); ret.Codes.Add(new X86Code("jnc", string.Format("PE_{0:X8}", Girl.PEAnalyzer.Util.GetBrTarget(il)))); if (this.optimize > 0 && nOp == 0) { ret.Ignore(); } break; case "brfalse": case "brfalse.s": ret.Codes.Add(new X86Code("pop", "ax")); ret.Codes.Add(new X86Code("or", "ax", "ax")); ret.Codes.Add(new X86Code("jz", string.Format("PE_{0:X8}", Girl.PEAnalyzer.Util.GetBrTarget(il)))); if (this.optimize > 0 && nOp == 0) { ret.Ignore(); } break; case "brtrue": case "brtrue.s": ret.Codes.Add(new X86Code("pop", "ax")); ret.Codes.Add(new X86Code("or", "ax", "ax")); ret.Codes.Add(new X86Code("jnz", string.Format("PE_{0:X8}", Girl.PEAnalyzer.Util.GetBrTarget(il)))); if (this.optimize > 0 && nOp == 0) { ret.Ignore(); } break; case "call": { TableBase tb = this.pedata.idxm.GetTable((int)il.Operand); MethodData tb_md = tb.Tag as MethodData; ret.Codes.Add(new X86Code("call", string.Format("{0}", Util.MangleFunction(tb_md)))); if (tb_md.RetType.Element != ELEMENT_TYPE.VOID) { ret.Codes.Add(new X86Code("push", "ax")); } break; } //case "callvirt": //{ // TableBase tb = this.pedata.idxm.GetTable((int)il.Operand); // MethodData tb_md = tb.Tag as MethodData; // string func = Util.MangleFunction(tb_md); // if (func.StartsWith("instance__")) func = func.Substring(10, func.Length - 10); // sw.WriteLine("\tcall _virtual__{0}", func); // if (tb_md.RetType.Element != ELEMENT_TYPE.VOID) sw.WriteLine("\tpush ax"); // break; //} case "ret": if (this.optimize == 0 || il == this.lastRet) { if (md.RetType.Element != ELEMENT_TYPE.VOID) { ret.Codes.Add(new X86Code("pop", "ax")); } if (md.LocalVars != null || md.ParamCount > 0) { if (md.LocalVars != null) { ret.Codes.Add(new X86Code("mov", "sp", "bp")); } ret.Codes.Add(new X86Code("pop", "bp")); } int st = Util.GetStackSize(md); if (st == 0) { ret.Codes.Add(new X86Code("ret")); } else { ret.Codes.Add(new X86Code("ret", st.ToString())); } } else { X86Code x = new X86Code("jmp", string.Format("PE_{0:X8}", this.lastRet.Address)); x.Notes = "[optimize] modify"; ret.Codes.Add(x); this.lastRet.IsBrTarget = true; } break; case "ceq": ret.Codes.Add(new X86Code("pop", "ax")); ret.Codes.Add(new X86Code("pop", "dx")); ret.Codes.Add(new X86Code("cmp", "ax", "dx")); ret.Codes.Add(new X86Code("je", string.Format("NM_{0:X8}", this.number))); ret.Codes.Add(new X86Code("xor", "ax", "ax")); ret.Codes.Add(new X86Code("jmp", string.Format("NM_{0:X8}", this.number + 1))); ret.Codes.Add(new X86Code(string.Format("NM_{0:X8}", this.number), true, "ceq internal", "mov", "ax", "1")); ret.Codes.Add(new X86Code(string.Format("NM_{0:X8}", this.number + 1), true, "ceq internal", "push", "ax")); this.number += 2; break; case "add": case "and": case "or": ret.Codes.Add(new X86Code("pop", "ax")); ret.Codes.Add(new X86Code("pop", "dx")); ret.Codes.Add(new X86Code(mne, "ax", "dx")); ret.Codes.Add(new X86Code("push", "ax")); break; case "sub": ret.Codes.Add(new X86Code("pop", "dx")); ret.Codes.Add(new X86Code("pop", "ax")); ret.Codes.Add(new X86Code("sub", "ax", "dx")); ret.Codes.Add(new X86Code("push", "ax")); break; case "mul": ret.Codes.Add(new X86Code("pop", "ax")); ret.Codes.Add(new X86Code("pop", "dx")); ret.Codes.Add(new X86Code("mul", "dx")); ret.Codes.Add(new X86Code("push", "ax")); break; case "div": ret.Codes.Add(new X86Code("pop", "cx")); ret.Codes.Add(new X86Code("pop", "ax")); ret.Codes.Add(new X86Code("xor", "dx", "dx")); ret.Codes.Add(new X86Code("div", "cx")); ret.Codes.Add(new X86Code("push", "ax")); break; case "rem": ret.Codes.Add(new X86Code("pop", "cx")); ret.Codes.Add(new X86Code("pop", "ax")); ret.Codes.Add(new X86Code("xor", "dx", "dx")); ret.Codes.Add(new X86Code("div", "cx")); ret.Codes.Add(new X86Code("push", "dx")); break; case "neg": ret.Codes.Add(new X86Code("pop", "ax")); ret.Codes.Add(new X86Code("neg", "ax")); ret.Codes.Add(new X86Code("push", "ax")); break; case "shr": case "shl": ret.Codes.Add(new X86Code("pop", "cx")); ret.Codes.Add(new X86Code("pop", "ax")); ret.Codes.Add(new X86Code(mne, "ax", "cl")); ret.Codes.Add(new X86Code("push", "ax")); break; case "conv.u1": ret.Codes.Add(new X86Code("pop", "ax")); ret.Codes.Add(new X86Code("mov", "ah", "0")); ret.Codes.Add(new X86Code("push", "ax")); break; case "conv.i2": case "conv.u2": case "conv.i4": case "conv.u4": // ignore in 16bit return(ret); //case "box": //{ // TypeRefTable t = this.pedata.idxm.GetTable((int)il.Operand) as TypeRefTable; // sw.WriteLine("\tcall _box__{0}@4", GetTypeName(this.pedata.idxm.GetName(t))); // sw.WriteLine("\tpush ax"); // break; //} } if (ret.Codes.Count < 1) { return(null); } return(ret); }
protected virtual JobFilterInfo GetFilters(MethodData methodData) { return new JobFilterInfo(_getFiltersThunk(methodData)); }
private static bool IsBetterThan(Expression[] args, MethodData m1, MethodData m2) { bool better = false; for (int i = 0; i < args.Length; i++) { int c = CompareConversions(args[i].Type, m1.Parameters[i].ParameterType, m2.Parameters[i].ParameterType); if (c < 0) return false; if (c > 0) better = true; } return better; }
protected virtual IEnumerable<JobFilterAttribute> GetMethodAttributes( MethodData methodData) { return methodData.GetMethodFilterAttributes(_cacheAttributeInstances); }
private bool IsApplicable(MethodData method, Expression[] args) { if (method.Parameters.Length != args.Length) return false; var expressionArray = new Expression[args.Length]; for (int index = 0; index < args.Length; ++index) { ParameterInfo parameterInfo = method.Parameters[index]; if (parameterInfo.IsOut) return false; Expression expression = this.PromoteExpression(args[index], parameterInfo.ParameterType, false); if (expression == null) return false; expressionArray[index] = expression; } method.Args = expressionArray; return true; }
public async Task TestStringInput(MethodData method) { await method.Execute().ConfigureAwait(false); Assert.True(SomeNullableValueTypeParameters.StringInputTested); }
//建立编译文件 public void CreateCompile(bool build) { string[] fileNames; //获取要生成的文件 if (genConfig != null) { if (genConfig.controllerFiles.Count > 0) { fileNames = new string[genConfig.controllerFiles.Count]; for (int i = 0; i < fileNames.Length; i++) { fileNames[i] = Frame.MapPath(genConfig.controllerFiles[i]); } } else { return; } } else { if (!Directory.Exists(Frame.MapPath(config.Controller))) { return; } //获取所有的controls文件 fileNames = Directory.GetFiles(Frame.MapPath(config.Controller), "*.cs", SearchOption.AllDirectories); if (fileNames == null || fileNames.Length < 1) { return; } } //生成的代码 string compileCode = ""; //类名称 string ClassName = ""; //前面的字符串部分添加或删除后,后面的代码的相对位置 int relative_postion = 0; if (fileNames.Length > 0) { Compiler com = new Compiler(); FileData fileData = null; ClassData classData = null; MethodData methodData = null; StreamWriter sw = null; VTemplate.Engine.TemplateDocument swDebug = null; //VTemplate.Engine.TemplateDocument swAspx = null; string compileFileName = ""; string compileDir = ""; string debugFileName = ""; string methodContent = ""; for (int i = 0; i < fileNames.Length; i++) { fileData = fileData = com.GetFileData(Frame.appRoot, this.config.APP, fileNames[i], System.Text.Encoding.UTF8); ClassName = Path.GetFileNameWithoutExtension(fileNames[i]); classData = fileData.GetClassData(ClassName); if (classData.MethodDataList.Count > 0) { for (int j = 0; j < classData.MethodDataList.Count; j++) { //只有公开方法才能访问 if (classData.MethodDataList[j].isPublic) { relative_postion = 0; compileCode = fileData.csharpCode.ToString(); methodData = classData.MethodDataList[j]; //相对 compileDir = config.ChangeControllerName(config.Web + config.defaultStyle, (fileData.nameSpace + '.' + ClassName).Replace('.', '/')) + "/"; //绝对 compileFileName = Frame.MapPath(compileDir + methodData.name + ".cs"); if (!Directory.Exists(Path.GetDirectoryName(compileFileName))) { Directory.CreateDirectory(Path.GetDirectoryName(compileFileName)); } //调试文件 debugFileName = Frame.MapPath(compileDir + methodData.name + ".html"); //输出调试文件 if (!File.Exists(debugFileName)) { swDebug = new VTemplate.Engine.TemplateDocument(Frame.MapPath("/NFinal/Template/Debug.tpl"), System.Text.Encoding.UTF8); swDebug.SetValue("Url", config.ChangeControllerName(config.APP, (fileData.nameSpace + '.' + ClassName).Replace('.', '/')) + "/" + methodData.name + ".htm"); swDebug.RenderTo(debugFileName, System.Text.Encoding.UTF8); } relative_postion += Replace(ref compileCode, relative_postion + fileData.start, fileData.length, "namespace " + (Frame.AssemblyTitle + compileDir.TrimEnd('/')).Replace('/', '.') + "\r\n{"); relative_postion += Replace(ref compileCode, relative_postion + classData.start, classData.length, "public class " + methodData.name + "Action " + (string.IsNullOrEmpty(classData.baseName) ? "" : " : " + classData.baseName) + "\r\n\t{" //添加初始化函数 + "\r\n\t\tpublic " + methodData.name + "Action(System.IO.TextWriter tw):base(tw){}" + "\r\n\t\tpublic " + methodData.name + "Action(string fileName) : base(fileName) {}"); //循环内部所有方法 for (int k = 0; k < classData.MethodDataList.Count; k++) { methodData = classData.MethodDataList[k]; //如果两个相等,则进行替换 if (j == k || (!classData.MethodDataList[k].isPublic)) { #region "替换原有方法" //排除非公开和非基类的方法,替换原有方法体 //if (methodData.isPublic) { methodContent = methodData.Content; SqlCompiler sqlCompiler = new NFinal.Compile.SqlCompiler(); //从代码中分析出数据库相关函数 List <DbFunctionData> dbFunctions = sqlCompiler.Compile(com.DeleteComment(methodContent)); if (dbFunctions.Count > 0) { SqlAnalyse analyse = new SqlAnalyse(); //与数据库相结合,从sql语句中分析出所有的表信息,列信息 methodData.dbFunctions = analyse.FillFunctionDataList(NFinal.DB.Coding.DB.DbStore, dbFunctions); } //数据库函数替换 int content_relative_position = 0; string StructDatas = string.Empty; if (dbFunctions.Count > 0) { bool hasSameVarName = false; List <string> varNames = new List <string>(); //添加struct类型 for (int s = 0; s < dbFunctions.Count; s++) { //去除重复项 if (varNames.Count > 0) { hasSameVarName = false; for (int c = 0; c < varNames.Count; c++) { //如果发现重复项,则跳过循环 if (varNames[c] == dbFunctions[s].varName) { hasSameVarName = true; break; } } if (hasSameVarName) { continue; } } varNames.Add(dbFunctions[s].varName); //分析出sql返回的List<dynamic>和dynamic类型是否有用AddNewField(string fileName,Type t);添加相关的类型 NewField newFiled = new NewField(dbFunctions[s].varName); List <NFinal.Compile.StructField> structFieldList = newFiled.GetFields(ref methodContent, methodData.name); //添加struct字段 string StructData = sqlCompiler.SetMagicStruct(methodData.name, dbFunctions[s], structFieldList, Frame.appRoot); StructDatas += StructData; if (!string.IsNullOrEmpty(StructData)) { compileCode = compileCode.Insert(methodData.start + relative_postion, StructData); relative_postion += StructData.Length; } } //更换函数中的数据库操作 content_relative_position += sqlCompiler.SetMagicFunction(methodData.name, ref methodContent, content_relative_position, methodData.dbFunctions, Frame.appRoot); //分析并更换其中的连接字符串 content_relative_position += sqlCompiler.SetMagicConnection(methodData.name, ref methodContent, Frame.appRoot ); } if (methodData.parameterTypeAndNames != string.Empty) { relative_postion += Replace(ref compileCode, relative_postion + methodData.parametersIndex, methodData.parametersLength, methodData.parameterTypeAndNames); } //从代码中分析出views函数 NFinal.Compile.ViewCompiler viewCompiler = new NFinal.Compile.ViewCompiler(); List <ViewData> views = viewCompiler.Compile(methodContent); //模版替换 if (views.Count > 0) { content_relative_position = 0; content_relative_position = viewCompiler.SetMagicFunction(ref methodContent, content_relative_position, fileData.nameSpace, ClassName, methodData.name, views, config); } if (build) { relative_postion += Replace(ref compileCode, relative_postion + methodData.position, methodData.Content.Length, methodContent); } else { relative_postion += Replace(ref compileCode, relative_postion + methodData.position, methodData.Content.Length, string.Empty); } //生成自动提示类 //views,Structs,DBFunctions AutoCompleteCompiler autoComplete = new AutoCompleteCompiler(); autoComplete.Compile(classData.baseName, methodData, StructDatas, views, fileData.nameSpace, ClassName, config); } #endregion } //如果两个不相等 else { compileCode = compileCode.Remove(relative_postion + classData.MethodDataList[k].start, classData.MethodDataList[k].length + classData.MethodDataList[k].Content.Length + 1);//去掉最后一个} relative_postion -= classData.MethodDataList[k].length + classData.MethodDataList[k].Content.Length + 1; } } //写aspx页面的自动提示层 //写Web层.class文件 sw = new StreamWriter(compileFileName, false, System.Text.Encoding.UTF8); sw.Write(compileCode); sw.Close(); } } } } } }
public bool WriteAsm(string asm) { MethodDefTable m = this.pedata.idxm.GetTable(this.pedata.cli.EntryPointToken) as MethodDefTable; if (m == null) { System.Console.WriteLine("Can not find entry point!"); return(false); } this.entryPoint = m.Tag as MethodData; System.Console.WriteLine("Entry Point: {0}", this.entryPoint.FullName); bool ok = true; FileStream fs = new FileStream(asm, FileMode.Create); StreamWriter sw = new StreamWriter(fs); this.hashUS = new Hashtable(); this.listUS = new ArrayList(); if (this.pedata.usrstr != null) { int ad = this.pedata.usrstr.GetDataOffset(), ptr = 1; while (this.data[ad + ptr] != 0 && ptr < this.pedata.usrstr.Size) { DoubleInt dataSize = this.pedata.usrstr.GetDataSize(ad + ptr); byte[] bytes = Girl.PEAnalyzer.Util.GetBytes(this.data, ad + ptr + dataSize.A, dataSize.B); this.hashUS[ptr] = Encoding.Unicode.GetString(bytes, 0, dataSize.B - 1); ptr += dataSize.A + dataSize.B; } } this.number = 0; sw.WriteLine("; This file was automatically generated by IL2Asm16."); if (this.pre != null) { this.InsertFile(sw, this.pre); } sw.WriteLine(); sw.WriteLine("[bits 16]"); if (!this.noMain) { sw.WriteLine("jmp {0}", this.jumpTo); sw.WriteLine(); sw.WriteLine("ILMain:"); foreach (object obj in this.pedata.idxm.Tables[(int)MetadataTables.TypeDef]) { TypeDefTable t = obj as TypeDefTable; foreach (object obj2 in t.Children[(int)Children.DefMethod]) { MethodDefTable mdt = obj2 as MethodDefTable; MethodData md = mdt.Tag as MethodData; if (!md.Name.EndsWith("::.cctor")) { continue; } sw.WriteLine("\tcall\t{0}", Util.MangleFunction(md)); } } sw.WriteLine("\tcall\t{0}", Util.MangleFunction(this.entryPoint)); sw.WriteLine("\tret"); } foreach (object obj in this.pedata.idxm.Tables[(int)MetadataTables.TypeDef]) { TypeDefTable t = obj as TypeDefTable; sw.WriteLine(); if (!this.WriteAsm(sw, t)) { ok = false; } } if (this.listUS.Count > 0) { sw.WriteLine(); this.listUS.Sort(); foreach (object obj in this.listUS) { int ptr = (int)obj; string str = this.hashUS[ptr] as string; bool instr = false; StringBuilder sb = new StringBuilder(); foreach (char ch in str) { if (ch < ' ') { if (instr) { sb.Append('\"'); instr = false; } if (sb.Length > 0) { sb.Append(", "); } sb.AppendFormat("0x{0:x2}", (int)ch); } else { if (!instr) { sb.Append('\"'); instr = true; } sb.Append(ch); } } if (instr) { sb.Append('\"'); } sw.WriteLine("US_{0:X8} db {1}, {2}, 0x00", ptr, str.Length, sb); } } if (this.post != null) { this.InsertFile(sw, this.post); } sw.Close(); fs.Close(); return(ok); }
private MethodData GetMethodData(MethodCall methodCall) { MethodData methodData; MethodBase method = methodCall.MethodBase; if (_methodDataCache.TryGetMethodData(method, out methodData)) { return(methodData); } bool canCacheMessageData; Type declaringType = method.DeclaringType; if (declaringType == typeof(object) && method == typeof(object).GetMethod("GetType")) { canCacheMessageData = true; methodData = new MethodData(method, MethodType.GetType); } else if (declaringType.IsAssignableFrom(_serviceChannel.GetType())) { canCacheMessageData = true; methodData = new MethodData(method, MethodType.Channel); } else { ProxyOperationRuntime operation = _proxyRuntime.GetOperation(method, methodCall.Args, out canCacheMessageData); if (operation == null) { if (_serviceChannel.Factory != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SFxMethodNotSupported1, method.Name))); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SFxMethodNotSupportedOnCallback1, method.Name))); } } MethodType methodType; if (operation.IsTaskCall(methodCall)) { methodType = MethodType.TaskService; } else if (operation.IsSyncCall(methodCall)) { methodType = MethodType.Service; } else if (operation.IsBeginCall(methodCall)) { methodType = MethodType.BeginService; } else { methodType = MethodType.EndService; } methodData = new MethodData(method, methodType, operation); } if (canCacheMessageData) { _methodDataCache.SetMethodData(methodData); } return(methodData); }
private static IconAccess GetAccess(MethodData method) { if (method.Inner.IsPrivate) return IconAccess.Private; if (method.Inner.IsFamily) return IconAccess.Protected; if (method.Inner.IsAssembly || method.Inner.IsFamilyOrAssembly) return IconAccess.Internal; return IconAccess.Public; }
public MethodWapper(MethodData methodData, ManagementObject wmiInstance) { Method = methodData; WMIInstance = wmiInstance; }
private MethodData PackMethod(MethodDefinition method) { var sinst = new List <StoredInstruction>(); foreach (var inst in method.Body.Instructions) { if (inst.Operand is Instruction) { continue; } var _op = inst.Operand; if (_op is TypeReference) { var op = (TypeReference)_op; _op = new StoredTypeReference() { name = op.Name, ns = op.Namespace }; } else if (_op is FieldReference) { var op = (FieldReference)_op; _op = new StoredFieldReference() { name = op.Name }; } else if (_op is MethodReference) { var op = (MethodReference)_op; _op = new StoredMethodReference() { name = op.Name }; } else if (_op is VariableReference) { var op = (VariableReference)_op; _op = new StoredVariableReference() { }; } sinst.Add(new StoredInstruction() { opcode = inst.OpCode, operand = _op }); if (inst.Operand != null) { Console.WriteLine(inst.Operand.GetType()); } } var methodData = new MethodData() { instructions = sinst.ToArray() }; Console.WriteLine(JsonConvert.SerializeObject(methodData, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore })); return(methodData); }
protected override void OnPaint(PaintEventArgs eva) { base.OnPaint(eva); classData = new Hashtable(); lastMethodData = new Hashtable(); nextFreeColumn = 0; Graphics g = eva.Graphics; g.FillRectangle(new SolidBrush(Color.White), new Rectangle(0, 0, Width, Height)); if (events.Count == 0) { return; } if (zoomScale >= 0.5) { g.TranslateTransform(padding + padding + timestampWidth, padding); } else { g.TranslateTransform(padding, padding); } double lastTimestamp = -1; double firstTimeStamp = lastTimestamp; float lastY = 0; double mediumDeltaTime = getMediumDeltaTime(); String lastThreadId = null; Hashtable threadCreationY = new Hashtable(); Hashtable threadDestroyY = new Hashtable(); foreach (LogEvent logEvent in events) { if (logEvent is MethodEvent) { MethodEvent e = (MethodEvent)logEvent; if (unwantedObjectIDs.Contains(e.InstanceObjectID)) continue; if (unwantedThreadIDs.Contains(e.ThreadID)) continue; if (unwantedClassesIDs.Contains(e.MethodInfo.ClassName)) continue; } if (logEvent is ThreadEvent) { ThreadEvent e = (ThreadEvent)logEvent; if (unwantedThreadIDs.Contains(e.ThreadID)) continue; } if (lastTimestamp == -1) { firstTimeStamp = logEvent.timestamp; lastTimestamp = logEvent.timestamp; } double deltaTime = logEvent.timestamp - lastTimestamp; float deltaY = (float) Math.Max(20, Math.Min(40 * (deltaTime / mediumDeltaTime), 80)) * zoomScale; float topY = padding + lastY - 20; float bottomY = topY + deltaY + 40; bool hasToDraw = !((topY <= eva.ClipRectangle.Top && bottomY <= eva.ClipRectangle.Top) || (topY >= eva.ClipRectangle.Bottom && bottomY >= eva.ClipRectangle.Bottom)); if (hasToDraw) { if (zoomScale >= 0.5) { String time = convertToReadableNumber(lastTimestamp + deltaTime - firstTimeStamp); g.DrawString(time, new Font("Courier New", 7), Brushes.Black, -padding - timestampWidth, deltaY + lastY - 7); } foreach (DictionaryEntry de in classData) { ClassData d = (ClassData)de.Value; foreach (MethodData m in d.methodData) { if (m.classData.getColumnLeftX() < eva.ClipRectangle.Right && m.classData.getColumnRightX() > eva.ClipRectangle.Left) { drawMethodData(g, m, lastY, lastY + deltaY); } } } } if (logEvent is MethodEvent) { MethodEvent e = (MethodEvent) logEvent; String currentThreadID = e.ThreadID; bool mustDrawHeader = !classData.ContainsKey(e.getHash()); ClassData currentClassData = getOrCreateClassData(e); if (mustDrawHeader) { drawHeader(g, e, currentClassData.getColumnLeftX(), lastY + deltaY); currentClassData.creationY = lastY + deltaY; } if (e.EventType == MethodEvent.EventTypeEnum.EnterEvent) { MethodData currentMethodData = new MethodData(); if (lastMethodData.ContainsKey(currentThreadID)) currentMethodData.callerMethodData = (MethodData) lastMethodData[currentThreadID]; currentMethodData.classData = currentClassData; currentMethodData.methodColumnNumber = currentClassData.methodData.Count; currentMethodData.methodEvent = e; currentClassData.methodData.Add(currentMethodData); lastMethodData[currentThreadID] = currentMethodData; if (hasToDraw) drawMethodEnter(g, currentMethodData, lastY + deltaY); if (threadCreationY.ContainsKey(currentThreadID)) { float startY = (float)threadCreationY[currentThreadID]; drawThreadCreate(g, currentMethodData, startY, lastY + deltaY); threadCreationY.Remove(currentThreadID); } } else if (e.EventType == MethodEvent.EventTypeEnum.LeaveEvent && currentClassData.methodData.Count > 0) { MethodData currentMethodData = (MethodData) currentClassData.methodData[currentClassData.methodData.Count - 1]; lastMethodData[currentThreadID] = currentMethodData.callerMethodData; currentClassData.methodData.RemoveAt(currentClassData.methodData.Count - 1); threadDestroyY[currentThreadID] = currentMethodData; currentMethodData.leaveY = lastY + deltaY; if (hasToDraw) drawMethodLeave(g, currentMethodData, lastY + deltaY); } lastThreadId = currentThreadID; } if (logEvent is ExceptionEvent) { if (hasToDraw && lastThreadId != null) drawException(g, (MethodData) lastMethodData[lastThreadId], lastY + deltaY); } if (logEvent is ThreadEvent) { ThreadEvent threadEvent = (ThreadEvent)logEvent; if (threadEvent.EventType == ThreadEvent.EventTypeEnum.CreateEvent) { drawThreadCreated(g, threadEvent.ThreadID, lastY + deltaY); threadCreationY[threadEvent.ThreadID] = lastY + deltaY; } if (threadEvent.EventType == ThreadEvent.EventTypeEnum.DestroyEvent) { MethodData md = (MethodData)threadDestroyY[threadEvent.ThreadID]; drawThreadDestroyed(g, threadEvent.ThreadID, lastY + deltaY); if (md != null) drawThreadDestroy(g, md, md.leaveY, lastY + deltaY); } } lastY += deltaY; lastTimestamp = logEvent.timestamp; } Pen blackPen = new Pen(Color.Gray); foreach (DictionaryEntry d in this.classData) { ClassData c = (ClassData)d.Value; g.DrawLine(blackPen, c.getColumnMidX(), c.creationY, c.getColumnMidX(), lastY); } this.MinimumSize = new Size((int)(timestampWidth + 3.0f * padding + (nextFreeColumn * (colWidth + colInterspace)) * zoomScale), (int)(2.0f * padding * zoomScale + lastY + 40)); this.Size = this.MinimumSize; }
public void CreateDAL(bool build) { string[] fileNames; //获取要生成的文件 if (genConfig != null) { if (genConfig.bllFiles.Count > 0) { fileNames = new string[genConfig.bllFiles.Count]; for (int i = 0; i < fileNames.Length; i++) { fileNames[i] = Frame.MapPath(genConfig.bllFiles[i]); } } else { return; } } else { if (!Directory.Exists(Frame.MapPath(config.BLL))) { return; } //获取所有的bll文件 fileNames = Directory.GetFiles(Frame.MapPath(config.BLL), "*.cs", SearchOption.AllDirectories); if (fileNames == null || fileNames.Length < 1) { return; } } //生成的代码 string compileCode = ""; //类名称 string ClassName = ""; int relative_position = 0; if (fileNames.Length > 0) { Compiler com = new Compiler(); FileData fileData = null; ClassData classData = null; MethodData methodData = null; StreamWriter sw = null; string compileFileName = ""; string compileDir = ""; string methodContent = ""; for (int i = 0; i < fileNames.Length; i++) { relative_position = 0; fileData = com.GetFileData(Frame.appRoot, this.config.APP, fileNames[i], System.Text.Encoding.UTF8); ClassName = Path.GetFileNameWithoutExtension(fileNames[i]); classData = fileData.GetClassData(ClassName); compileCode = fileData.csharpCode.ToString(); //相对 compileDir = config.ChangeBLLName(config.DAL.Trim('/'), fileData.nameSpace.Replace('.', '/')); //绝对 compileFileName = Frame.MapPath(compileDir + "\\" + ClassName + ".cs"); //更改命名空间 relative_position += Replace(ref compileCode, relative_position + fileData.start, fileData.length, "namespace " + (Frame.AssemblyTitle + "/" + compileDir.TrimEnd('/')).Replace('/', '.') + "\r\n{"); if (classData.MethodDataList.Count > 0) { for (int j = 0; j < classData.MethodDataList.Count; j++) { methodData = classData.MethodDataList[j]; methodContent = methodData.Content; SqlCompiler sqlCompiler = new NFinal.Compile.SqlCompiler(); //从代码中分析出数据库相关函数 List <DbFunctionData> dbFunctions = sqlCompiler.Compile(com.DeleteComment(methodContent)); if (dbFunctions.Count > 0) { SqlAnalyse analyse = new SqlAnalyse(); //与数据库相结合,从sql语句中分析出所有的表信息,列信息 methodData.dbFunctions = analyse.FillFunctionDataList(NFinal.DB.Coding.DB.DbStore, dbFunctions); } //数据库函数替换 int content_relative_position = 0; if (dbFunctions.Count > 0) { bool hasSameVarName = false; List <string> varNames = new List <string>(); //添加struct类型 for (int s = 0; s < dbFunctions.Count; s++) { //去除重复项 if (varNames.Count > 0) { hasSameVarName = false; for (int c = 0; c < varNames.Count; c++) { //如果发现重复项,则跳过循环 if (varNames[c] == dbFunctions[s].varName) { hasSameVarName = true; break; } } if (hasSameVarName) { continue; } } varNames.Add(dbFunctions[s].varName); //分析出sql返回的List<dynamic>和dynamic类型是否有用AddNewField(string fileName,Type t);添加相关的类型 NewField newFiled = new NewField(dbFunctions[s].varName); List <NFinal.Compile.StructField> structFieldList = newFiled.GetFields(ref methodContent, methodData.name); //添加struct字段 string StructData = sqlCompiler.SetMagicStruct(methodData.name, dbFunctions[s], structFieldList, Frame.appRoot); if (!string.IsNullOrEmpty(StructData)) { compileCode = compileCode.Insert(methodData.start + relative_position, StructData); relative_position += StructData.Length; } } //修正函数返回类型,提高执行效率 if (methodData.returnType.IndexOf("dynamic") > -1) { string returnTypeString = ""; if (new System.Text.RegularExpressions.Regex(@"List\s*<\s*dynamic\s*>").IsMatch(methodData.returnType)) { returnTypeString = string.Format("NFinal.DB.NList<__{0}_{1}__>", methodData.name, methodData.returnVarName); } else { returnTypeString = string.Format("__{0}_{1}__", methodData.name, methodData.returnVarName); } relative_position += Replace(ref compileCode, methodData.returnTypeIndex + relative_position + classData.position, methodData.returnType.Length, returnTypeString); } //更换函数内的数据库操作函数 content_relative_position += sqlCompiler.SetMagicFunction(methodData.name, ref methodContent, content_relative_position, methodData.dbFunctions, Frame.appRoot); //分析并更换其中的连接字符串 content_relative_position += sqlCompiler.SetMagicConnection(methodData.name, ref methodContent, Frame.appRoot ); } if (build) { relative_position += Replace(ref compileCode, relative_position + methodData.position, methodData.Content.Length, methodContent); } else { if (methodData.returnType == "void") { relative_position += Replace(ref compileCode, relative_position + methodData.position, methodData.Content.Length, string.Empty); } else { relative_position += Replace(ref compileCode, relative_position + methodData.position, methodData.Content.Length, "return null;"); } } } } //如果文件夹不存在则新建 if (!Directory.Exists(Frame.MapPath(compileDir))) { Directory.CreateDirectory(Frame.MapPath(compileDir)); } //写DAL层.class文件 sw = new StreamWriter(compileFileName, false, System.Text.Encoding.UTF8); sw.Write(compileCode); sw.Close(); } } }
bool CheckIfMethodIsApplicableAndPrepareIt(MethodData method, Expression[] args) { if (method.Parameters.Length != args.Length) return false; Expression[] promotedArgs = new Expression[args.Length]; for (int i = 0; i < args.Length; i++) { ParameterInfo pi = method.Parameters[i]; if (pi.IsOut) return false; Expression promoted; if (pi.ParameterType.IsGenericParameter) { promoted = args[i]; } else { promoted = PromoteExpression(args[i], pi.ParameterType, true); if (promoted == null) return false; } promotedArgs[i] = promoted; } method.Args = promotedArgs; if (method.MethodBase.IsGenericMethodDefinition && method.MethodBase is MethodInfo) { var methodInfo = ((MethodInfo)method.MethodBase); var genericArgsType = new Type[methodInfo.GetGenericArguments().Length]; int genericArgsTypeIndex = 0; for (int i = 0; i < method.Args.Length; i++) { if (method.Parameters[i].ParameterType.IsGenericParameter) genericArgsType[genericArgsTypeIndex++] = method.Args[i].Type; } method.MethodBase = methodInfo.MakeGenericMethod(genericArgsType); } return true; }
//--------------------------------------------------------------------- // 立即玩 public async Task enterDesktopPlayNow() { if (IsEntering) { EbLog.Note("CellPlayerDesktop.enterDesktopPlayNow() 错误:正在进入中"); return; } IsEntering = true; if (!string.IsNullOrEmpty(DesktopEtGuid)) { await leaveDesktop(); } DesktopRequestPlayerEnter request_enter; request_enter.desktop_etguid = ""; request_enter.seat_index = 255; request_enter.player_clip = 0; request_enter.player_gold = CoActor.Def.PropGold.get(); request_enter.is_vip = CoActor.Def.mPropIsVIP.get(); var grain = Entity.getUserData <GrainCellPlayer>(); var grain_desktopservice = grain.GF.GetGrain <ICellDesktopService>(0); DesktopInfo desktop_info = await grain_desktopservice.searchDesktopAuto(request_enter); if (string.IsNullOrEmpty(desktop_info.desktop_etguid)) { EbLog.Note("CellPlayerDesktop.enterDesktopPlayNow() 获取桌子信息出错"); } else { EbLog.Note("CellPlayerDesktop.enterDesktopPlayNow() 获取桌子信息成功"); } // Step1:监听桌子广播 await _createDesktopStreamConsumer(desktop_info.desktop_etguid); // 自动下注 int bet_chip = 2000; int left_chip = CoActor.Def.PropGold.get(); if (left_chip < bet_chip) { bet_chip = left_chip; } left_chip -= bet_chip; CoPlayer.CoActor.Def.PropGold.set(left_chip); // Step2:进入桌子并获取桌子初始化信息 var grain_desktop = grain.GF.GetGrain <ICellDesktop>(new Guid(desktop_info.desktop_etguid)); DesktopData desktop_data = await grain_desktop.s2sPlayerEnter(request_enter, CoPlayer.exportEtPlayerMirror()); IsEntering = false; DesktopEtGuid = desktop_data.desktop_cfg_data.desktop_etguid; DesktopNotify desktop_notify; desktop_notify.id = DesktopNotifyId.DesktopInit; desktop_notify.data = EbTool.protobufSerialize <DesktopData>(desktop_data); MethodData notify_data = new MethodData(); notify_data.method_id = MethodType.s2cPlayerDesktopNotify; notify_data.param1 = EbTool.protobufSerialize <DesktopNotify>(desktop_notify); var grain_player = grain.GF.GetGrain <ICellPlayer>(new Guid(Entity.Guid)); grain_player.s2sNotify(notify_data); }
public void Optimize(ArrayList list, MethodData md) { X86Code.Optimize(list); bool bx = true; Hashtable locals = new Hashtable(); int max = 0; string target = null; for (int i = 0; i < list.Count; i++) { X86Code x = list[i] as X86Code; if (x == null || x.ignore) { continue; } if (x.Mnemonic == "int" || x.Operand1 == "bx") { bx = false; } int p1a = x.Operand1.IndexOf("[ss:bp-"), p1b = x.Operand1.LastIndexOf(']'); if (0 <= p1a && p1a < p1b) { string var = x.Operand1.Substring(p1a + 1, p1b - p1a - 1); int v = !locals.Contains(var) ? 1 : ((int)locals[var]) + 1; locals[var] = v; if (max < v) { max = v; target = var; } } int p2a = x.Operand2.IndexOf("[ss:bp-"), p2b = x.Operand2.LastIndexOf(']'); if (0 <= p2a && p2a < p2b) { string var = x.Operand2.Substring(p2a + 1, p2b - p2a - 1); int v = !locals.Contains(var) ? 1 : ((int)locals[var]) + 1; locals[var] = v; if (max < v) { max = v; target = var; } } } if (bx && target != null) { for (int i = 0; i < list.Count; i++) { X86Code x = list[i] as X86Code; if (x == null || x.ignore) { continue; } string op1 = x.Operand1, op2 = x.Operand2; int p1 = op1.IndexOf(target), p2 = op2.IndexOf(target); if (p1 >= 0) { op1 = "bx"; } if (p2 >= 0) { op2 = "bx"; } if (p1 < 0 && p2 < 0) { continue; } x.Ignore(); X86Code xx = new X86Code(x.Mnemonic, op1, op2); xx.Notes = "[optimize] add"; list.Insert(i + 1, xx); } if (md.LocalVars != null && md.LocalVars.Count == 1 && target.StartsWith("ss:bp-")) { for (int i = 0; i < list.Count; i++) { X86Code x = list[i] as X86Code; if (x == null || x.ignore) { continue; } if (x.Mnemonic == "sub" && x.Operand1 == "sp") { x.Ignore(); break; } } for (int i = list.Count - 1; i >= 0; i--) { X86Code x = list[i] as X86Code; if (x == null || x.ignore) { continue; } if (x.Mnemonic == "mov" && x.Operand1 == "sp") { x.Ignore(); break; } } } } X86Code.Optimize(list); if (md.LocalVars != null || md.ParamCount > 0 || !bx) { X86Code xb1 = new X86Code("push", "bx"), xb2 = new X86Code("pop", "bx"); xb1.Notes = xb2.Notes = "[optimize] add"; list.Insert(0, xb1); for (int i = 0; i < list.Count; i++) { X86Code x = list[i] as X86Code; if (x == null || x.ignore) { continue; } if (x.Mnemonic == "ret") { list.Insert(i, xb2); i++; } } } }
public async Task TestStringRef(MethodData method) { await method.Execute().ConfigureAwait(false); Assert.True(SomeOutParameters.StringRefTested); }
private static bool IsBetterThan(Expression[] args, MethodData left, MethodData right) { bool flag = false; for (int index = 0; index < args.Length; ++index) { int num = CompareConversions( args[index].Type, left.Parameters[index].ParameterType, right.Parameters[index].ParameterType); if (num < 0) return false; if (num > 0) flag = true; } return flag; }
//------------------------------------------------------------------------- public async Task <MethodData> c2sPlayerFriendRequest(MethodData method_data) { MethodData result = new MethodData(); result.method_id = MethodType.None; var playerfriend_request = EbTool.protobufDeserialize <PlayerFriendRequest>(method_data.param1); switch (playerfriend_request.id) { case PlayerFriendRequestId.GetPlayerInfoFriend: // 请求获取好友玩家信息 { var player_etguid = EbTool.protobufDeserialize <string>(playerfriend_request.data); var grain = Entity.getUserData <GrainCellPlayer>(); var grain_playerservice = grain.GF.GetGrain <ICellPlayerService>(0); var player_info = await grain_playerservice.getPlayerInfoFriend(player_etguid); PlayerFriendResponse playerfriend_response; playerfriend_response.id = PlayerFriendResponseId.GetPlayerInfoFriend; playerfriend_response.data = EbTool.protobufSerialize <PlayerInfoFriend>(player_info); result.method_id = MethodType.s2cPlayerFriendResponse; result.param1 = EbTool.protobufSerialize <PlayerFriendResponse>(playerfriend_response); } break; case PlayerFriendRequestId.RequestAddFriend: // 请求添加为好友 { var et_player_guid = EbTool.protobufDeserialize <string>(playerfriend_request.data); ProtocolResult r = ProtocolResult.Failed; // 不可以添加自己为好友 if (et_player_guid == Entity.Guid) { r = ProtocolResult.FriendIsMe; goto End; } // 不可以重复添加好友 PlayerInfo current_friend = null; Dictionary <string, PlayerInfo> map_friend = Def.mPropMapFriend.get(); if (map_friend.TryGetValue(et_player_guid, out current_friend)) { r = ProtocolResult.FriendExistFriend; goto End; } // 请求添加好友。由于加好友是双向的,需要告知被加的好友 var grain = Entity.getUserData <GrainCellPlayer>(); var grain_playerproxy = grain.GF.GetGrain <ICellPlayerProxy>(new Guid(et_player_guid)); grain_playerproxy.s2sRequestAddFriend(Entity.Guid); r = ProtocolResult.Success; End: PlayerFriendResponse playerfriend_response; playerfriend_response.id = PlayerFriendResponseId.RequestAddFriend; playerfriend_response.data = EbTool.protobufSerialize <ProtocolResult>(r); result.method_id = MethodType.s2cPlayerFriendResponse; result.param1 = EbTool.protobufSerialize <PlayerFriendResponse>(playerfriend_response); } break; case PlayerFriendRequestId.AgreeAddFriend: // 请求是否同意添加好友 { var addfriend_agree = EbTool.protobufDeserialize <AddFriendAgree>(playerfriend_request.data); ProtocolResult r = ProtocolResult.Failed; PlayerInfo friend_item = null; Dictionary <string, PlayerInfo> map_friend = Def.mPropMapFriend.get(); var grain = Entity.getUserData <GrainCellPlayer>(); var grain_playerservice = grain.GF.GetGrain <ICellPlayerService>(0); PlayerInfo player_info = await grain_playerservice.getPlayerInfo(addfriend_agree.player_etguid); if (player_info != null && !string.IsNullOrEmpty(player_info.player_etguid)) { //friend_item = new FriendItem(); //friend_item.et_guid = player_info.player_etguid; //friend_item.nick_name = player_info.nick_name; //friend_item.icon = player_info.icon; //friend_item.level = player_info.level; //friend_item.exp = player_info.exp; //friend_item.chip = player_info.chip; //friend_item.gold = player_info.gold; //friend_item.individual_signature = player_info.individual_signature;// 个性签名 //friend_item.ip_address = player_info.ip_address;// ip所在地 //friend_item.is_vip = false;// 是否是VIP //friend_item.vip_level = 0;// VIP等级 //friend_item.vip_point = 0;// VIP积分 //friend_item.status = FriendOnlineStatus.Offline;// 好友在线状态 //friend_item.last_online_dt = DateTime.Now;// 好友最后在线时间 //friend_item.desktop_etguid = "";// 如果好友正在牌桌中,该牌桌的EtGuid r = ProtocolResult.Success; if (addfriend_agree.agree) { // 好友数据添加到好友列表 map_friend[addfriend_agree.player_etguid] = friend_item; // 通知本地客户端添加好友 PlayerFriendNotify friend_notify; friend_notify.id = PlayerFriendNotifyId.AddFriend; friend_notify.data = EbTool.protobufSerialize(friend_item); _onFriendNotify(friend_notify); // 由于加好友是双向的,需要告知被加的好友 var grain_playerproxy = grain.GF.GetGrain <ICellPlayerProxy>(new Guid(addfriend_agree.player_etguid)); grain_playerproxy.s2sResponseAddFriend(Entity.Guid, addfriend_agree.agree); } } End: PlayerFriendResponse playerfriend_response; playerfriend_response.id = PlayerFriendResponseId.AgreeAddFriend; playerfriend_response.data = EbTool.protobufSerialize <ProtocolResult>(r); result.method_id = MethodType.s2cPlayerFriendResponse; result.param1 = EbTool.protobufSerialize <PlayerFriendResponse>(playerfriend_response); } break; case PlayerFriendRequestId.DeleteFriend: // 请求删除好友 { var et_player_guid = EbTool.protobufDeserialize <string>(playerfriend_request.data); ProtocolResult r = ProtocolResult.Failed; PlayerInfo current_friend = null; Dictionary <string, PlayerInfo> map_friend = Def.mPropMapFriend.get(); if (map_friend.TryGetValue(et_player_guid, out current_friend)) { map_friend.Remove(current_friend.player_etguid); r = ProtocolResult.Success; } else { goto End; } // 通知本地客户端删除好友 PlayerFriendNotify friend_notify; friend_notify.id = PlayerFriendNotifyId.DeleteFriend; friend_notify.data = EbTool.protobufSerialize(et_player_guid); _onFriendNotify(friend_notify); // 告知被删的好友 var grain = Entity.getUserData <GrainCellPlayer>(); var grain_playerproxy = grain.GF.GetGrain <ICellPlayerProxy>(new Guid(et_player_guid)); grain_playerproxy.s2sDeleteFriend(Entity.Guid); End: PlayerFriendResponse playerfriend_response; playerfriend_response.id = PlayerFriendResponseId.DeleteFriend; playerfriend_response.data = EbTool.protobufSerialize <ProtocolResult>(r); result.method_id = MethodType.s2cPlayerFriendResponse; result.param1 = EbTool.protobufSerialize <PlayerFriendResponse>(playerfriend_response); } break; case PlayerFriendRequestId.FindFriend: // 请求查找好友 { var find_info = EbTool.protobufDeserialize <string>(playerfriend_request.data); var grain = Entity.getUserData <GrainCellPlayer>(); var grain_playerservice = grain.GF.GetGrain <ICellPlayerService>(0); var list_playerinfo = await grain_playerservice.findPlayers(find_info); //List<FriendItem> list_frienditem = new List<FriendItem>(); //foreach (var i in list_playerinfo) //{ // PlayerInfo player_info = i; // if (string.IsNullOrEmpty(player_info.player_etguid)) continue; // FriendItem friend_item = new FriendItem(); // friend_item.et_guid = player_info.player_etguid; // friend_item.nick_name = player_info.nick_name; // friend_item.icon = player_info.icon; // friend_item.level = player_info.level; // friend_item.exp = player_info.exp; // friend_item.chip = player_info.chip; // friend_item.gold = player_info.gold; // friend_item.individual_signature = player_info.individual_signature;// 个性签名 // friend_item.ip_address = player_info.ip_address;// ip所在地 // friend_item.is_vip = false;// 是否是VIP // friend_item.vip_level = 0;// VIP等级 // friend_item.vip_point = 0;// VIP积分 // friend_item.status = FriendOnlineStatus.Offline;// 好友在线状态 // friend_item.last_online_dt = DateTime.Now;// 好友最后在线时间 // friend_item.desktop_etguid = "";// 如果好友正在牌桌中,该牌桌的EtGuid // list_frienditem.Add(friend_item); //} PlayerFriendResponse playerfriend_response; playerfriend_response.id = PlayerFriendResponseId.FindFriend; playerfriend_response.data = EbTool.protobufSerialize <List <PlayerInfo> >(list_playerinfo); result.method_id = MethodType.s2cPlayerFriendResponse; result.param1 = EbTool.protobufSerialize <PlayerFriendResponse>(playerfriend_response); } break; default: break; } return(result); }
private bool IsApplicable(MethodData method, Expression[] args) { if (method.Parameters.Length != args.Length) return false; Expression[] promotedArgs = new Expression[args.Length]; for (int i = 0; i < args.Length; i++) { ParameterInfo pi = method.Parameters[i]; if (pi.IsOut) return false; Expression promoted = PromoteExpression(args[i], pi.ParameterType, false); if (promoted == null) return false; promotedArgs[i] = promoted; } method.Args = promotedArgs; return true; }
public object[] ConvertNative(MethodData md) { Stack st1 = new Stack(); foreach (ILCode il in md.ILCodes) { st1.Push(il); } this.lastRet = null; Stack st2 = new Stack(); while (st1.Count > 0) { ILCode il = st1.Pop() as ILCode; if (il.OpCode.Name == "ret" && this.lastRet == null) { this.lastRet = il; } else if (il.OpCode.Name == "pop" && st1.Count > 0) { ILCode il2 = st1.Peek() as ILCode; if (il2.OpCode.Name == "newobj") { TableBase tb = this.pedata.idxm.GetTable((int)il2.Operand); MethodData tb_md = tb.Tag as MethodData; if (tb_md.Name == "[I8086]I8086.Inline::.ctor" && st1.Count > 1) { st1.Pop(); ILCode il3 = st1.Peek() as ILCode; if (il3 != null && il3.OpCode.Name == "ldstr") { st1.Pop(); X86Codes nc = new X86Codes(); nc.Address = il3.Address; nc.IsBrTarget = il3.IsBrTarget; nc.Comment = "[native] inline"; nc.Codes.Add(X86Code.Parse(this.hashUS[((int)il3.Operand) & 0xffffff] as string)); st2.Push(nc); continue; } st1.Push(il2); } } } if (il.OpCode.Name == "call") { TableBase tb = this.pedata.idxm.GetTable((int)il.Operand); MethodData tb_md = tb.Tag as MethodData; string name = tb_md.Name; if (name.StartsWith("[I8086]I8086.Registers::set_")) { string reg = name.Substring(name.Length - 2, 2).ToLower(); if (st1.Count > 0 && !name.EndsWith("S")) { ILCode il2 = st1.Peek() as ILCode; string mne = il2.OpCode.Name; int nOp = Util.GetOperandValue(il2); if (mne.StartsWith("ldc.i4")) { st1.Pop(); X86Codes nc = new X86Codes(); nc.Address = il2.Address; nc.IsBrTarget = il2.IsBrTarget; nc.Comment = "[native] set register"; nc.Codes.Add(new X86Code("mov", reg, nOp.ToString())); st2.Push(nc); continue; } else if (mne.StartsWith("ldloc")) { st1.Pop(); X86Codes nc = new X86Codes(); nc.Address = il2.Address; nc.IsBrTarget = il2.IsBrTarget; nc.Comment = "[native] set register"; nc.Codes.Add(new X86Code("mov", reg, string.Format("[ss:bp-{0}]", (nOp + 1) * 2))); st2.Push(nc); continue; } else if (mne.StartsWith("ldarg")) { st1.Pop(); X86Codes nc = new X86Codes(); nc.Address = il2.Address; nc.IsBrTarget = il2.IsBrTarget; nc.Comment = "[native] set register"; nc.Codes.Add(new X86Code("mov", reg, string.Format("[ss:bp+{0}]", Util.GetArgPos(md, nOp, this.optimize)))); st2.Push(nc); continue; } } if (name.EndsWith("X") || name.EndsWith("I") || name.EndsWith("S")) { X86Codes nc = new X86Codes(); nc.Address = il.Address; nc.IsBrTarget = il.IsBrTarget; nc.Comment = "[native] set register"; nc.Codes.Add(new X86Code("pop", reg)); st2.Push(nc); continue; } } else if (name.StartsWith("[I8086]I8086.Registers::get_")) { X86Codes nc = new X86Codes(); nc.Address = il.Address; nc.IsBrTarget = il.IsBrTarget; nc.Comment = "[native] get register"; nc.Codes.Add(new X86Code("push", name.Substring(name.Length - 2, 2).ToLower())); st2.Push(nc); continue; } else if (name == "[I8086]I8086.IO::In" && st1.Count > 0) { ILCode il2 = st1.Peek() as ILCode; string mne = il2.OpCode.Name; int nOp = Util.GetOperandValue(il2); X86Codes nc = new X86Codes(); nc.Comment = "[native] in"; if (mne.StartsWith("ldc.i4")) { st1.Pop(); nc.Address = il2.Address; nc.IsBrTarget = il2.IsBrTarget; nc.Codes.Add(new X86Code("in", "al", nOp.ToString())); } else { nc.Address = il.Address; nc.IsBrTarget = il.IsBrTarget; nc.Codes.Add(new X86Code("pop", "dx")); nc.Codes.Add(new X86Code("in", "al", "dx")); } nc.Codes.Add(new X86Code("mov", "ah", "0")); nc.Codes.Add(new X86Code("push", "ax")); st2.Push(nc); continue; } else if (name == "[I8086]I8086.IO::Out") { X86Codes nc = new X86Codes(); nc.Address = il.Address; nc.IsBrTarget = il.IsBrTarget; nc.Comment = "[native] out"; nc.Codes.Add(new X86Code("pop", "ax")); nc.Codes.Add(new X86Code("pop", "dx")); nc.Codes.Add(new X86Code("out", "dx", "al")); st2.Push(nc); continue; } else if (name == "[I8086]I8086.StringPtr::Get") { continue; } else if (name.StartsWith("[I8086]I8086.Flags::get_")) { string mne = "jz"; int p = name.IndexOf('_') + 1; switch (name.Substring(p, name.Length - p)) { case "NZ": case "NE": mne = "jnz"; break; case "C": mne = "jc"; break; case "NC": mne = "jnc"; break; } X86Codes nc = new X86Codes(); nc.Address = il.Address; nc.IsBrTarget = il.IsBrTarget; nc.Comment = "[native] get flag"; nc.Codes.Add(new X86Code(mne, string.Format("NM_{0:X8}", this.number))); nc.Codes.Add(new X86Code("xor", "ax", "ax")); nc.Codes.Add(new X86Code("jmp", string.Format("NM_{0:X8}", this.number + 1))); nc.Codes.Add(new X86Code(string.Format("NM_{0:X8}", this.number), true, "[native] get flag internal", "mov", "ax", "1")); nc.Codes.Add(new X86Code(string.Format("NM_{0:X8}", this.number + 1), true, "[native] get flag internal", "push", "ax")); st2.Push(nc); this.number += 2; continue; } } st2.Push(il); } return(st2.ToArray()); }
public new bool ShouldSelect(MethodData method, ISelectionContext context) { return base.ShouldSelect(method, context); }
public static void LogicalDiskSample() { //// Управляющий класс ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk"); // true - если объекты, возвращенные от WMI, должны содержать // измененные сведения; diskClass.Options.UseAmendedQualifiers = true; //------- описание класса // Коллекция объектов QualifierData QualifierDataCollection qualifierCollection = diskClass.Qualifiers; // QualifierData - содержит сведения относительно WMI описателя foreach (QualifierData q in qualifierCollection) { Console.WriteLine(q.Name + " = " + q.Value); } Console.WriteLine(new string('-', 45)); //------------------------------------------------ //------- Доступные методы класса Console.WriteLine("\n Доступные методы класса... "); MethodDataCollection diskMethods = diskClass.Methods; foreach (MethodData method in diskMethods) { Console.WriteLine("Метод = " + method.Name); } Console.WriteLine(new string('-', 45)); //------------------------------------------------ // то же, но через нумератор //MethodDataCollection.MethodDataEnumerator diskEnumerator = // diskClass.Methods.GetEnumerator(); //while (diskEnumerator.MoveNext()) //{ // MethodData method = diskEnumerator.Current; // Console.WriteLine("Method = " + method.Name); //} //Console.WriteLine(new string('-', 45)); //------------------------------------------------- //------- Свойства класса ManagementObject diskС = new ManagementObject("Win32_LogicalDisk.DeviceID='C:'"); PropertyDataCollection.PropertyDataEnumerator propertyEnumerator = diskС.Properties.GetEnumerator(); while (propertyEnumerator.MoveNext()) { PropertyData p = (PropertyData)propertyEnumerator.Current; Console.WriteLine("Найденое свойство: " + p.Name); } Console.WriteLine(new string('-', 45)); //------------------------------------------------ //------- Экземпляры класса Console.WriteLine("\n Теперь отыщем все диски... "); // Получим коллекцию всех экземпляров класса ManagementObjectCollection disks = diskClass.GetInstances(); // Перечислитель коллекции ManagementObjectCollection.ManagementObjectEnumerator disksEnumerator = disks.GetEnumerator(); while (disksEnumerator.MoveNext()) { ManagementObject disk = (ManagementObject)disksEnumerator.Current; Console.WriteLine("Найден диск: " + disk["deviceid"]); Console.WriteLine("Размер: " + disk["Size"]); } Console.WriteLine(new string('-', 45)); //------------------------------------------------ // Получение сведений о методе класса MethodData m = diskClass.Methods["SetPowerState"]; Console.WriteLine("Name: " + m.Name); Console.WriteLine("Origin: " + m.Origin); // аргументы ManagementBaseObject inParams = m.InParameters; foreach (PropertyData pdata in inParams.Properties) { Console.WriteLine(); Console.WriteLine("InParam_Name: " + pdata.Name); Console.WriteLine("InParam_Type: " + pdata.Type); } // Возвращаемые значения ManagementBaseObject outParams = m.OutParameters; foreach (PropertyData pdata in outParams.Properties) { Console.WriteLine(); Console.WriteLine("OutParam_Name: " + pdata.Name); Console.WriteLine("OutParam_Type: " + pdata.Type); } }
public void AddNewMethod (MethodBase mb, int il_size) { if (methods == null) methods = new ArrayList (); MethodData md = new MethodData (mb, il_size); md.Checked = true; methods.Add (md); }
private bool StaticCanNotInline(MethodData methodData) { if (InlineExplicitOnly && !methodData.HasAggressiveInliningAttribute) { return(true); } if (methodData.HasDoNotInlineAttribute) { return(true); } if (methodData.IsMethodImplementationReplaced) { return(true); } if (methodData.HasProtectedRegions) { return(true); } if (methodData.HasMethodPointerReferenced) { return(true); } var method = methodData.Method; if (method.IsVirtual && !methodData.IsDevirtualized) { return(true); } if (methodData.DoNotInline) { return(true); } if (method.DeclaringType.IsValueType && method.IsVirtual && !method.IsConstructor && !method.IsStatic) { return(true); } var returnType = methodData.Method.Signature.ReturnType; // FIXME: Add rational if (!MosaTypeLayout.CanFitInRegister(returnType) && !returnType.IsUI8 && !returnType.IsR8) { return(true); } // FUTURE: Don't hardcode namepsace if (((method.MethodAttributes & MosaMethodAttributes.Public) == MosaMethodAttributes.Public) && method.DeclaringType.BaseType != null && method.DeclaringType.BaseType.Namespace == "Mosa.UnitTests") { return(true); } return(false); }