public DynamicReadTravellerBuilder(MethodBuilder builder, SerializableType target, TravellerContext context)
 {
     _target = target;
     _context = context;
     _il = builder.IL;
     _visitorVariable = new MethodArgILCodeVariable(1, typeof(IReadVisitor));
 }
        public When_converting_to_serializable_object_with_additional_properies()
        {
            var dynamicObject = new DynamicObject()
            {
                { "Int32Value", Int32Value },
                { "StringValue", StringValue },
            };

            obj = dynamicObject.CreateObject<SerializableType>();
        }
	protected virtual SerializableType GetSerializableType(SerializedProperty p_property)
	{
		SerializableType v_return = null;
		if(p_property.serializedObject != null && p_property.serializedObject.targetObject != null)
		{
			v_return = p_property.serializedObject.targetObject.GetFieldValue<SerializableType>(p_property.name);
		}
		if(v_return == null)
			v_return = new SerializableType();
		return v_return;
	}
	protected virtual void SetSerializableType(SerializedProperty p_property, SerializableType p_value)
	{
		if(p_property.serializedObject != null && p_property.serializedObject.targetObject != null)
		{
			FieldInfo v_myField = p_property.serializedObject.targetObject.GetType().GetField(p_property.name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
			if(v_myField != null)
			{
				v_myField.SetValue(p_property.serializedObject.targetObject, p_value);
			}
		}
	}
        public When_converting_to_serializable_object_with_private_property_setters()
        {
            var dynamicObject = new DynamicObject
            {
                { "Int32Value", Int32Value },
                { "DoubleValue", DoubleValue },
                { "StringValue", StringValue },
            };

            obj = dynamicObject.CreateObject<SerializableType>();
        }
        public When_converting_to_serializable_object_with_missing_properties()
        {
            var dynamicObject = new DynamicObject()
            {
                { "Int32Value", Int32Value },
                { "DoubleValue", DoubleValue },
                { "NullableDateTimeValue", NullableDateTimeValue },
                { "StringValue", StringValue },
            };

            obj = dynamicObject.CreateObject<SerializableType>();
        }
	protected override void DrawComponentAfterDependenceCheck(Rect position, SerializedProperty property, GUIContent label, System.Type p_type)
	{
		SerializableTypeAttribute v_attr = (SerializableTypeAttribute)attribute;
		SerializableType v_serType = GetSerializableType(property);
		SerializableType v_newType = InspectorUtils.SerializableTypePopup(position, label.text, v_serType, v_attr.FilterType, v_attr.AcceptGenericDefinitions);
		if(v_newType == null)
			v_newType = new SerializableType();
		if(v_serType.CastedType != v_newType.CastedType || v_serType.StringType != v_newType.StringType)
		{
			SetSerializableType(property, v_newType);
			try
			{
				EditorUtility.SetDirty(property.serializedObject.targetObject);
			}
			catch{}
		}
	}
    protected override void DrawComponentAfterDependenceCheck(Rect position, SerializedProperty property, GUIContent label, System.Type p_type)
    {
        SerializableTypeAttribute v_attr    = (SerializableTypeAttribute)attribute;
        SerializableType          v_serType = GetSerializableType(property);
        SerializableType          v_newType = InspectorUtils.SerializableTypePopup(position, label.text, v_serType, v_attr.FilterType, v_attr.AcceptGenericDefinitions);

        if (v_newType == null)
        {
            v_newType = new SerializableType();
        }
        if (v_serType.CastedType != v_newType.CastedType || v_serType.StringType != v_newType.StringType)
        {
            SetSerializableType(property, v_newType);
            try
            {
                EditorUtility.SetDirty(property.serializedObject.targetObject);
            }
            catch {}
        }
    }
Esempio n. 9
0
        private void Initialize(Generator generator, Type assetType, bool isOptional, bool isMutating)
        {
            if (generator == null)
            {
                throw new ArgumentNullException("generator");
            }
            if (assetType == null)
            {
                throw new ArgumentNullException("assetType");
            }

            _generator  = generator;
            _assetType  = assetType;
            _isOptional = isOptional;
            _isMutating = isMutating;

            isActive = true;

            Disconnect();
        }
Esempio n. 10
0
        private void Initialize(Generator generator, System.Type assetType, string name, string path, bool isEnabled, Availability availability, bool persistable)
        {
            if (generator == null)
            {
                throw new System.ArgumentNullException("generator");
            }
            if (assetType == null)
            {
                throw new System.ArgumentNullException("assetType");
            }
            if (string.IsNullOrEmpty(name))
            {
                throw new System.ArgumentException("Output slot must be given a non-empty name.", "name");
            }
            if (assetType == typeof(GameObject) && availability == Availability.DuringGeneration)
            {
                throw new System.ArgumentException("Assets of type GameObject must always be available after generation.", "availability");
            }
            if (assetType == typeof(GameObject) && persistable == false)
            {
                throw new System.ArgumentException("Assets of type GameObject must always be available after generation.", "persistable");
            }
            if ((availability & Availability.AfterGeneration) != 0 && persistable == false)
            {
                throw new System.ArgumentException("Inconsistent argument values.", "persistable");
            }

            _generator    = generator;
            _assetType    = assetType;
            _persistable  = persistable;
            _availability = availability;

            this.path      = string.IsNullOrEmpty(path) ? null : path;
            this.name      = name;
            this.isEnabled = isEnabled;

            isActive = true;

            DisconnectAll();
            ForgetAsset();
        }
Esempio n. 11
0
        public byte[] GetListOf(Guid version, SerializableType type, int ID, string property)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            if (String.IsNullOrEmpty(property))
            {
                throw new ArgumentNullException("property");
            }

            return(MakeRequest(GetListOfUri,
                               reqStream =>
            {
                reqStream.Write(version);
                reqStream.Write(type);
                reqStream.Write(ID);
                reqStream.Write(property);
                reqStream.WriteRaw(Encoding.ASCII.GetBytes("\n"));    // required for basic.authenticated POST to apache
            }));
        }
