public static T ParseCommand <T>(byte[] cmdBytes) { var cmdSize = GetFirstCommandSize(cmdBytes); var bts = cmdBytes.Skip(tag4ContentSize).Take(cmdSize).ToArray(); return(SerializerUtility.Instance().BinDeserialize <T>(bts)); }
internal void SendResponse(CommandResult result) { MemoryStream ms = new MemoryStream(); BufferedStream bs = new BufferedStream(ms); BinaryWriter bw = new BinaryWriter(bs, UnicodeEncoding.UTF8); var cmdBytes = SerializerUtility.Instance().BinSerialize(result); bw.Write(cmdBytes.Length); bw.Write(cmdBytes); bw.Flush(); if (!this.IsTagged) { try { this.Socket.Send(ms.ToArray()); } catch (Exception ex) { Console.WriteLine("Socket.Send失败"); } } }
public TypeItem(MemberData member, FilterAttribute filter = null) { if (member == null) { member = new MemberData(typeof(object)); } _value = SerializerUtility.Duplicate(member); Name = _value.name; if (_value.targetType == MemberData.TargetType.Type) { type = _value.startType; if (type != null) { while (type.IsArray) { type = type.GetElementType(); _value = new MemberData(type); array++; } } } else { type = _value.type; } this.filter = filter; }
public async Task <(Asn1Object, int)> Read(Stream stream, CancellationToken cancellationToken) { var(identifier, identifierBytes) = await SerializerUtility.ReadIdentifier(stream, cancellationToken); var(length, lengthBytes) = await SerializerUtility.ReadLength(stream, cancellationToken); var serializerToUse = FindSerializer(identifier); var(item, itemBytes) = await serializerToUse.Read(this, identifier, length, stream, cancellationToken); return(item, itemBytes + identifierBytes + lengthBytes); }
public CommandResult WaitForResult() { var commandResult = mgr.Receive(); if (!commandResult.Sucessful) { Exception exception = SerializerUtility.Instance().BinDeserialize <Exception>(commandResult.Exception); throw exception; } return(commandResult); }
public MultipurposeMember(MultipurposeMember member) { if (member == null) { return; } target = new MemberData(member.target); parameters = new MemberData[member.parameters.Length]; for (int i = 0; i < parameters.Length; i++) { parameters[i] = new MemberData(member.parameters[i]); } initializer = SerializerUtility.Duplicate(member.initializer); }
public void OnBeforeSerialize() { // #if UNITY_EDITOR // Event e = Event.current; // if(e != null && e.type != UnityEngine.EventType.Used && // (e.type == UnityEngine.EventType.Repaint || // e.type == UnityEngine.EventType.MouseDrag || // e.type == UnityEngine.EventType.Layout || // e.type == UnityEngine.EventType.ScrollWheel)) { // return; // } // #endif _odinSerializedData = SerializerUtility.Serialize(value, out listReference); _serializedData = null; }
public void Send(Command cmd) { MemoryStream ms = new MemoryStream(); BufferedStream bs = new BufferedStream(ms); BinaryWriter bw = new BinaryWriter(bs, UnicodeEncoding.UTF8); var cmdBytes = SerializerUtility.Instance().BinSerialize(cmd); bw.Write(cmdBytes.Length); bw.Write(cmdBytes); bw.Flush(); clientSocket.Send(ms.ToArray()); }
protected void InitLocalVariable() { if (_localVar == null) { var variables = new List <VariableData>(); foreach (var var in localVariable) { if (var.value == null && var.Type.IsValueType) { var.value = ReflectionUtils.CreateInstance(var.Type); } variables.Add(new VariableData(var)); } _localVar = variables; } else { for (int x = 0; x < localVariable.Count; x++) { if (!localVariable[x].resetOnEnter) { continue; } for (int y = 0; y < _localVar.Count; y++) { if (localVariable[x].Name == _localVar[y].Name) { _localVar[y].value = SerializerUtility.Duplicate(localVariable[x].value); goto NEXT; } } _localVar.Add(new VariableData(localVariable[x])); //Add a new local variable if not exist NEXT: continue; } } }
public async void Run(IBackgroundTaskInstance taskInstance) { BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); try { Geolocator geolocator = new Geolocator(); Geoposition position = await geolocator.GetGeopositionAsync(); ////////////////////////////////////////////////////////////////////////// #if DEBUG XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01); XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text"); toastTextElements[0].AppendChild(toastXml.CreateTextNode(position.Coordinate.Point.Position.Latitude + "|" + position.Coordinate.Point.Position.Longitude)); ToastNotification toastNotification = new ToastNotification(toastXml); ToastNotificationManager.CreateToastNotifier().Show(toastNotification); #endif ////////////////////////////////////////////////////////////////////////// ApplicationDataContainer settings = ApplicationData.Current.LocalSettings; LimitedQueue <GPSInfo> queue; if (settings.Values.ContainsKey("Queue") == true) { string queueString = (string)settings.Values["Queue"]; queue = SerializerUtility.Deserialize <LimitedQueue <GPSInfo> >(queueString); } else { queue = new LimitedQueue <GPSInfo>(20); } queue.Push(new GPSInfo() { Latitude = position.Coordinate.Point.Position.Latitude, Longitude = position.Coordinate.Point.Position.Longitude, PositionSource = position.Coordinate.PositionSource.ToString() }); try { string deviceUniqueId = UniqueIdUtility.GetUniqueId(); GPSInfo[] gpsInfoList = queue.Retrive(); string gpsInfoListJson = SerializerUtility.Serialize <GPSInfo[]>(gpsInfoList); KeyValuePair <string, string>[] postData = new KeyValuePair <string, string> [2]; postData[0] = new KeyValuePair <string, string>("deviceUniqueId", deviceUniqueId); postData[1] = new KeyValuePair <string, string>("gpsInfoList", gpsInfoListJson); await HttpUtility.GetHttpResponse(ConfigUtility.GetValue("SendPositionAPI"), postData); queue.Clear(); } finally { string queueString = SerializerUtility.Serialize <LimitedQueue <GPSInfo> >(queue); settings.Values["Queue"] = queueString; } } catch (Exception ex) { } deferral.Complete(); }
private static void Command_IncludeTypes(object sender, EventArgsCommand e) { SerializerUtility.AddType(typeof(StardewValley.Characters.Junimo)); //Adds a type to SaveGame.serializer // SerializerUtility.AddFarmerType(typeof(/*Class2NameHere*/)); //Adds a type to SaveGame.farmerSerializer }
public void OnAfterDeserialize() { value = SerializerUtility.DeserializeMigration(ref _odinSerializedData, ref _serializedData, ref listReference) as BaseValueData; }
private async void CheckBinding() { try { KeyValuePair <string, string>[] postData = new KeyValuePair <string, string> [1]; postData[0] = new KeyValuePair <string, string>("deviceUniqueId", UniqueIdUtility.GetUniqueId()); string owner = await HttpUtility.GetHttpResponse(ConfigUtility.GetValue("GetDeviceOwnerAPI"), postData); if (owner == "") { BackgroundTaskUtility.UnregisterBackgroundTask("MyTask"); ApplicationDataContainer settings = ApplicationData.Current.LocalSettings; if (settings.Values.ContainsKey("Queue") == true) { settings.Values.Remove("Queue"); } } else { BackgroundTaskUtility.RegisterBackgroundTask("RuntimeComponent.TrackingTask", "MyTask", new TimeTrigger(15, false), null); } await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { if (owner == "") { ownerTextbox.Text = ""; ownerTextbox.IsEnabled = true; deviceNameTextbox.Text = ""; deviceNameTextbox.IsEnabled = true; bindButton.IsEnabled = true; unbindButton.IsEnabled = false; } else { string[] ownerAndDeviceName = SerializerUtility.Deserialize <string[]>(owner); ownerTextbox.Text = ownerAndDeviceName[0]; ownerTextbox.IsEnabled = false; deviceNameTextbox.Text = ownerAndDeviceName[1]; deviceNameTextbox.IsEnabled = false; bindButton.IsEnabled = false; unbindButton.IsEnabled = true; } bindingGrid.Visibility = Visibility.Visible; }); } catch (Exception ex) { await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { bindingGrid.Visibility = Visibility.Collapsed; errorGrid.Visibility = Visibility.Visible; }); } finally { await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { progressRing.IsActive = false; progressRing.Visibility = Visibility.Collapsed; }); } }
private CommandResult Process(Command command) { var serviceDescriptor = ServiceRegistry.ResolveServiceDescriptor(command.CallContract); var methodDescriptor = ServiceRegistry.ResolveMethodDescriptor(command.CallContract, command.Method2Invoke); List <object> parameters = new List <object>(); foreach (var pd in methodDescriptor.ParameterDescriptors) { parameters.Add(ParameterParser.GetValue(command, pd)); } object serviceInstance = Activator.CreateInstance(serviceDescriptor.ServiceType); bool successful = false; Exception exc = null; bool noReturnValue = false; object resultValue = null; if (methodDescriptor.MethodInfo.ReturnType.Equals(typeof(void))) { noReturnValue = true; } try { if (noReturnValue) { methodDescriptor.MethodInfo.Invoke(serviceInstance, parameters.ToArray()); } else { resultValue = methodDescriptor.MethodInfo.Invoke(serviceInstance, parameters.ToArray()); } successful = true; } catch (Exception ex) { exc = ex.InnerException; successful = false; } CommandResult result = new CommandResult(); result.Sucessful = successful; result.ConnectionWorker = command.ConnectionWorker; if (successful) { if (!noReturnValue) { result.Result = SerializerUtility.Instance().BinSerialize(resultValue); } } else { result.Exception = SerializerUtility.Instance().BinSerialize(exc); } result.ConnectionWorker.LastActiveTime = DateTime.Now; //reset timeout return(result); }
public static T Create <T>(CommandBusClient commandBusClient) { string id = string.Format("Commonization{0}", typeof(T).FullName.Replace(".", "")); string proxyTypeString = "Commonization" + id; string proxyDllName = id + ".dll"; Type proxyType = null; if (!createdProxies.ContainsKey(typeof(T))) { AssemblyBuilder asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(id), AssemblyBuilderAccess.RunAndSave); var mdlBldr = asmBuilder.DefineDynamicModule(id, proxyDllName); var typeBldr = mdlBldr.DefineType(proxyTypeString, TypeAttributes.Public, null, new Type[] { typeof(T) }); //嵌入ESB私有变量 var esbSrvField = typeBldr.DefineField("esbSrv", typeof(CommandBusClient), FieldAttributes.Private); var serializeField = typeBldr.DefineField("serializeSrv", typeof(SerializerUtility), FieldAttributes.Private); //构造函数 var constructor = typeBldr.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(CommandBusClient), typeof(SerializerUtility) }); var il = constructor.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_2); il.Emit(OpCodes.Stfld, serializeField); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Stfld, esbSrvField); il.Emit(OpCodes.Ret); //改写方法 var methods = typeof(T).GetMethods(BindingFlags.Public | BindingFlags.Instance); for (var i = 0; i < methods.Length; i++) { var paramTypes = GetParametersType(methods[i]); Type[] parameterTypes = null; if (paramTypes != null && paramTypes.Length > 0) { parameterTypes = paramTypes.Select(f => f.ParameterType).ToArray(); } else { parameterTypes = new Type[] { } }; var methodBlfr = typeBldr.DefineMethod(methods[i].Name, MethodAttributes.Public | MethodAttributes.Virtual, CallingConventions.Standard, methods[i].ReturnType, parameterTypes); il = methodBlfr.GetILGenerator(); //声明各个局部变量 var requestLocal = il.DeclareLocal(typeof(Command)); var argsLocal = il.DeclareLocal(typeof(Dictionary <string, object>)); var responseLocal = il.DeclareLocal(typeof(CommandResult)); var value2Object = il.DeclareLocal(typeof(object)); #region Command requestLocal=new Command(); il.Emit(OpCodes.Newobj, typeof(Command).GetConstructor(new Type[0])); il.Emit(OpCodes.Stloc, requestLocal); #endregion #region Dictionary<string, object> argsLocal=new Dictionary<string, object>(); il.Emit(OpCodes.Newobj, typeof(Dictionary <string, object>).GetConstructor(new Type[0])); il.Emit(OpCodes.Stloc, argsLocal); #endregion #region 将传入方法的参数全部Add到List object 中 MethodInfo mi = typeof(Dictionary <string, object>).GetMethod("Add"); if (paramTypes != null) { for (var index = 0; index < paramTypes.Length; index++) { if (paramTypes[index].ParameterType.IsValueType) { //box il.Emit(OpCodes.Ldarg, 1 + index); il.Emit(OpCodes.Box, paramTypes[index].ParameterType); il.Emit(OpCodes.Stloc, value2Object); il.Emit(OpCodes.Ldloc, argsLocal); il.Emit(OpCodes.Ldstr, paramTypes[index].ParameterName); //Dictionary->key il.Emit(OpCodes.Ldloc, value2Object); //Dictionary->value il.Emit(OpCodes.Callvirt, mi); } else { il.Emit(OpCodes.Ldloc, argsLocal); il.Emit(OpCodes.Ldstr, paramTypes[index].ParameterName); //Dictionary->key il.Emit(OpCodes.Ldarg, 1 + index); //Dictionary->value il.Emit(OpCodes.Callvirt, mi); } } } #endregion #region requestLocal.Arguments=argsLocal mi = typeof(Command).GetMethod("set_Arguments"); il.Emit(OpCodes.Ldloc, requestLocal); il.Emit(OpCodes.Ldloc, 1); il.Emit(OpCodes.Callvirt, mi); #endregion #region requestLocal.Method2Invoke=methods[i].Name mi = typeof(Command).GetMethod("set_Method2Invoke"); il.Emit(OpCodes.Ldloc, requestLocal); il.Emit(OpCodes.Ldstr, methods[i].Name); il.Emit(OpCodes.Callvirt, mi); #endregion #region requestLocal.CallContractNamespace=typeof(T).Namespace mi = typeof(Command).GetMethod("set_CallContractNamespace"); il.Emit(OpCodes.Ldloc, requestLocal); il.Emit(OpCodes.Ldstr, typeof(T).Namespace); il.Emit(OpCodes.Callvirt, mi); #endregion #region requestLocal.CallContract=typeof(T).Name mi = typeof(Command).GetMethod("set_CallContract"); il.Emit(OpCodes.Ldloc, requestLocal); il.Emit(OpCodes.Ldstr, typeof(T).Name); il.Emit(OpCodes.Callvirt, mi); #endregion #region esbSrvField.Send(requestLocal) mi = typeof(CommandBusClient).GetMethod("Send"); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, esbSrvField); il.Emit(OpCodes.Ldloc, requestLocal); il.Emit(OpCodes.Call, mi); #endregion #region esbSrvField.WaitForResult() mi = typeof(CommandBusClient).GetMethod("WaitForResult"); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, esbSrvField); il.Emit(OpCodes.Callvirt, mi); il.Emit(OpCodes.Stloc, responseLocal); #endregion if (methods[i].ReturnType != typeof(void)) { var response_Result_Bytes = il.DeclareLocal(typeof(byte[])); var responseResultCasted = il.DeclareLocal(methods[i].ReturnType); #region responseResult=responseLocal.Result/Successful/Exception; mi = typeof(CommandResult).GetMethod("get_Result"); il.Emit(OpCodes.Ldloc, responseLocal); il.Emit(OpCodes.Callvirt, mi); il.Emit(OpCodes.Stloc, response_Result_Bytes); #endregion #region SerializerUtility.BinDeserialize<T>(cmdResult.Result) mi = typeof(SerializerUtility).GetMethod("BinDeserialize"); mi = mi.MakeGenericMethod(methods[i].ReturnType); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, serializeField); il.Emit(OpCodes.Ldloc, response_Result_Bytes); il.Emit(OpCodes.Callvirt, mi); il.Emit(OpCodes.Stloc, responseResultCasted); il.Emit(OpCodes.Ldloc, responseResultCasted); #endregion } il.Emit(OpCodes.Ret); } proxyType = typeBldr.CreateType(); //asmBuilder.Save(proxyDllName); createdProxies[typeof(T)] = proxyType; } proxyType = createdProxies[typeof(T)]; return((T)Activator.CreateInstance(proxyType, new object[] { commandBusClient, SerializerUtility.Instance() })); }
public void EnsureInitialized() { if (hasInitialize) { return; } if (!Application.isPlaying) { throw new System.Exception("Can't initialize event when not playing."); } else if (target == null) { throw new Exception("Target graph can't be null"); } hasInitialize = true; if (target is uNodeComponentSingleton singleton) { bool flag = singleton.EnsureInitialized(false); runtimeBehaviour = singleton.runtimeBehaviour; if (flag && runtimeBehaviour != null) { //Initialize the variable for (int i = 0; i < target.Variables.Count; i++) { VariableData var = target.Variables[i]; for (int x = 0; x < variable.Count; x++) { if (var.Name.Equals(variable[x].Name)) { var = variable[x]; break; } } SetVariable(var.Name, SerializerUtility.Duplicate(var.value)); } runtimeBehaviour.OnAwake(); } runtimeInstance = singleton.runtimeInstance; if (flag && runtimeInstance != null) { //Initialize the variable for (int i = 0; i < target.Variables.Count; i++) { VariableData var = target.Variables[i]; for (int x = 0; x < variable.Count; x++) { if (var.Name.Equals(variable[x].Name)) { var = variable[x]; break; } } SetVariable(var.Name, SerializerUtility.Duplicate(var.value)); } variable = runtimeInstance.Variables; runtimeInstance.Initialize(); } return; } var type = target.GeneratedTypeName.ToType(false); if (type != null) { //Instance native c# graph, native graph will call Awake immediately runtimeBehaviour = gameObject.AddComponent(type) as RuntimeBehaviour; runtimeBehaviour.hideFlags = HideFlags.HideInInspector; //Initialize the references var references = target.graphData.unityObjects; for (int i = 0; i < references.Count; i++) { SetVariable(references[i].name, references[i].value); } //Initialize the variable for (int i = 0; i < target.Variables.Count; i++) { VariableData var = target.Variables[i]; for (int x = 0; x < variable.Count; x++) { if (var.Name.Equals(variable[x].Name)) { var = variable[x]; break; } } SetVariable(var.Name, SerializerUtility.Duplicate(var.value)); } //Call awake runtimeBehaviour.OnAwake(); } else { //Instance reflection graph var main = RuntimeGraphManager.InstantiateGraph(target, gameObject, variable); variable = main.Variables; runtimeInstance = main; main.Initialize(); //Initialize the graph, so it will call Awake after created. main.manualHandlingEvent = true; } }