public ObservableCollection <StaffAllResponseModel> All() { var collection = new ObservableCollection <StaffAllResponseModel>(); var rowId = 0; using (var db = new FrameContext()) { var list = _staffService.GetAll(db, false, a => a.Id) .Select(a => new { a, a.DeptForeign }).ToList(); list.ForEach(staff => { collection.Add(GenerateStaffAllResponseModel(staff.a, staff.DeptForeign, ++rowId)); }); } return(collection); }
public VariableMultimap(FrameContext context) { map = new Dictionary <string, Dictionary <Type, object> >(); for (int i = 0; i < context.LocalNames.Count; ++i) { var name = context.LocalNames[i]; var variable = context.Locals[i]; // TODO: Switch to handle null with NoneType if (variable != null) { Add(name, variable); } } }
public async Task CallDotNetOptionalsExplicitOutOfOrder() { FrameContext runContext = await runProgram( "a = obj.Kwargs(second=20, first=2)\n", new Dictionary <string, object>() { { "obj", new ReflectIntoPython(1337, "Kwargs test!") } }, 1); var variables = runContext.DumpVariables(); Assert.That(variables.ContainsKey("a")); var a = (int)variables["a"]; Assert.That(a, Is.EqualTo(202)); }
public FrameContext frame() { FrameContext _localctx = new FrameContext(_ctx, State); EnterRule(_localctx, 2, RULE_frame); int _la; try { EnterOuterAlt(_localctx, 1); { State = 17; header(); State = 19; _errHandler.Sync(this); switch (Interpreter.AdaptivePredict(_input, 1, _ctx)) { case 1: { State = 18; comment(); } break; } State = 22; _errHandler.Sync(this); _la = _input.La(1); do { { { State = 21; line(); } } State = 24; _errHandler.Sync(this); _la = _input.La(1); } while (_la == ELEMENT); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.ReportError(this, re); _errHandler.Recover(this, re); } finally { ExitRule(); } return(_localctx); }
public void Setup() { var serviceContext = new ServiceContext { HttpParserFactory = f => new HttpParser <FrameAdapter>(), ServerOptions = new KestrelServerOptions() }; var frameContext = new FrameContext { ServiceContext = serviceContext, ConnectionInformation = new MockConnectionInformation { PipeFactory = new PipeFactory() } }; var frame = new Frame <object>(application: null, frameContext: frameContext); frame.Reset(); _responseHeadersDirect = (FrameResponseHeaders)frame.ResponseHeaders; var context = new DefaultHttpContext(frame); _response = new DefaultHttpResponse(context); switch (Type) { case BenchmarkTypes.ContentLengthNumeric: ContentLengthNumeric(1); break; case BenchmarkTypes.ContentLengthString: ContentLengthString(1); break; case BenchmarkTypes.Plaintext: Plaintext(1); break; case BenchmarkTypes.Common: Common(1); break; case BenchmarkTypes.Unknown: Unknown(1); break; } }
public TestInput() { var trace = new KestrelTrace(new TestKestrelTrace()); var ltp = new LoggingThreadPool(trace); var context = new FrameContext() { DateHeaderValueManager = new DateHeaderValueManager(), ServerAddress = ServerAddress.FromUrl("http://localhost:5000"), ConnectionControl = this, FrameControl = this }; FrameContext = new Frame <object>(null, context); _memoryPool = new MemoryPool(); FrameContext.SocketInput = new SocketInput(_memoryPool, ltp); }
/// <summary> /// Schedule a new program to run that requires certain arguments. This is exposed for other scripts to pass /// in function calls that need to be spun up as independent coroutines. /// </summary> /// <param name="program">The code to schedule. The is treated like a function call with zero or more arguments.</param> /// <param name="args">The arguments that need to be seeded to the the code to run.</param> /// <returns></returns> public TaskEventRecord Schedule(CodeObject program, FrameContext context, params object[] args) { if (args.Length != program.ArgVarNames.Count) { throw new Exception("The given code object requires " + program.ArgCount + " arguments but only " + args.Length + " arguments were given"); } var scheduleState = PrepareFrameContext(program); for (int argIdx = 0; argIdx < args.Length; ++argIdx) { scheduleState.Frame.SetVariable(program.ArgVarNames[argIdx], args[argIdx]); } unblocked.Add(scheduleState); return(scheduleState.SubmitterReceipt); }
/// <summary> /// Creates a new frame context as a child of the super context. If the super context is null, then this /// context is considered a root context. If it is defined, this context is considered a subcontext. /// Subcontexts come up when defining functions in functions and then scheduling them out. /// </summary> /// <param name="newProgram"></param> /// <param name="superContext"></param> /// <returns></returns> private ScheduledTaskRecord PrepareFrameContext(CodeObject newProgram, FrameContext superContext) { var newFrameStack = new Stack <Frame>(); var rootFrame = new Frame(newProgram); foreach (string name in newProgram.VarNames) { rootFrame.AddLocal(name, null); } newFrameStack.Push(rootFrame); FrameContext subContext = superContext != null?superContext.CreateSubcontext(newFrameStack) : new FrameContext(newFrameStack); var initialContinuation = new InitialScheduledContinuation(this.interpreter, subContext); return(new ScheduledTaskRecord(subContext, initialContinuation, new TaskEventRecord(subContext))); }
public async Task CallGenericExtensionMethodNoArgs() { FrameContext runContext = await runProgram( "obj = ReflectIntoPython(1337, 'Generic test!')\n" + "a = obj.AGenericExtensionMethodNoArgs(ReflectIntoPython)\n", new Dictionary <string, object>() { { "ReflectIntoPython", new PyDotNetClassProxy(typeof(ReflectIntoPython)) } }, 1); var variables = runContext.DumpVariables(); Assert.That(variables.ContainsKey("a")); var aInstance = (bool)variables["a"]; Assert.That(aInstance, Is.True); }
public async Task CallExtensionMethodWithArgs() { FrameContext runContext = await runProgram( "obj = ReflectIntoPython(1337, 'Generic test!')\n" + "a = obj.AnExtensionMethodWithArgs(1)\n", new Dictionary <string, object>() { { "ReflectIntoPython", new PyDotNetClassProxy(typeof(ReflectIntoPython)) } }, 1); var variables = runContext.DumpVariables(); Assert.That(variables.ContainsKey("a")); var a = (int)variables["a"]; Assert.That(a, Is.EqualTo(1338)); }
public async Task TryUnhandledFinally() { FrameContext runContext = await runProgram( "a = 0\n" + "try:\n" + " raise Exception('Hello, World!')\n" + "finally:\n" + " a = 1\n", new Dictionary <string, object>(), 1, false); Assert.NotNull(runContext.CurrentException); Assert.That(runContext.CurrentException.__dict__["message"], Is.EqualTo("Hello, World!")); var variables = new VariableMultimap(runContext); var a = (PyInteger)variables.Get("a"); Assert.That(a, Is.EqualTo(PyInteger.Create(1))); }
static void DumpDatastack(FrameContext tasklet) { if (tasklet.DataStack.Count > 0) { Console.WriteLine("Data stack:"); int i = 0; foreach (var dataStackObj in tasklet.DataStack) { Console.WriteLine(" " + i + " " + dataStackObj); } } else { Console.WriteLine("Data stack is empty"); } Console.WriteLine("Code cursor = " + tasklet.Cursor); }
/// <summary> /// 删除操作员信息 /// </summary> /// <returns></returns> public CommandResult <Staff> Delete(int staffId) { var result = new CommandResult <Staff>(); if (!Exist(a => a.Id == staffId)) { result.Message = "操作员信息在系统中已不存在"; } else if (Exist(a => a.Id == staffId && (a.LogonName == null || a.LogonName == ""))) { result.Message = "该员工已不是操作员"; } else { using (var db = new FrameContext()) { using (var scope = new TransactionScope()) { var relationships = _staffRoleRelationshipsService.FindList(db, a => a.StaffId == staffId).ToList(); foreach (var relationship in relationships) { _staffRoleRelationshipsService.Delete(db, relationship); } var entity = BaseService.Find(db, a => a.Id == staffId); entity.LogonId = null; entity.LogonName = null; entity.LogonPwd = null; if (!BaseService.Update(db, entity)) { result.Message = "未知原因"; } else { result.ResultStatus = ResultStatus.Success; result.Message = "操作员删除成功"; result.Data = entity; } scope.Complete(); } } } return(result); }
/// <summary> /// Implements the dir() command used to dump methods and properties of this PyObject. /// </summary> /// <param name="o">The object to inspect</param> /// <returns>A PyList of the names of the methods and properties of this PyObject.</returns> //public static async Task<PyList> dir(IInterpreter interpreter, FrameContext context, PyObject o) public static async Task <object> dir(IInterpreter interpreter, FrameContext context, PyObject o) { // TODO: Figure out how to switch to Task<PyList> signature without everything hanging. var internalList = new List <object>(); foreach (var name in o.__dict__.Keys) { internalList.Add(PyString.Create(name)); } // Alphabetize them. It's how Python does it and it is quite useful for scanning through the output anyways. internalList.Sort((a, b) => a.ToString().CompareTo(b.ToString())); var retList = (PyList)await PyListClass.Instance.Call(interpreter, context, new object[0]); retList.SetList(internalList); return(retList); }
public CommandResult <Dept> GetModel(int deptId) { var result = new CommandResult <Dept>(); using (var db = new FrameContext()) { if (!Exist(a => a.Id == deptId)) { result.Message = "部门不存在"; } else { result.Data = BaseService.Find(db, a => a.Id == deptId); result.ResultStatus = ResultStatus.Success; } } return(result); }
public FrameFeatureCollection() { var serviceContext = new ServiceContext { HttpParserFactory = _ => NullParser <FrameAdapter> .Instance, ServerOptions = new KestrelServerOptions() }; var frameContext = new FrameContext { ServiceContext = serviceContext, ConnectionInformation = new MockConnectionInformation { PipeFactory = new PipeFactory() } }; _frame = new Frame <object>(application: null, frameContext: frameContext); }
public PyModuleSpec find_spec(FrameContext context, string name, string import_path, PyModule target) { var splitNames = name.Split('.'); foreach (var moduleRoot in moduleRootPaths) { var foundPath = findModule(splitNames, moduleRoot); if (foundPath != null) { var spec = PyModuleSpec.Create(name, loader, "", null); spec.LoaderState = foundPath; return(spec); } } // Fall-through: Module not found. Return null according to specifications. return(null); }
public async Task CallGenericMethod() { FrameContext runContext = await runProgram( "obj = ReflectIntoPython(1337, 'Generic test!')\n" + "a = obj.GenericMethod(ReflectIntoPython, obj)\n", new Dictionary <string, object>() { { "ReflectIntoPython", new PyDotNetClassProxy(typeof(ReflectIntoPython)) } }, 1); var variables = runContext.DumpVariables(); Assert.That(variables.ContainsKey("a")); var aInstance = (ReflectIntoPython)variables["a"]; Assert.That(aInstance.AnInteger, Is.EqualTo(1337)); Assert.That(aInstance.AString, Is.EqualTo("Generic test!")); }
public async Task ReturningEventDotNet() { string failNote = "Attempted to bind a callable to an event that requires a return type. We don't support this type of binding. " + "All our callables have to be async, and that meddles with signature of basic return values. Why are you using an event with " + "a return type anyways?"; FrameContext runContext = await runProgram ("obj = ReflectIntoPython(1337, 'I did it!')\n" + "obj.ReturnIntTakeIntEvent += obj.SubscribeReturnInteger\n" + "obj.TriggerReturningIntEvent(111)\n" + "obj.ReturnIntTakeIntEvent -= obj.SubscribeReturnInteger\n" + "a = obj.AnInteger\n", new Dictionary <string, object>() { { "ReflectIntoPython", new WrappedCodeObject(typeof(ReflectIntoPython).GetConstructors()) } }, 1, false); Assert.NotNull(runContext.EscapedDotNetException); Assert.That(runContext.EscapedDotNetException.Message, Is.EqualTo(failNote)); }
/// <summary> /// This is more of a formality since the injected module loader already has the module loaded, but this gives us conformity with /// the module importing system. /// </summary> /// <param name="spec">The module spec we will load.</param> /// <returns>The loaded asset... which might be a PyModule wrapper if this is a namespace. Otherwise, the asset itself.</returns> public async Task <object> Load(IInterpreter interpreter, FrameContext context, PyModuleSpec spec) { // Don't get too fixated on this being a module at the end of the day. var module = PyModule.Create(spec.Name); var clrContext = (ClrContext)spec.LoaderState; // TODO: [CLR - OPTIMIZE GETATTR] Create a .NET PyModule interface overridding __getattr__ to do these lookups instead of stuffing the // module with everything. Tackle that once this has settled down a bit and we know exactly what we're trying to do. // Some LINQ magic could probably do this but I think I want to be able to step through it. bool foundAny = false; foreach (var assembly in clrContext.AddedReferences) { foreach (var type in assembly.GetTypes()) { if (type.Namespace == spec.Name) { if (!module.__dict__.ContainsKey(type.Name)) { foundAny = true; module.__dict__.Add(type.Name, type); } } } } // Maybe it's not a namespace! if (!foundAny) { foreach (var assembly in clrContext.AddedReferences) { foreach (var type in assembly.GetTypes()) { if (type.Name == spec.Name) { return(type); } } } } return(module); }
public CommandResult <Staff> Add(StaffAddRequestModel requestModel) { var result = new CommandResult <Staff>(); if (Exist(a => a.Code == requestModel.Code)) { result.Message = $"该员工编号“{requestModel.Code}”在系统中已存在"; } else if (Exist(a => a.Name == requestModel.Name)) { result.Message = $"该姓名“{requestModel.Name}”在系统中已存在"; } else { var entity = new Staff { Code = requestModel.Code, DeptId = requestModel.DeptId, Name = requestModel.Name, Sex = requestModel.Sex, Birth = requestModel.Birth, InTime = requestModel.InTime, Tel = requestModel.Tel, Add = requestModel.Add, State = requestModel.State, Oper = requestModel.Oper, Supper = false }; using (var db = new FrameContext()) { if (!BaseService.Add(db, entity)) { result.Message = "未知原因"; } else { result.ResultStatus = ResultStatus.Success; result.Message = "员工信息添加成功"; result.Data = entity; } } } return(result); }
public void Setup() { var serviceContext = new ServiceContext { HttpParserFactory = _ => NullParser <FrameAdapter> .Instance, ServerOptions = new KestrelServerOptions() }; var frameContext = new FrameContext { ServiceContext = serviceContext, ConnectionInformation = new MockConnectionInformation { PipeFactory = new PipeFactory() }, TimeoutControl = new MockTimeoutControl() }; _frame = new Frame <object>(application: null, frameContext: frameContext); }
// TODO: Make every part of this much easier. Creating the objects properly will need to be simplified. One-step // construction with passed-in values will greatly help. This could be done with a factory, but we should investigate // if we can just use the basic type constructors in some way first. public async Task <PyTuple> get_player_pos_wrapper(IInterpreter interpreter, FrameContext context) { PyFloat f1 = (PyFloat)await PyFloatClass.Instance.Call(interpreter, context, new object[0]); f1.number = Decimal.Parse(playerXLabel.Text); PyFloat f2 = (PyFloat)await PyFloatClass.Instance.Call(interpreter, context, new object[0]); f2.number = Decimal.Parse(playerYLabel.Text); var tuples = new PyObject[2] { f1, f2 }; var new_pytup = (PyTuple)await PyTupleClass.Instance.Call(interpreter, context, new object[0]); new_pytup.Values = tuples; return(new_pytup); }
public void TryUnhandledFinally() { FrameContext runContext = null; Assert.Throws <EscapedPyException>( () => { runProgram( "a = 0\n" + "try:\n" + " raise Exception('Hello, World!')\n" + "finally:\n" + " a = 1\n", new Dictionary <string, object>(), 1, out runContext); }, "Hello, World!"); var variables = new VariableMultimap(runContext); var a = (PyInteger)variables.Get("a"); Assert.That(a, Is.EqualTo(PyInteger.Create(1))); }
public async Task SystemBasicFromDefaults() { var finder = new ClrModuleFinder(); finder.AddDefaultAssembly(Assembly.LoadWithPartialName("System")); var mockStack = new Stack <Frame>(); var mockFrame = new Frame(); mockStack.Push(mockFrame); var mockContext = new FrameContext(mockStack); var spec = finder.find_spec(mockContext, "System", null, null); Assert.NotNull(spec); var module = await spec.Loader.Load(null, mockContext, spec) as PyModule; Assert.That(module.Name, Is.EqualTo("System")); }
public CommandResult <TopMenus> Update(int topMenuId, long timestamp, TopMenusUpdateRequestModel requestModel) { var result = new CommandResult <TopMenus>(); using (var db = new FrameContext()) { if (!BaseService.Exist(db, a => a.Id == topMenuId)) { result.Message = "该数据在系统中已不存在,请检查后再试……"; } else if (!BaseService.Exist(db, a => a.Id == topMenuId && a.Timestamp == timestamp)) { result.Message = "该节点已在别处被更改过!"; } else if (requestModel.MenuId != null && requestModel.MenuId.Trim().Length != 0 && BaseService.Exist(db, a => a.Id != topMenuId && a.MenuId == requestModel.MenuId)) { result.Message = $"菜单唯一标识 MenuId “{requestModel.MenuId}”在系统中已存在!"; } else { var entity = BaseService.Find(db, a => a.Id == topMenuId); entity.DisplayName = requestModel.DisplayName; entity.DllPath = requestModel.DllPath; entity.EntryFunction = requestModel.EntryFunction; entity.Ico = requestModel.Ico; entity.MenuId = requestModel.MenuId; entity.ParentId = requestModel.ParentId; entity.Timestamp = requestModel.Timestamp; if (!BaseService.Update(db, entity)) { result.Message = "未知原因"; } else { result.ResultStatus = ResultStatus.Success; result.Message = "更新数据成功"; result.Data = entity; } } } return(result); }
public void ReturningEventDotNet() { FrameContext runContext = null; Assert.Throws <Exception>( () => { runProgram("obj = ReflectIntoPython(1337, 'I did it!')\n" + "obj.ReturnIntTakeIntEvent += obj.SubscribeReturnInteger\n" + "obj.TriggerReturningIntEvent(111)\n" + "obj.ReturnIntTakeIntEvent -= obj.SubscribeReturnInteger\n" + "a = obj.AnInteger\n", new Dictionary <string, object>() { { "ReflectIntoPython", new WrappedCodeObject(typeof(ReflectIntoPython).GetConstructors()) } }, 1, out runContext); }, "Attempted to bind a callable to an event that requires a return type. We don't support this type of binding. " + "All our callables have to be async, and that meddles with signature of basic return values. Why are you using an event with " + "a return type anyways?"); }
public async Task CallGenericExtensionMethod() { FrameContext runContext = await runProgram( "obj = ReflectIntoPython(1337, 'Generic test!')\n" + "b = MockMaterial()\n" + "b.color = 333\n" + "a = obj.AGenericExtensionMethod(MockMaterial, b)\n", new Dictionary <string, object>() { { "ReflectIntoPython", new PyDotNetClassProxy(typeof(ReflectIntoPython)) }, { "MockMaterial", typeof(MockMaterial) } }, 1); var variables = runContext.DumpVariables(); Assert.That(variables.ContainsKey("a")); var aInstance = (MockMaterial)variables["a"]; Assert.That(aInstance.color, Is.EqualTo(333)); }
public async Task SystemDotEnvironment() { var finder = new ClrModuleFinder(); var mockStack = new Stack <Frame>(); var mockFrame = new Frame(); mockStack.Push(mockFrame); var mockContext = new FrameContext(mockStack); var clrLoader = new ClrModuleInternals(); clrLoader.AddReference(mockContext, "mscorlib"); var spec = finder.find_spec(mockContext, "System", null, null); Assert.NotNull(spec); var module = await spec.Loader.Load(null, mockContext, spec) as PyModule; Assert.That(module.Name, Is.EqualTo("System")); }
public async Task NamesAreNotDefinedMultipleTimes() { FrameContext runContext = await runProgram( "class Foo:\n" + " def __init__(self):\n" + " self.a = 1\n" + "\n" + "foo = Foo()\n" + "a = 3\n" + "foo.a = 2\n" + "foo.a = a\n", new Dictionary <string, object>(), 1); Assert.That(runContext.LocalNames.Count, Is.EqualTo(3)); Assert.That(runContext.LocalNames.Contains("Foo")); Assert.That(runContext.LocalNames.Contains("foo")); Assert.That(runContext.LocalNames.Contains("a")); Assert.That(runContext.Names.Count, Is.EqualTo(1)); Assert.That(runContext.Names.Contains("a")); }