Esempio n. 12
0
        private static Field[] CreateFields(MonoManager manager, MonoTypeContext context)
        {
            List <Field>   fields     = new List <Field>();
            TypeDefinition definition = context.Type.Resolve();
            IReadOnlyDictionary <GenericParameter, TypeReference> arguments = context.GetContextArguments();

            foreach (FieldDefinition field in definition.Fields)
            {
                if (MonoField.IsSerializable(field, arguments))
                {
                    MonoTypeContext  fieldContext    = new MonoTypeContext(field.FieldType, arguments);
                    MonoTypeContext  resolvedContext = fieldContext.Resolve();
                    MonoTypeContext  serFieldContext = GetSerializedElementContext(resolvedContext);
                    SerializableType scriptType      = manager.GetSerializableType(serFieldContext);
                    bool             isArray         = MonoField.IsSerializableArray(resolvedContext.Type);
                    Field            fieldStruc      = new Field(scriptType, isArray, field.Name);
                    fields.Add(fieldStruc);
                }
            }
            return(fields.ToArray());
        }
Esempio n. 13
0
        public void Analyze(AssemblyDefinition assemblyDefinition, ModuleDefinition moduleDefinition, TypeDefinition typeDefinition, MethodDefinition methodDefinition)
        {
            var attr = methodDefinition.GetAttribute <FieldOperationAttribute>();

            if (attr.ConstructorArguments.Count != 5)
            {
                return;
            }
            string         identifier              = (string)attr.ConstructorArguments[0].Value;
            TypeDefinition configTypeDef           = ((TypeReference)attr.ConstructorArguments[1].Value).Resolve();
            string         displayName             = (string)attr.ConstructorArguments[2].Value;
            string         subIdentifier           = (string)attr.ConstructorArguments[3].Value;
            TypeDefinition outputTypeRef           = ((TypeReference)attr.ConstructorArguments[4].Value).Resolve();
            var            outputTypeQualifiedName = outputTypeRef.AssemblyQualifiedName();
            var            configTypeQualifiedName = configTypeDef?.AssemblyQualifiedName();
            var            configType              = new SerializableType(configTypeQualifiedName);
            var            outputType              = new SerializableType(outputTypeQualifiedName);
            var            method = new SerializableMethod(typeDefinition.AssemblyQualifiedName(), methodDefinition.Name);
            var            opCall = new FieldOperationSchema.Operation.Variant
            {
                displayName = displayName,
                configType  = configType,
                method      = method,
                outputType  = outputType
            };

            if (!operations.TryGetValue(identifier, out FieldOperationSchema.Operation op))
            {
                op = new FieldOperationSchema.Operation
                {
                    identifier = identifier
                };
                operations[identifier] = op;
            }
            if (op.callVariants.ContainsKey(subIdentifier))
            {
                Debug.LogError($"Duplicate Sub-Identifiers found for identifier '{identifier}': '{subIdentifier}'");
            }
            op.callVariants[subIdentifier] = opCall;
        }
Esempio n. 14
0
        public void Export(TextWriter writer, int intent)
        {
            if (Attributes != null)
            {
                foreach (ScriptExportAttribute attribute in Attributes)
                {
                    attribute.Export(writer, intent);
                }
            }

            writer.WriteIndent(intent);
            writer.Write("{0} ", Keyword);
            if (IsNew)
            {
                writer.Write("new ");
            }

            string name = Type.GetTypeNestedName(DeclaringType);

            name = SerializableType.IsEngineObject(Type.Namespace, name) ? $"{Type.Namespace}.{name}" : name;
            writer.WriteLine("{0} {1};", name, Name);
        }
        public void TestConstructor()
        {
            int id = 0;
            SerializableType      type      = SerializableType.Bench;
            bool                  isStatic  = true;
            SerializableVector3   position  = new SerializableVector3(0, 0, 0);
            SerializableVector3   scale     = new SerializableVector3(1, 1, 1);
            SerializableVector3   rotation  = new SerializableVector3(2, 2, 2);
            SerializableCharacter character = new SerializableCharacter(true, "Test");

            SerializableTransformObject constructor = new SerializableTransformObject(id, type, isStatic, position, scale, rotation, character);

            Assert.True(constructor is SerializableTransformObject);

            Assert.That(constructor.Id, Is.EqualTo(id));
            Assert.That(constructor.Type, Is.EqualTo(type));
            Assert.That(constructor.IsStatic, Is.EqualTo(isStatic));
            Assert.That(constructor.Position, Is.EqualTo(position));
            Assert.That(constructor.Scale, Is.EqualTo(scale));
            Assert.That(constructor.Rotation, Is.EqualTo(rotation));
            Assert.That(constructor.Character, Is.EqualTo(character));
        }
Esempio n. 16
0
 /// <summary>
 /// 序列化
 /// </summary>
 /// <param name="st"></param>
 public virtual void DoSerialization(SerializableType st)
 {
     if (st == SerializableType.Binary)
     {
         string keys = "";
         foreach (string key in Keys)
         {
             _info.AddValue(key, GetValue(key));
             string typename = "";
             if (GetValue(key) != null)
             {
                 typename = GetValue(key).GetType().FullName;
             }
             _info.AddValue(key + "_Type#", typename);
             keys += keys.Length <= 0 ? key : ";" + key;
         }
         _info.AddValue("DatatdKeys#", keys);
     }
     else
     {
     }
 }
Esempio n. 17
0
        ///序列化过程使用try > catch
        public static System.Object DeSerializableObj(string inPath, SerializableType type = SerializableType.Bin)
        {
            try
            {
                switch (type)
                {
                case SerializableType.Bin:
                    return(DeSerializable_BinHanlder(inPath));

                case SerializableType.Soap:
                    return(DeSerializable_SnoapHanlder(inPath));

                case SerializableType.Json:
                    return(DeSerializable_JsonHandler(inPath));
                }
            }
            catch (System.Exception e)
            {
                Console.Write(e);
            }
            return(null);
        }
    public void OnBeforeSerialize()
    {
        if (methodInfo == null)
        {
            return;
        }
        type       = new SerializableType(methodInfo.DeclaringType);
        methodName = methodInfo.Name;
        if (methodInfo.IsPrivate)
        {
            flags |= (int)BindingFlags.NonPublic;
        }
        else
        {
            flags |= (int)BindingFlags.Public;
        }
        if (methodInfo.IsStatic)
        {
            flags |= (int)BindingFlags.Static;
        }
        else
        {
            flags |= (int)BindingFlags.Instance;
        }
        var p = methodInfo.GetParameters();

        if (p != null && p.Length > 0)
        {
            parameters = new List <SerializableType>(p.Length);
            for (int i = 0; i < p.Length; i++)
            {
                parameters.Add(new SerializableType(p[i].ParameterType));
            }
        }
        else
        {
            parameters = null;
        }
    }
Esempio n. 19
0
        public byte[] GetListOf(Guid version, SerializableType type, int ID, string property)
        {
            using (Logging.Facade.DebugTraceMethodCallFormat("GetListOf", "type={0}", type))
            {
                DebugLogIdentity();
                try
                {
                    if (type == null)
                    {
                        throw new ArgumentNullException("type");
                    }

                    using (var ctx = _ctxFactory())
                    {
                        var ifType      = _iftFactory(type.GetSystemType());
                        int resultCount = 0;
                        var ticks       = _perfCounter.IncrementGetListOf(ifType);
                        try
                        {
                            IEnumerable <IStreamable> lst = _sohFactory
                                                            .GetServerObjectHandler(ifType)
                                                            .GetListOf(version, ctx, ID, property);
                            resultCount = lst.Count();
                            return(SendObjects(lst, false /*true*/).ToArray());
                        }
                        finally
                        {
                            _perfCounter.DecrementGetListOf(ifType, resultCount, ticks);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Helper.ThrowFaultException(ex);
                    // Never called, Handle errors throws an Exception
                    return(null);
                }
            }
        }
Esempio n. 20
0
        public byte[] InvokeServerMethod(out byte[] retChangedObjects, Guid version, SerializableType type, int ID, string method, SerializableType[] parameterTypes, byte[] parameter, byte[] changedObjects, ObjectNotificationRequest[] notificationRequests)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            var req = InitializeRequest(InvokeServerMethodUri);

            using (var reqStream = req.GetRequestStream())
                using (var reqWriter = _writerFactory(new BinaryWriter(reqStream)))
                {
                    reqWriter.Write(version);
                    reqWriter.Write(type);
                    reqWriter.Write(ID);
                    reqWriter.Write(method);
                    reqWriter.Write(parameterTypes);
                    reqWriter.Write(parameter);
                    reqWriter.Write(changedObjects);
                    reqWriter.Write(notificationRequests);
                }
            try
            {
                using (var response = req.GetResponse())
                    using (var input = response.GetResponseStream())
                        using (var reader = _readerFactory(new BinaryReader(input)))
                        {
                            reader.Read(out retChangedObjects);
                            return(reader.ReadByteArray());
                        }
            }
            catch (WebException ex)
            {
                var errorMsg = String.Format("Error when accessing server({0}): {1}: {2}", InvokeServerMethodUri, ex.Status, ex.Response);
                Log.Error(errorMsg);
                throw new ApplicationException(errorMsg, ex);
            }
        }
        public static string GetName(TypeReference type)
        {
            if (MonoType.IsCPrimitive(type))
            {
                return(SerializableType.ToCPrimitiveString(type.Name));
            }

            if (type.IsGenericInstance)
            {
                GenericInstanceType generic = (GenericInstanceType)type;
                return(GetGenericInstanceName(generic));
            }
            else if (type.HasGenericParameters)
            {
                return(GetGenericTypeName(type));
            }
            else if (type.IsArray)
            {
                ArrayType array = (ArrayType)type;
                return(GetName(array.ElementType) + $"[{new string(',', array.Dimensions.Count - 1)}]");
            }
            return(type.Name);
        }
Esempio n. 22
0
        public string GetTypeNestedName(ScriptExportType relativeType)
        {
            if (relativeType == null)
            {
                return(NestedName);
            }
            if (SerializableType.IsEngineObject(Namespace, NestedName))
            {
                return($"{Namespace}.{NestedName}");
            }
            if (DeclaringType == null)
            {
                return(TypeName);
            }
            if (relativeType == DeclaringType)
            {
                return(TypeName);
            }

            string declaringName = NestType.GetTypeNestedName(relativeType);

            return($"{declaringName}.{TypeName}");
        }
Esempio n. 23
0
        private void CreateSerilizer(SerializableType serilizableType)
        {
            switch (serilizableType)
            {
            case SerializableType.None:
                throw new ArgumentOutOfRangeException("serilizableType", serilizableType, null);

            case SerializableType.Newtonsoft:
                _curSerialiser = new NewtonsoftSerilizer();
                break;

            case SerializableType.FullSerializer:
                _curSerialiser = new FullSerializer();
                break;

            case SerializableType.GameDevWareSerializer:
                _curSerialiser = new GameDevWareSerializer();
                break;

            default:
                throw new ArgumentOutOfRangeException("serilizableType", serilizableType, null);
            }
        }
Esempio n. 24
0
 private bool AssemblyContainsFilteredType(Assembly p_assembly, SerializableType p_filterType, bool p_acceptGenericDefinition, bool p_acceptAbstractDefinition)
 {
     if (p_filterType == null || p_filterType.CastedType == null)
     {
         return(true);
     }
     if (p_assembly != null)
     {
         string v_safeTypeNameInAssembly = GetSafeTypedNameInAssembly(p_filterType);
         foreach (System.Type v_type in p_assembly.GetTypes())
         {
             if (v_type != null &&
                 p_filterType != null &&
                 (TypeExtensions.IsSameOrSubClassOrImplementInterface(v_type, p_filterType.CastedType) ||
                  v_type.FullName.Contains(v_safeTypeNameInAssembly)) &&
                 (p_acceptGenericDefinition || !v_type.IsGenericTypeDefinition) &&
                 (p_acceptAbstractDefinition || !v_type.IsAbstract))
             {
                 return(true);
             }
         }
     }
     return(false);
 }
Esempio n. 25
0
        public string this[SerializableType type, string key]
        {
            get
            {
                if (string.IsNullOrWhiteSpace(key))
                {
                    throw new Exception("key cannot be null or whitespace");
                }

                var serialized = GetSerialized(type, key);
                return(serialized != null ? serialized.Data : null);
            }

            set
            {
                if (string.IsNullOrWhiteSpace(key))
                {
                    throw new Exception("key cannot be null or whitespace");
                }

                var serialized = GetSerialized(type, key);
                if (serialized == null)
                {
                    var serializedData = GetSerialized(type);
                    serialized = new Serialized
                    {
                        Type   = (int)type,
                        OldKey = key
                    };
                    _context.Serialized.AddObject(serialized);
                    serializedData.Add(key, serialized);
                }

                serialized.Data = value;
            }
        }
Esempio n. 26
0
        private static void GenerateEngineCurve(TypeTreeContext context, SerializableType origin, string name)
        {
            switch (origin.Name)
            {
            case SerializableType.FloatCurveName:
                FloatCurveLayout.GenerateTypeTree(context, name);
                break;

            case SerializableType.Vector3CurveName:
                Vector3CurveLayout.GenerateTypeTree(context, name);
                break;

            case SerializableType.QuaternionCurveName:
                QuaternionCurveLayout.GenerateTypeTree(context, name);
                break;

            case SerializableType.PPtrCurveName:
                PPtrCurveLayout.GenerateTypeTree(context, name);
                break;

            default:
                throw new Exception($"Unknown engine curve {origin.Name}");
            }
        }
Esempio n. 27
0
        ///*.bin
        public static void SerializableObj(System.Object s_object, string outPath, SerializableType type = SerializableType.Bin)
        {
            try
            {
                switch (type)
                {
                case SerializableType.Bin:
                    Serializable_BinHandler(s_object, outPath);
                    break;

                case SerializableType.Soap:
                    Serializable_SoapHandler(s_object, outPath);
                    break;

                case SerializableType.Json:
                    Serializable_JsonHandler(s_object, outPath);
                    break;
                }
            }
            catch (System.Exception e)
            {
                Console.Write(e);
            }
        }
Esempio n. 28
0
 public override void DeSerialization(SerializableType st)
 {
     if (st == SerializableType.Binary)
     {
         string   keys     = _info.GetString("DatatdKeys#");
         string[] keyarray = keys.Split(';');
         foreach (string key in keyarray)
         {
             string typename = _info.GetString(key + "_Type#");
             if (!string.IsNullOrEmpty(typename))
             {
                 Type t = Type.GetType(_info.GetString(key + "_Type#"));
                 SetValue(key, _info.GetValue(key, t));
             }
             else
             {
                 SetValue(key, null);
             }
         }
     }
     else
     {
     }
 }
Esempio n. 29
0
        protected override void DrawComponentAfterDependenceCheck(Rect position, SerializedProperty property, GUIContent label, System.Type p_type)
        {
            SerializableTypeAttribute v_attr    = (SerializableTypeAttribute)attribute;
            SerializableType          v_serType = GetSerializableTypeValue(property);
            SerializableType          v_newType = KiltEditor.InspectorUtils.SerializableTypePopup(position, label.text, v_serType, v_attr.FilterType, v_attr.AcceptGenericDefinitions, v_attr.AcceptAbstractDefinitions, v_attr.AcceptNulls, v_attr.FilterAssemblies);

            if (v_newType == null)
            {
                v_newType = new SerializableType();
            }
            if (v_serType.CastedType != v_newType.CastedType || v_serType.StringType != v_newType.StringType)
            {
                SetSerializableTypeValue(property, v_newType);
                try
                {
#if UNITY_5_3_OR_NEWER
                    property.serializedObject.ApplyModifiedPropertiesWithoutUndo();
#else
                    EditorUtility.SetDirty(property.serializedObject.targetObject);
#endif
                }
                catch { }
            }
        }
        public void Analyze(AssemblyDefinition assemblyDefinition, ModuleDefinition moduleDefinition, TypeDefinition typeDefinition)
        {
            var attr = typeDefinition.GetAttribute <ActionArgumentAttribute>();
            var delegateTypeReference          = assemblyDefinition.MainModule.ImportReference(typeof(Delegate));
            var multicastDelegateTypeReference = assemblyDefinition.MainModule.ImportReference(typeof(MulticastDelegate));
            var actionDelegateTypeDefinition   = ((TypeReference)attr.ConstructorArguments[0].Value).Resolve();
            var delegateType  = new SerializableType(actionDelegateTypeDefinition.AssemblyQualifiedName());
            var parameterName = (string)attr.ConstructorArguments[1].Value;
            var field         = typeDefinition.Fields[0];

            if (actionDelegateTypeDefinition.BaseType.FullName != delegateTypeReference.FullName && actionDelegateTypeDefinition.BaseType.FullName != multicastDelegateTypeReference.FullName)
            {
                Debug.LogError("Not Delegate");
                return;
            }
            var parameter = actionDelegateTypeDefinition.Methods.First(m => m.Name == "Invoke").Parameters.FirstOrDefault(parameter => parameter.Name == parameterName);

            if (parameter == null || parameter.ParameterType.FullName != field.FieldType.FullName)
            {
                Debug.LogError("Unknown parameter");
                return;
            }
            if (!data.TryGetValue(delegateType.AssemblyQualifiedName, out Dictionary <string, ActionArgumentComponentSchema.ActionArgumentComponent> argumentComponents))
            {
                argumentComponents = new Dictionary <string, ActionArgumentComponentSchema.ActionArgumentComponent>();
                data[delegateType.AssemblyQualifiedName] = argumentComponents;
            }
            argumentComponents[parameterName] = new ActionArgumentComponentSchema.ActionArgumentComponent
            {
                delegateType    = delegateType,
                componentType   = new SerializableType(typeDefinition.AssemblyQualifiedName()),
                parameterName   = parameterName,
                fieldName       = field.Name,
                singletonTarget = parameter.CustomAttributes.Any(a => a.AttributeType.FullName == typeof(SingletonArgumentAttribute).FullName)
            };
        }
Esempio n. 31
0
        private static void GenerateNode(TypeTreeContext context, SerializableType origin, string name)
        {
#warning TODO: QuaternionCurve, Vector3Curve, PPtrCurve
            if (origin.IsPrimitive())
            {
                context.AddPrimitive(origin.Name, name);
            }
            else if (origin.IsString())
            {
                context.AddString(name);
            }
            else if (origin.IsEngineStruct())
            {
                GenerateEngineStruct(context, origin, name);
            }
            else if (origin.IsEnginePointer())
            {
                context.AddPPtr(origin.Name, name);
            }
            else
            {
                GenerateSerializableNode(context, origin, name);
            }
        }
Esempio n. 32
0
        public void CallbackOrderShouldBe0()
        {
            var actual = new SerializableType();

            Assert.AreEqual(0, actual.callbackOrder);
        }
            public async Task <object> Start()
            {
                RequestResponseAmqpLink requestLink = await this.client.link.GetOrCreateAsync(TimeSpan.FromMinutes(1));

                ApplicationProperties properties = new ApplicationProperties();

                properties.Map[AmqpClientConstants.ManagementOperationKey] = this.md.Operation.Name;
                // generate message sections containing the arguments
                // convert custom-type parameters if needed
                object  bodyValue = null;
                AmqpMap bodyMap   = null;

                for (int i = 0; i < this.argCount; i++)
                {
                    ManagementParamAttribute paramAttribute = this.md.Parameters[i];
                    object value = SerializationHelper.ToAmqp(this.md.ParameterTypes[i].Serializable, this.mcm.InArgs[i]);

                    if (paramAttribute.Location == ManagementParamLocation.ApplicationProperties)
                    {
                        properties.Map[paramAttribute.Name] = value;
                    }
                    else if (paramAttribute.Location == ManagementParamLocation.MapBody)
                    {
                        if (bodyMap == null)
                        {
                            bodyMap = new AmqpMap();
                        }

                        bodyMap[new MapKey(paramAttribute.Name)] = value;
                    }
                    else
                    {
                        bodyValue = value;
                    }
                }

                // Upsert link RequestProperties to ApplicationProperties
                foreach (var requestProperty in requestLink.RequestProperties)
                {
                    properties.Map[requestProperty.Key] = requestProperty.Value;
                }

                this.request = AmqpMessage.Create(new AmqpValue {
                    Value = bodyMap ?? bodyValue
                });
                this.request.ApplicationProperties = properties;

                this.response = await requestLink.RequestAsync(request, TimeSpan.FromMinutes(1));

                int    statusCode        = (int)this.response.ApplicationProperties.Map[AmqpClientConstants.ResponseStatusCode];
                string statusDescription = (string)this.response.ApplicationProperties.Map[AmqpClientConstants.ResponseStatusDescription];

                if (statusCode != (int)AmqpResponseStatusCode.Accepted && statusCode != (int)AmqpResponseStatusCode.OK)
                {
                    AmqpSymbol errorCondition = AmqpExceptionHelper.GetResponseErrorCondition(this.response, (AmqpResponseStatusCode)statusCode);
                    Error      error          = new Error {
                        Condition = errorCondition, Description = statusDescription
                    };
                    throw new AmqpException(error);
                }

                object returnValue = null;

                if (this.response.ValueBody != null)
                {
                    returnValue = this.response.ValueBody.Value;
                }

                if (md.ReturnType.HasValue && returnValue != null)
                {
                    Type             expected     = md.ReturnType.Type;
                    SerializableType serializable = md.ReturnType.Serializable;
                    if (serializable == null)
                    {
                        // must be a generic parameter
                        expected     = mcm.GenericTypes[md.ReturnType.Type.GenericParameterPosition];
                        serializable = expected.GetSerializable();
                    }

                    returnValue = SerializationHelper.FromAmqp(serializable, returnValue);
                    if (!expected.IsAssignableFrom(returnValue.GetType()))
                    {
                        throw new InvalidOperationException($"Return type mismatch in {mcm.MethodBase.Name}. Expect {expected.Name} Actual {returnValue.GetType().Name}");
                    }
                }

                return(returnValue);
            }
Esempio n. 34
0
 public static string NullSerializer(SerializableType type, string propertyName)
 {
     return($"The property {propertyName} is marked with the Serializable attribute of type {type} but no implementation of a Serializer was provided");
 }
        public virtual void Export(TextWriter writer, int intent)
        {
            if (IsSerializable)
            {
                writer.WriteIndent(intent);
                writer.WriteLine("[{0}]", ScriptExportAttribute.SerializableName);
            }

            writer.WriteIndent(intent);
            writer.Write("{0} {1} {2}", Keyword, IsStruct ? "struct" : "class", TypeName);
            if (Base != null && !SerializableType.IsBasic(Base.Namespace, Base.NestedName))
            {
                writer.Write(" : {0}", Base.GetTypeNestedName(DeclaringType));
            }
            writer.WriteLine();
            writer.WriteIndent(intent++);
            writer.WriteLine('{');

            foreach (ScriptExportType nestedType in NestedTypes)
            {
                nestedType.Export(writer, intent);
                writer.WriteLine();
            }

            foreach (ScriptExportEnum nestedEnum in NestedEnums)
            {
                nestedEnum.Export(writer, intent);
                writer.WriteLine();
            }

            foreach (ScriptExportDelegate @delegate in NestedDelegates)
            {
                @delegate.Export(writer, intent);
            }
            if (NestedDelegates.Count > 0)
            {
                writer.WriteLine();
            }

            if (Constructor != null)
            {
                Constructor.Export(writer, intent);
                writer.WriteLine();
            }
            foreach (ScriptExportMethod method in Methods)
            {
                method.Export(writer, intent);
                writer.WriteLine();
            }
            foreach (ScriptExportProperty property in Properties)
            {
                property.Export(writer, intent);
            }
            if (Properties.Count > 0)
            {
                writer.WriteLine();
            }
            foreach (ScriptExportField field in Fields)
            {
                field.Export(writer, intent);
            }

            writer.WriteIndent(--intent);
            writer.WriteLine('}');
        }
		public void ShouldDeSerializeASerializableType()
		{
			SerializableType type = new SerializableType();
			type.Field = 1;
			string typeRepresentation = GenericSerializer.Serialize<SerializableType>(type);

			SerializableType type1 = GenericSerializer.Deserialize<SerializableType>(typeRepresentation);

			Assert.AreEqual(type.Field, type1.Field, "Not Equal");
		}
Esempio n. 37
0
        public byte[] InvokeServerMethod(out byte[] retChangedObjects, Guid version, SerializableType type, int ID, string method, SerializableType[] parameterTypes, byte[] parameter, byte[] changedObjects, ObjectNotificationRequest[] notificationRequests)
        {
            if (type == null) throw new ArgumentNullException("type");

            var req = InitializeRequest(InvokeServerMethodUri);
            using (var reqStream = req.GetRequestStream())
            using (var reqWriter = _writerFactory.Invoke(new BinaryWriter(reqStream)))
            {
                reqWriter.Write(version);
                reqWriter.Write(type);
                reqWriter.Write(ID);
                reqWriter.Write(method);
                reqWriter.Write(parameterTypes);
                reqWriter.Write(parameter);
                reqWriter.Write(changedObjects);
                reqWriter.Write(notificationRequests);
            }
            try
            {
                using (var response = req.GetResponse())
                using (var input = response.GetResponseStream())
                using (var reader = _readerFactory.Invoke(new BinaryReader(input)))
                {
                    reader.Read(out retChangedObjects);
                    return reader.ReadByteArray();
                }
            }
            catch (WebException ex)
            {
                var errorMsg = String.Format("Error when accessing server({0}): {1}: {2}", InvokeServerMethodUri, ex.Status, ex.Response);
                Log.Error(errorMsg);
                throw new ApplicationException(errorMsg, ex);
            }
        }
Esempio n. 38
0
        public byte[] GetListOf(Guid version, SerializableType type, int ID, string property)
        {
            if (type == null) throw new ArgumentNullException("type");
            if (String.IsNullOrEmpty(property)) throw new ArgumentNullException("property");

            return MakeRequest(GetListOfUri,
                reqStream =>
                {
                    reqStream.Write(version);
                    reqStream.Write(type);
                    reqStream.Write(ID);
                    reqStream.Write(property);
                    reqStream.WriteRaw(Encoding.ASCII.GetBytes("\n"));// required for basic.authenticated POST to apache
                });
        }
Esempio n. 39
0
        private static void GenerateEngineStruct(TypeTreeContext context, SerializableType origin, string name)
        {
            switch (origin.Name)
            {
            case SerializableType.Vector2Name:
                Vector2f.GenerateTypeTree(context, name);
                break;

            case SerializableType.Vector2IntName:
                Vector2i.GenerateTypeTree(context, name);
                break;

            case SerializableType.Vector3Name:
                Vector3f.GenerateTypeTree(context, name);
                break;

            case SerializableType.Vector3IntName:
                Vector3i.GenerateTypeTree(context, name);
                break;

            case SerializableType.Vector4Name:
                Vector4f.GenerateTypeTree(context, name);
                break;

            case SerializableType.RectName:
                Rectf.GenerateTypeTree(context, name);
                break;

            case SerializableType.BoundsName:
                AABB.GenerateTypeTree(context, name);
                break;

            case SerializableType.BoundsIntName:
                AABBi.GenerateTypeTree(context, name);
                break;

            case SerializableType.QuaternionName:
                Quaternionf.GenerateTypeTree(context, name);
                break;

            case SerializableType.Matrix4x4Name:
                Matrix4x4f.GenerateTypeTree(context, name);
                break;

            case SerializableType.ColorName:
                ColorRGBAf.GenerateTypeTree(context, name);
                break;

            case SerializableType.Color32Name:
                ColorRGBA32.GenerateTypeTree(context, name);
                break;

            case SerializableType.LayerMaskName:
                LayerMask.GenerateTypeTree(context, name);
                break;

            case SerializableType.AnimationCurveName:
                AnimationCurveTpl <Float> .GenerateTypeTree(context, name, Float.GenerateTypeTree);

                break;

            case SerializableType.GradientName:
                Gradient.GenerateTypeTree(context, name);
                break;

            case SerializableType.RectOffsetName:
                RectOffset.GenerateTypeTree(context, name);
                break;

            case SerializableType.GUIStyleName:
                GUIStyle.GenerateTypeTree(context, name);
                break;

            case SerializableType.PropertyNameName:
                PropertyName.GenerateTypeTree(context, name);
                break;

            default:
                throw new Exception($"Unknown engine struct {origin.Name}");
            }
        }
Esempio n. 40
0
        private void BuildWriteMethods(SerializableType target, TravellerContext context)
        {
            var typedMethodBuilder = _travelWriteMethod;
            var writeBuilder = new DynamicWriteTravellerBuilder(typedMethodBuilder, target, context);
            writeBuilder.BuildTravelWriteMethod();

            var untypedMethodBuilder = _classBuilder.DefineOverloadMethod("Travel", typeof(void), new[] { typeof(IWriteVisitor), typeof(object) });
            var il = untypedMethodBuilder.IL;
            il.LoadThis();
            il.Var.Load(new MethodArgILCodeVariable(1, typeof(IWriteVisitor)));
            il.Var.Load(new MethodArgILCodeVariable(2, typeof(object)));
            il.Cast(target.Type);
            il.Call(typedMethodBuilder.Method);
            il.Return();
        }
Esempio n. 41
0
 public override void SetUp()
 {
     base.SetUp();
     t = iftFactory(typeof(TestDataObject)).ToSerializableType();
 }
Esempio n. 42
0
        public override void Emit(StringBuilder builder)
        {
            //Class time! (or record lol)
            AppendGeneratedCodeAttribute(builder);
            builder.Append($"[{nameof(DataContractAttribute)}]{Environment.NewLine}");
            if (ClassAccessibility == Accessibility.NotApplicable)
            {
                builder.Append($"partial {ComputeClassOrRecordKeyword()} {ComputeContextTypeName()} : {SerializableType.GetFriendlyName()}, {nameof(IGGDBFSerializable)}");
            }
            else
            {
                builder.Append($"{ClassAccessibility.ToString().ToLower()} partial {ComputeClassOrRecordKeyword()} {ComputeContextTypeName()} : {SerializableType.GetFriendlyName()}, {nameof(IGGDBFSerializable)}");
            }

            CalculatePossibleTypeConstraints(OriginalContextSymbol, builder);

            builder.Append($"{Environment.NewLine}{{");

            //We do this to support nav properties in the base type
            var typeToParse = SerializableType;

            do
            {
                EmitOverridenNavigationProperties(builder, typeToParse);
                typeToParse = typeToParse.BaseType;
            } while (typeToParse != null);


            int propCount = 1;

            foreach (var prop in EnumerateForeignCollectionProperties())
            {
                INamedTypeSymbol collectionElementType = (INamedTypeSymbol)ComputeCollectionElementType(prop);
                string           backingPropertyName   = ComputeCollectionPropertyBackingFieldName(prop);

                //We must emit a serializable backing field for the collection property
                builder.Append($"[{nameof(DataMemberAttribute)}({nameof(DataMemberAttribute.Order)} = {propCount})]{Environment.NewLine}");
                builder.Append($"public {nameof(SerializableGGDBFCollection<int, object>)}<{new TablePrimaryKeyParser().Parse(collectionElementType, true)}, {collectionElementType.GetFriendlyName()}> {backingPropertyName};{Environment.NewLine}{Environment.NewLine}");

                //The concept of returning the base property getter if the derived field is null for cases where we want to access the collection
                //during the process of serializing the real model type to the new model type. We need to access the collection and process it
                //for keys to build the serializable collection.
                //get => _ModelCollection != null ? _ModelCollection.Load(TestContext.Instance.Test4Datas) : base.ModelCollection;
                builder.Append($"[{nameof(IgnoreDataMemberAttribute)}]{Environment.NewLine}");
                builder.Append($"public override {prop.Type.Name}<{collectionElementType.GetFriendlyName()}> {prop.Name} {Environment.NewLine}{{ get => {backingPropertyName} != null ? {backingPropertyName}.{nameof(SerializableGGDBFCollection<int, object>.Load)}({OriginalContextSymbol.GetFriendlyName()}.Instance.{new TableNameParser().Parse(collectionElementType)}) : base.{prop.Name};{Environment.NewLine}");

                builder.Append($"}}{Environment.NewLine}");

                propCount++;
            }

            //This is for collections of owned types
            foreach (var prop in EnumerateOwnedTypeForeignCollectionProperties())
            {
                INamedTypeSymbol collectionElementType = (INamedTypeSymbol)ComputeCollectionElementType(prop);
                string           backingPropertyName   = ComputeCollectionPropertyBackingFieldName(prop);

                //We must emit a serializable backing field for the collection property
                builder.Append($"[{nameof(DataMemberAttribute)}({nameof(DataMemberAttribute.Order)} = {propCount})]{Environment.NewLine}");
                builder.Append($"public {ComputeOwnedTypeName(collectionElementType)}[] {backingPropertyName};{Environment.NewLine}{Environment.NewLine}");

                //Just return backing field or base prop getter if null (could be null too)
                builder.Append($"[{nameof(IgnoreDataMemberAttribute)}]{Environment.NewLine}");
                builder.Append($"public override {prop.Type.Name}<{collectionElementType.GetFriendlyName()}> {prop.Name} {Environment.NewLine}{{ get => {backingPropertyName} != null ? {backingPropertyName} : base.{prop.Name};{Environment.NewLine}");

                builder.Append($"}}{Environment.NewLine}");

                propCount++;
            }

            if (!SerializableType.IsRecord)
            {
                builder.Append($"public {ClassName}() {{ }}{Environment.NewLine}");
            }

            EmitSerializableInitializeMethod(builder);

            builder.Append($"}}");

            //For all owned types we should maybe generate keys
            if (SerializableType.HasOwnedTypePropertyWithForeignKey())
            {
                foreach (var prop in EnumerateOwnedTypesWithForeignKeys())
                {
                    //TODO: If multiple owned types with generic type parameters are used in the same table then this won't work.
                    INamedTypeSymbol             ownedType = (INamedTypeSymbol)(prop.IsICollectionType() ? ((INamedTypeSymbol)prop.Type).TypeArguments.First() : prop.Type);
                    SerializableTypeClassEmitter emitter   = new SerializableTypeClassEmitter(ComputeOwnedTypeName(ownedType, true), ownedType, OriginalContextSymbol, ClassAccessibility);

                    builder.Append($"{Environment.NewLine}{Environment.NewLine}");
                    emitter.Emit(builder);
                }
            }
        }
		public void ShouldSerializeASerializableType()
		{
			SerializableType type = new SerializableType();
			type.Field = 1;

			string typeRepresentation = GenericSerializer.Serialize<SerializableType>(type);

			Assert.IsTrue(!String.IsNullOrEmpty(typeRepresentation), "Serialization failed");
		}
Esempio n. 44
0
        public byte[] GetList(Guid version, SerializableType type, int maxListCount, bool eagerLoadLists, SerializableExpression[] filter, OrderByContract[] orderBy)
        {
            if (type == null) throw new ArgumentNullException("type");

            return MakeRequest(GetListUri,
                reqStream =>
                {
                    reqStream.Write(version);
                    reqStream.Write(type);
                    reqStream.Write(maxListCount);
                    reqStream.Write(eagerLoadLists);
                    reqStream.Write(filter);
                    reqStream.Write(orderBy);
                    reqStream.WriteRaw(Encoding.ASCII.GetBytes("\n"));// required for basic.authenticated POST to apache
                });
        }