예제 #1
0
        private static object BindList(string ParentKey, string ParentType, Dictionary <string, string> Parameters, Dictionary <string, ParameterBinding> Bindings, DataContext dataContext)
        {
            ParameterBinding binding;

            if (!Bindings.TryGetValue(ParentKey, out binding))
            {
                return(null);
            }

            string BindingString = binding.Binding;

            if (string.IsNullOrWhiteSpace(BindingString))
            {
                return(null);
            }

            Type keytype        = Data.TypeCache.GetType(binding.KeyType);
            Type collectiontype = Data.TypeCache.GetType(ParentType);

            try
            {
                var value = Lib.Helper.JsonHelper.Deserialize(BindingString, collectiontype);
                if (value != null)
                {
                    var list  = value as System.Collections.IList;
                    var count = list.Count;
                    for (int i = 0; i < count; i++)
                    {
                        var item = list[i];
                        if (item != null)
                        {
                            object KeyBack;
                            string stritem = item.ToString();
                            if (IsValueBinding(stritem))
                            {
                                string key = GetBindingKey(stritem);
                                KeyBack = GetValue(key, binding.KeyType, dataContext);
                                list[i] = TypeHelper.ChangeType(KeyBack, keytype);
                            }
                        }
                    }
                    return(list);
                }
            }
            catch (Exception)
            {
            }


            string bkey      = GetBindingKey(BindingString);
            var    valueback = GetValue(bkey, binding.FullTypeName, dataContext);

            if (valueback != null && valueback.GetType() == collectiontype)
            {
                return(valueback);
            }

            return(null);
        }
예제 #2
0
        public Type EmitEntityType(string entityTypeName, IDictionary <string, Type> entityPropertyDic, Type parentInterfaceType)
        {
            string      name    = string.Format("{0}.{1}", this.assemblyName, entityTypeName);
            TypeBuilder builder = this.moduleBuilder.DefineType(name, TypeAttributes.Serializable | TypeAttributes.Public);

            if (parentInterfaceType != null)
            {
                builder.AddInterfaceImplementation(parentInterfaceType);
            }
            List <FieldBuilder> list = new List <FieldBuilder>();

            foreach (string str2 in entityPropertyDic.Keys)
            {
                PropertyInfo property = parentInterfaceType.GetProperty(str2);
                Type         type     = entityPropertyDic[str2];
                FieldBuilder item     = builder.DefineField("m_" + str2, type, FieldAttributes.Private);
                list.Add(item);
                item.SetConstant(TypeHelper.ChangeType(type, TypeHelper.GetDefaultValue(type)));
                PropertyBuilder builder3       = builder.DefineProperty(str2, PropertyAttributes.None, type, null);
                MethodBuilder   methodInfoBody = builder.DefineMethod("get", MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.Public, type, Type.EmptyTypes);
                ILGenerator     generator      = methodInfoBody.GetILGenerator();
                generator.Emit(OpCodes.Ldarg_0);
                generator.Emit(OpCodes.Ldfld, item);
                generator.Emit(OpCodes.Ret);
                if ((property != null) && property.CanRead)
                {
                    MethodInfo getMethod = property.GetGetMethod();
                    builder.DefineMethodOverride(methodInfoBody, getMethod);
                }
                MethodBuilder builder5   = builder.DefineMethod("set", MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.Public, null, new Type[] { type });
                ILGenerator   generator2 = builder5.GetILGenerator();
                generator2.Emit(OpCodes.Ldarg_0);
                generator2.Emit(OpCodes.Ldarg_1);
                generator2.Emit(OpCodes.Stfld, item);
                generator2.Emit(OpCodes.Ret);
                if ((property != null) && property.CanWrite)
                {
                    MethodInfo setMethod = property.GetSetMethod();
                    builder.DefineMethodOverride(builder5, setMethod);
                }
                builder3.SetGetMethod(methodInfoBody);
                builder3.SetSetMethod(builder5);
            }
            ILGenerator iLGenerator = builder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes).GetILGenerator();

            iLGenerator.Emit(OpCodes.Ldarg_0);
            iLGenerator.Emit(OpCodes.Call, typeof(object).GetConstructor(new Type[0]));
            foreach (FieldBuilder builder2 in list)
            {
                if (builder2.FieldType == typeof(string))
                {
                    iLGenerator.Emit(OpCodes.Ldarg_0);
                    iLGenerator.Emit(OpCodes.Ldstr, "");
                    iLGenerator.Emit(OpCodes.Stfld, builder2);
                }
            }
            iLGenerator.Emit(OpCodes.Ret);
            return(builder.CreateType());
        }
        public void ChangeType_ReturnsNullIfTypeAllowsNulls()
        {
            // Act
            var actual = TypeHelper.ChangeType(null, typeof(int?));

            // Assert
            Assert.Null(actual);
        }
예제 #4
0
 protected void OnChangeEventArgs(ChangeEventArgs input)
 {
     Value = (TValue)TypeHelper.ChangeType(input.Value, typeof(TValue));
     if (ValueChanged.HasDelegate)
     {
         _ = ValueChanged.InvokeAsync(Value);
     }
     SetFieldValue(Value);
 }
        public void ChangeType_ReturnsValueIfTypesMatch()
        {
            // Act
            var actual = TypeHelper.ChangeType(3, typeof(int));

            // Assert
            Assert.Equal(typeof(int), actual.GetType());
            Assert.Equal(3, actual);
        }
        public void ChangeType_ReturnsConvertedTypeWhenThereIsAConverterFromTheType()
        {
            // Act
            var actual = TypeHelper.ChangeType("3", typeof(int));

            // Assert
            Assert.Equal(typeof(int), actual.GetType());
            Assert.Equal(3, actual);
        }
예제 #7
0
        /// <summary>
        /// copy object to another object
        /// </summary>
        /// <param name="copyFrom"></param>
        /// <param name="instance"></param>
        /// <returns></returns>
        private static object Copy(object copyFrom, object instance)
        {
            if (copyFrom == null)
            {
                return(instance);
            }

            #region map method to Action/Func field

            //GetMethods doesn't return extension method.
            var fromMethods = copyFrom.GetType().GetMethods().ToList();
            //var extensionMethods = GetExtensionMethods(typeof(KscriptContextExtension).Assembly,copyFrom.GetType());
            //fromMethods.AddRange(extensionMethods);

            var fields = instance.GetType().GetFields().ToList();
            foreach (var field in fields)
            {
                var matchMethod = fromMethods.Find(m => IsSameMethod(field, m));
                if (matchMethod == null)
                {
                    continue;
                }

                var delegateMethod = matchMethod.CreateDelegate(field.FieldType, copyFrom);
                field.SetValue(instance, delegateMethod);
            }
            #endregion

            #region map properties
            var fromProperties = copyFrom.GetType().GetProperties().ToList();
            var properties     = instance.GetType().GetProperties().ToList();
            foreach (var prop in properties)
            {
                var matchProp = fromProperties.Find(p => p.Name.Equals(prop.Name, StringComparison.OrdinalIgnoreCase));
                if (matchProp == null)
                {
                    continue;
                }
                var value = matchProp.GetValue(copyFrom);
                if (prop.PropertyType == matchProp.PropertyType)
                {
                    prop.SetValue(instance, value);
                }
                else
                {
                    var matchPropertyInstance = Activator.CreateInstance(prop.PropertyType);
                    matchPropertyInstance = Copy(value, matchPropertyInstance);
                    //need convert type
                    prop.SetValue(instance, TypeHelper.ChangeType(matchPropertyInstance, prop.PropertyType));
                }
            }
            #endregion


            return(TypeHelper.ChangeType(instance, instance.GetType()));
        }
        public T GetValue <T>(string name)
        {
            object val = GetValue(name);

            if (val != null)
            {
                return(TypeHelper.ChangeType <T>(val));
            }
            return(default(T));
        }
예제 #9
0
        /// <summary>
        /// This type supports the Fluorine infrastructure and is not intended to be used directly from your code.
        /// </summary>
        /// <param name="context">An ITypeDescriptorContext that provides a format context.</param>
        /// <param name="culture">A CultureInfo object. If a null reference (Nothing in Visual Basic) is passed, the current culture is assumed.</param>
        /// <param name="value">The Object to convert.</param>
        /// <param name="destinationType">The Type to convert the value parameter to.</param>
        /// <returns>An Object that represents the converted value.</returns>
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == null)
            {
                throw new ArgumentNullException("destinationType");
            }

            if (destinationType.IsArray)
            {
                return((value as JavaScriptArray).ToArray());
            }
            if (destinationType == typeof(ArrayList))
            {
                return(value as ArrayList);
            }
            if (destinationType == typeof(IList))
            {
                return(value as IList);
            }
            //generic interface
            Type typeGenericICollection = destinationType.GetInterface("System.Collections.Generic.ICollection`1");

            if (typeGenericICollection != null)
            {
                object     obj             = TypeHelper.CreateInstance(destinationType);
                MethodInfo miAddCollection = destinationType.GetMethod("Add");
                if (miAddCollection != null)
                {
                    ParameterInfo[] parameters = miAddCollection.GetParameters();
                    if (parameters != null && parameters.Length == 1)
                    {
                        Type  parameterType = parameters[0].ParameterType;
                        IList list          = (IList)value;
                        for (int i = 0; i < list.Count; i++)
                        {
                            miAddCollection.Invoke(obj, new object[] { TypeHelper.ChangeType(list[i], parameterType) });
                        }
                        return(obj);
                    }
                }
            }
            Type typeIList = destinationType.GetInterface("System.Collections.IList");

            if (typeIList != null)
            {
                object obj  = TypeHelper.CreateInstance(destinationType);
                IList  list = obj as IList;
                for (int i = 0; i < (value as IList).Count; i++)
                {
                    list.Add((value as IList)[i]);
                }
                return(obj);
            }
            return(base.ConvertTo(context, culture, value, destinationType));
        }
예제 #10
0
 private static void ConfigObject(XmlNode objNode, ref object target)
 {
     foreach (XmlAttribute attribute in objNode.Attributes)
     {
         ReflectionHelper.SetProperty(target, attribute.Name, attribute.Value);
     }
     foreach (XmlNode node in objNode.ChildNodes)
     {
         if (node.Attributes["value"] != null)
         {
             ReflectionHelper.SetProperty(target, node.Attributes["name"].Value, node.Attributes["value"].Value);
         }
         else
         {
             XmlNode node2 = node.ChildNodes[0];
             if (node2.Name == "object")
             {
                 object obj2 = Activator.CreateInstance(ReflectionHelper.GetType(node2.Attributes["type"].Value));
                 ConfigObject(node2, ref obj2);
                 ReflectionHelper.SetProperty(target, node.Attributes["name"].Value, obj2);
             }
             else if (node2.Name == "list")
             {
                 object obj4;
                 Type   type  = ReflectionHelper.GetType(node2.Attributes["element-type"].Value);
                 Type   type3 = typeof(List <>).MakeGenericType(new Type[] { type });
                 object obj3  = Activator.CreateInstance(type3);
                 if (TypeHelper.IsSimpleType(type))
                 {
                     foreach (XmlNode node3 in node2.ChildNodes)
                     {
                         obj4 = TypeHelper.ChangeType(type, node3.InnerText);
                         type3.GetMethod("Add").Invoke(obj3, new object[] { obj4 });
                     }
                 }
                 else
                 {
                     foreach (XmlNode node3 in node2.ChildNodes)
                     {
                         Type type4 = type;
                         if (node3.Attributes["type"] != null)
                         {
                             type4 = ReflectionHelper.GetType(node3.Attributes["type"].Value);
                         }
                         obj4 = Activator.CreateInstance(type4);
                         ConfigObject(node3, ref obj4);
                         type3.GetMethod("Add").Invoke(obj3, new object[] { obj4 });
                     }
                 }
                 ReflectionHelper.SetProperty(target, node.Attributes["name"].Value, obj3);
             }
         }
     }
 }
예제 #11
0
 protected override void FormItem_OnReset(object value, bool requireRerender)
 {
     if (value == null)
     {
         SelectedValue = default;
     }
     else
     {
         SelectedValue = (TValue)TypeHelper.ChangeType(value, typeof(TValue));
     }
 }
예제 #12
0
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            object obj2;
            IList  list;
            int    num;

            if (destinationType == null)
            {
                throw new ArgumentNullException("destinationType");
            }
            if (destinationType.IsArray)
            {
                return((value as JavaScriptArray).ToArray());
            }
            if (destinationType == typeof(ArrayList))
            {
                return(value as ArrayList);
            }
            if (destinationType == typeof(IList))
            {
                return(value as IList);
            }
            if (destinationType.GetInterface("System.Collections.Generic.ICollection`1") != null)
            {
                obj2 = TypeHelper.CreateInstance(destinationType);
                MethodInfo method = destinationType.GetMethod("Add");
                if (method != null)
                {
                    ParameterInfo[] parameters = method.GetParameters();
                    if ((parameters != null) && (parameters.Length == 1))
                    {
                        Type parameterType = parameters[0].ParameterType;
                        list = (IList)value;
                        for (num = 0; num < list.Count; num++)
                        {
                            method.Invoke(obj2, new object[] { TypeHelper.ChangeType(list[num], parameterType) });
                        }
                        return(obj2);
                    }
                }
            }
            if (destinationType.GetInterface("System.Collections.IList") != null)
            {
                obj2 = TypeHelper.CreateInstance(destinationType);
                list = obj2 as IList;
                for (num = 0; num < (value as IList).Count; num++)
                {
                    list.Add((value as IList)[num]);
                }
                return(obj2);
            }
            return(base.ConvertTo(context, culture, value, destinationType));
        }
예제 #13
0
        /// <summary>
        /// This type supports the Fluorine infrastructure and is not intended to be used directly from your code.
        /// </summary>
        /// <param name="context">An ITypeDescriptorContext that provides a format context.</param>
        /// <param name="culture">A CultureInfo object. If a null reference (Nothing in Visual Basic) is passed, the current culture is assumed.</param>
        /// <param name="value">The Object to convert.</param>
        /// <param name="destinationType">The Type to convert the value parameter to.</param>
        /// <returns>An Object that represents the converted value.</returns>
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == null)
            {
                throw new ArgumentNullException("destinationType");
            }
            JavaScriptObject javaScriptObject = value as JavaScriptObject;

            if (destinationType == typeof(object) || destinationType == typeof(JavaScriptObject))
            {
                return(value);
            }
            if (destinationType == typeof(Hashtable))
            {
                return(new Hashtable(javaScriptObject));
            }
            if (destinationType == typeof(ASObject))
            {
                return(new ASObject(javaScriptObject));
            }

            if (ReflectionUtils.ImplementsInterface(destinationType, "System.Collections.Generic.IDictionary`2"))
            {
                return(TypeHelper.ChangeType(javaScriptObject, destinationType));
            }
            if (ReflectionUtils.ImplementsInterface(destinationType, "System.Collections.IDictionary"))
            {
                return(TypeHelper.ChangeType(javaScriptObject, destinationType));
            }

            object newObject = Activator.CreateInstance(destinationType);

#if !(NET_1_1)
            foreach (KeyValuePair <string, object> entry in value as JavaScriptObject)
#else
            foreach (DictionaryEntry entry in value as JavaScriptObject)
#endif
            {
                string     memberName = entry.Key as string;
                MemberInfo memberInfo = ReflectionUtils.GetMember(destinationType, memberName, MemberTypes.Field | MemberTypes.Property);
                if (memberInfo != null)
                {
                    object memberValue = TypeHelper.ChangeType(entry.Value, ReflectionUtils.GetMemberUnderlyingType(memberInfo));
                    ReflectionUtils.SetMemberValue(memberInfo, newObject, memberValue);
                }
            }

            return(newObject);
        }
예제 #14
0
        public void ChangeTypeTest()
        {
            var test = new MockGenericType
            {
                EnumMockEnum = EnumMockEnum.EnumMockEnum
            };

            var result = TypeHelper.ChangeType(nameof(EnumMockEnum.EnumMockEnum2), test.EnumMockEnum.GetType());

            Assert.Equal(EnumMockEnum.EnumMockEnum2, result);

            var result2 = TypeHelper.ChangeType(EnumMockEnum.EnumMockEnum2, test.EnumMockEnum.GetType());

            Assert.Equal(EnumMockEnum.EnumMockEnum2, result2);
        }
예제 #15
0
 protected virtual void OnChangeEventArgs(ChangeEventArgs input)
 {
     try
     {
         Value = (TValue)TypeHelper.ChangeType(input.Value, typeof(TValue));
     }
     catch (FormatException) when(ThrowOnInvalidValue)
     {
     }
     if (ValueChanged.HasDelegate)
     {
         _ = ValueChanged.InvokeAsync(Value);
     }
     SetFieldValue(Value, true);
 }
예제 #16
0
        private CheckBoxOption <TModel, TValue> ConvertModelItem(TModel modelItem)
        {
            if (!ModelItemIsSimpleType)
            {
                return(null);
            }
            Status status = CheckBox.Status.Checked;

            if (IsChecked != null)
            {
                status = IsChecked(modelItem) ? Status.Checked : Status.UnChecked;
            }

            if (IsIndeterminate != null)
            {
                status = IsIndeterminate(modelItem) ? Status.Indeterminate : Status.UnChecked;
            }
            if (SelectedItems != null)
            {
                status = SelectedItems.Contains(modelItem) ? Status.Checked : Status.UnChecked;
            }

            var label = string.Empty;

            if (Label != null)
            {
                label = Label(modelItem);
            }
            else if (ModelItemIsSimpleType)
            {
                label = Convert.ToString(modelItem);
            }
            var option = new CheckBoxOption <TModel, TValue>()
            {
                Status     = status,
                Value      = Value == null ? (TValue)TypeHelper.ChangeType(label, typeof(TValue)) : Value(modelItem),
                IsDisabled = false,
                Label      = label,
                Model      = modelItem
            };

            return(option);
        }
예제 #17
0
 protected override void FormItem_OnReset(object value, bool requireRerender)
 {
     if (value == null)
     {
         Value = default;
     }
     else
     {
         Value = (TValue)TypeHelper.ChangeType(value, typeof(TValue));
     }
     if (ValueChanged.HasDelegate)
     {
         _ = ValueChanged.InvokeAsync(Value);
     }
     else
     {
         StateHasChanged();
     }
 }
예제 #18
0
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == null)
            {
                throw new ArgumentNullException("destinationType");
            }
            JavaScriptObject d = value as JavaScriptObject;

            if ((destinationType == typeof(object)) || (destinationType == typeof(JavaScriptObject)))
            {
                return(value);
            }
            if (destinationType == typeof(Hashtable))
            {
                return(new Hashtable(d));
            }
            if (destinationType == typeof(ASObject))
            {
                return(new ASObject(d));
            }
            if (ReflectionUtils.ImplementsInterface(destinationType, "System.Collections.Generic.IDictionary`2"))
            {
                return(TypeHelper.ChangeType(d, destinationType));
            }
            if (ReflectionUtils.ImplementsInterface(destinationType, "System.Collections.IDictionary"))
            {
                return(TypeHelper.ChangeType(d, destinationType));
            }
            object target = Activator.CreateInstance(destinationType);

            foreach (KeyValuePair <string, object> pair in value as JavaScriptObject)
            {
                string     key    = pair.Key;
                MemberInfo member = ReflectionUtils.GetMember(destinationType, key, MemberTypes.Property | MemberTypes.Field);
                if (member != null)
                {
                    object obj4 = TypeHelper.ChangeType(pair.Value, ReflectionUtils.GetMemberUnderlyingType(member));
                    ReflectionUtils.SetMemberValue(member, target, obj4);
                }
            }
            return(target);
        }
예제 #19
0
 public void ResultReceived(IPendingServiceCall call)
 {
     //Unwrap flex messages
     if (call.Result is ErrorMessage)
     {
         StatusFunction statusFunction = _responder.GetType().GetProperty("Status").GetValue(_responder, null) as StatusFunction;
         if (statusFunction != null)
         {
             statusFunction(new Fault(call.Result as ErrorMessage));
         }
     }
     else if (call.Result is AcknowledgeMessage)
     {
         AcknowledgeMessage ack            = call.Result as AcknowledgeMessage;
         Delegate           resultFunction = _responder.GetType().GetProperty("Result").GetValue(_responder, null) as Delegate;
         if (resultFunction != null)
         {
             ParameterInfo[] arguments = resultFunction.Method.GetParameters();
             object          result    = TypeHelper.ChangeType(ack.body, arguments[0].ParameterType);
             resultFunction.DynamicInvoke(result);
         }
     }
     else if (call.IsSuccess)
     {
         Delegate resultFunction = _responder.GetType().GetProperty("Result").GetValue(_responder, null) as Delegate;
         if (resultFunction != null)
         {
             ParameterInfo[] arguments = resultFunction.Method.GetParameters();
             object          result    = TypeHelper.ChangeType(call.Result, arguments[0].ParameterType);
             resultFunction.DynamicInvoke(result);
         }
     }
     else
     {
         StatusFunction statusFunction = _responder.GetType().GetProperty("Status").GetValue(_responder, null) as StatusFunction;
         if (statusFunction != null)
         {
             statusFunction(new Fault(call.Result));
         }
     }
 }
예제 #20
0
        public async Task IntegrationTestApiServiceWorkflowClientCreateAndAction()
        {
            using (var client = new WorkflowClient(BaseApiAddress))
            {
                var createRequest =
                    new CreateWorkflowRequestContract <PhoneCallWorkflow>(ArgumentContract.Create("CanDial", true));

                var createResponse = await client.CreateAsync(createRequest);

                var workflowId = createResponse.WorkflowId;

                await client.ActionAsync(new ActionWorkflowRequestContract(workflowId, "Call Dialed"));

                await client.ActionAsync(new ActionWorkflowRequestContract(workflowId, "No Answer"));

                var waitResponse = await client.WaitAsync(workflowId);

                Assert.AreEqual(
                    PhoneStates.Disconnected,
                    TypeHelper.ChangeType <PhoneStates>(waitResponse.WorkflowState));
                Assert.AreEqual("Hello World!", waitResponse.GetArgument <string>("Message"));
            }
        }
예제 #21
0
        protected override void FormItem_OnReset(object value, bool requireRerender)
        {
            RequireRender = true;
            if (CheckBoxGroup != null)
            {
                if (CheckBoxGroup.SelectedItems.Contains(TypeHelper.ChangeType <TValue>(value)))
                {
                    Status = Status.Checked;
                }
                else
                {
                    Status = Status.UnChecked;
                }
                if (StatusChanged.HasDelegate)
                {
                    _ = StatusChanged.InvokeAsync(Status);
                }
                else
                {
                    CheckBoxGroup.MarkAsRequireRender();
                }
                return;
            }

            if (TypeHelper.Equal(Value, TypeHelper.ChangeType <TValue>(value)))
            {
                Status = Status.Checked;
            }
            else
            {
                Status = Status.UnChecked;
            }
            if (StatusChanged.HasDelegate)
            {
                _ = StatusChanged.InvokeAsync(Status);
            }
        }
예제 #22
0
 private void BeginResponseFlexCall(IAsyncResult ar)
 {
     try
     {
         AmfRequestData amfRequestData = ar.AsyncState as AmfRequestData;
         if (amfRequestData != null)
         {
             HttpWebResponse response = (HttpWebResponse)amfRequestData.Request.EndGetResponse(ar);
             if (response != null)
             {
                 //Get response and deserialize
                 Stream responseStream = response.GetResponseStream();
                 if (responseStream != null)
                 {
                     AMFDeserializer amfDeserializer = new AMFDeserializer(responseStream);
                     AMFMessage responseMessage = amfDeserializer.ReadAMFMessage();
                     AMFBody responseBody = responseMessage.GetBodyAt(0);
                     for (int i = 0; i < responseMessage.HeaderCount; i++)
                     {
                         AMFHeader header = responseMessage.GetHeaderAt(i);
                         if (header.Name == AMFHeader.RequestPersistentHeader)
                             _netConnection.AddHeader(header.Name, header.MustUnderstand, header.Content);
                     }
                     object message = responseBody.Content;
                     if (message is ErrorMessage)
                     {
                         /*
                         ASObject status = new ASObject();
                         status["level"] = "error";
                         status["code"] = "NetConnection.Call.Failed";
                         status["description"] = (result as ErrorMessage).faultString;
                         status["details"] = result;
                         _netConnection.RaiseNetStatus(status);
                         */
                         if (amfRequestData.Call != null)
                         {
                             PendingCall call = amfRequestData.Call;
                             call.Result = message;
                             call.Status = Messaging.Rtmp.Service.Call.STATUS_INVOCATION_EXCEPTION;
                             amfRequestData.Callback.ResultReceived(call);
                         }
                         if (amfRequestData.Responder != null)
                         {
                             StatusFunction statusFunction = amfRequestData.Responder.GetType().GetProperty("Status").GetValue(amfRequestData.Responder, null) as StatusFunction;
                             if (statusFunction != null)
                                 statusFunction(new Fault(message as ErrorMessage));
                         }
                     }
                     else if (message is AcknowledgeMessage)
                     {
                         AcknowledgeMessage ack = message as AcknowledgeMessage;
                         if (_netConnection.ClientId == null && ack.HeaderExists(MessageBase.FlexClientIdHeader))
                             _netConnection.SetClientId(ack.GetHeader(MessageBase.FlexClientIdHeader) as string);
                         if (amfRequestData.Call != null)
                         {
                             PendingCall call = amfRequestData.Call;
                             call.Result = ack.body;
                             call.Status = Messaging.Rtmp.Service.Call.STATUS_SUCCESS_RESULT;
                             amfRequestData.Callback.ResultReceived(call);
                         }
                         if (amfRequestData.Responder != null)
                         {
                             Delegate resultFunction = amfRequestData.Responder.GetType().GetProperty("Result").GetValue(amfRequestData.Responder, null) as Delegate;
                             if (resultFunction != null)
                             {
                                 ParameterInfo[] arguments = resultFunction.Method.GetParameters();
                                 object result = TypeHelper.ChangeType(ack.body, arguments[0].ParameterType);
                                 resultFunction.DynamicInvoke(result);
                             }
                         }
                     }
                 }
                 else
                     _netConnection.RaiseNetStatus("Could not aquire ResponseStream");
             }
             else
                 _netConnection.RaiseNetStatus("Could not aquire HttpWebResponse");
         }
     }
     catch (Exception ex)
     {
         _netConnection.RaiseNetStatus(ex);
     }
 }
예제 #23
0
        /// <summary>
        /// This type supports the infrastructure and is not intended to be used directly from your code.
        /// </summary>
        /// <param name="context">An ITypeDescriptorContext that provides a format context.</param>
        /// <param name="culture">A CultureInfo object. If a null reference (Nothing in Visual Basic) is passed, the current culture is assumed.</param>
        /// <param name="value">The Object to convert.</param>
        /// <param name="destinationType">The Type to convert the value parameter to.</param>
        /// <returns>An Object that represents the converted value.</returns>
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            ASObject aso = value as ASObject;

            if (!ReflectionUtils.IsInstantiatableType(destinationType))
            {
                return(null);
            }

            object instance = TypeHelper.CreateInstance(destinationType);

            if (instance != null)
            {
                foreach (string memberName in aso.Keys)
                {
                    object val = aso[memberName];
                    //MemberInfo mi = ReflectionUtils.GetMember(destinationType, key, MemberTypes.Field | MemberTypes.Property);
                    //if (mi != null)
                    //    ReflectionUtils.SetMemberValue(mi, result, aso[key]);

                    PropertyInfo propertyInfo = null;
                    try {
                        propertyInfo = destinationType.GetProperty(memberName);
                    } catch (AmbiguousMatchException) {
                        //To resolve the ambiguity, include BindingFlags.DeclaredOnly to restrict the search to members that are not inherited.
                        propertyInfo = destinationType.GetProperty(memberName, BindingFlags.DeclaredOnly | BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance);
                    }
                    if (propertyInfo != null)
                    {
                        try {
                            val = TypeHelper.ChangeType(val, propertyInfo.PropertyType);
                            if (propertyInfo.CanWrite && propertyInfo.GetSetMethod() != null)
                            {
                                if (propertyInfo.GetIndexParameters() == null || propertyInfo.GetIndexParameters().Length == 0)
                                {
                                    propertyInfo.SetValue(instance, val, null);
                                }
                                else
                                {
                                    string msg = __Res.GetString(__Res.Reflection_PropertyIndexFail, string.Format("{0}.{1}", destinationType.FullName, memberName));
                                    throw new FluorineException(msg);
                                }
                            }
                            else
                            {
                                //string msg = __Res.GetString(__Res.Reflection_PropertyReadOnly, string.Format("{0}.{1}", type.FullName, memberName));
                            }
                        } catch (Exception ex) {
                            string msg = __Res.GetString(__Res.Reflection_PropertySetFail, string.Format("{0}.{1}", destinationType.FullName, memberName), ex.Message);
                            throw new FluorineException(msg);
                        }
                    }
                    else
                    {
                        FieldInfo fi = destinationType.GetField(memberName, BindingFlags.Public | BindingFlags.Instance);
                        try {
                            if (fi != null)
                            {
                                val = TypeHelper.ChangeType(val, fi.FieldType);
                                fi.SetValue(instance, val);
                            }
                            else
                            {
                                //string msg = __Res.GetString(__Res.Reflection_MemberNotFound, string.Format("{0}.{1}", destinationType.FullName, memberName));
                            }
                        } catch (Exception ex) {
                            string msg = __Res.GetString(__Res.Reflection_FieldSetFail, string.Format("{0}.{1}", destinationType.FullName, memberName), ex.Message);
                            throw new FluorineException(msg);
                        }
                    }
                }
            }
            return(instance);
        }
예제 #24
0
 private void BeginResponseFlashCall(IAsyncResult ar)
 {
     try
     {
         AmfRequestData amfRequestData = ar.AsyncState as AmfRequestData;
         if (amfRequestData != null)
         {
             HttpWebResponse response = (HttpWebResponse)amfRequestData.Request.EndGetResponse(ar);
             if (response != null)
             {
                 //Get response and deserialize
                 Stream responseStream = response.GetResponseStream();
                 if (responseStream != null)
                 {
                     AMFDeserializer amfDeserializer = new AMFDeserializer(responseStream);
                     AMFMessage responseMessage = amfDeserializer.ReadAMFMessage();
                     AMFBody responseBody = responseMessage.GetBodyAt(0);
                     for (int i = 0; i < responseMessage.HeaderCount; i++)
                     {
                         AMFHeader header = responseMessage.GetHeaderAt(i);
                         if (header.Name == AMFHeader.RequestPersistentHeader)
                             _netConnection.AddHeader(header.Name, header.MustUnderstand, header.Content);
                     }
                     if (amfRequestData.Call != null)
                     {
                         PendingCall call = amfRequestData.Call;
                         call.Result = responseBody.Content;
                         call.Status = responseBody.Target.EndsWith(AMFBody.OnStatus) ? Messaging.Rtmp.Service.Call.STATUS_INVOCATION_EXCEPTION : Messaging.Rtmp.Service.Call.STATUS_SUCCESS_RESULT;
                         amfRequestData.Callback.ResultReceived(call);
                     }
                     if (amfRequestData.Responder != null)
                     {
                         if (responseBody.Target.EndsWith(AMFBody.OnStatus))
                         {
                             StatusFunction statusFunction = amfRequestData.Responder.GetType().GetProperty("Status").GetValue(amfRequestData.Responder, null) as StatusFunction;
                             if (statusFunction != null)
                                 statusFunction(new Fault(responseBody.Content));
                         }
                         else
                         {
                             Delegate resultFunction = amfRequestData.Responder.GetType().GetProperty("Result").GetValue(amfRequestData.Responder, null) as Delegate;
                             if (resultFunction != null)
                             {
                                 ParameterInfo[] arguments = resultFunction.Method.GetParameters();
                                 object result = TypeHelper.ChangeType(responseBody.Content, arguments[0].ParameterType);
                                 resultFunction.DynamicInvoke(result);
                             }
                         }
                     }
                 }
                 else
                     _netConnection.RaiseNetStatus("Could not aquire ResponseStream");
             }
             else
                 _netConnection.RaiseNetStatus("Could not aquire HttpWebResponse");
         }
     }
     catch (Exception ex)
     {
         _netConnection.RaiseNetStatus(ex);
     }
 }
예제 #25
0
        /// <summary>
        /// ConfigObject 使用objNode的各个子节点配置target的对应的属性
        /// </summary>
        private static void ConfigObject(XmlNode objNode, ref object target)
        {
            foreach (XmlAttribute attr in objNode.Attributes)
            {
                ReflectionHelper.SetProperty(target, attr.Name, attr.Value);
            }

            foreach (XmlNode childNode in objNode.ChildNodes)
            {
                if (childNode.Attributes["value"] != null)
                {
                    ReflectionHelper.SetProperty(target, childNode.Attributes["name"].Value, childNode.Attributes["value"].Value);
                }
                else
                {
                    XmlNode childProNode = childNode.ChildNodes[0];
                    if (childProNode.Name == "object")
                    {
                        Type   proType = ReflectionHelper.GetType(childProNode.Attributes["type"].Value);
                        object proObj  = Activator.CreateInstance(proType);
                        SpringFox.ConfigObject(childProNode, ref proObj);
                        ReflectionHelper.SetProperty(target, childNode.Attributes["name"].Value, proObj);
                    }
                    else if (childProNode.Name == "list")
                    {
                        Type   listElementType       = ReflectionHelper.GetType(childProNode.Attributes["element-type"].Value);
                        Type   closedGenericListType = typeof(List <>).MakeGenericType(listElementType);
                        object list = Activator.CreateInstance(closedGenericListType);
                        //ISimpleList simpleList = (ISimpleList)SpringFox.DynamicProxyCreator.CreateDynamicProxy<ISimpleList>(list);

                        #region Add object into list
                        if (TypeHelper.IsSimpleType(listElementType))
                        {
                            foreach (XmlNode elementNode in childProNode.ChildNodes)
                            {
                                object element = TypeHelper.ChangeType(listElementType, elementNode.InnerText);
                                closedGenericListType.GetMethod("Add").Invoke(list, new object[] { element });
                                //simpleList.Add(element);
                            }
                        }
                        else
                        {
                            foreach (XmlNode elementNode in childProNode.ChildNodes)
                            {
                                Type curElementType = listElementType;
                                if (elementNode.Attributes["type"] != null)
                                {
                                    curElementType = ReflectionHelper.GetType(elementNode.Attributes["type"].Value);
                                }
                                object element = Activator.CreateInstance(curElementType);
                                SpringFox.ConfigObject(elementNode, ref element);
                                closedGenericListType.GetMethod("Add").Invoke(list, new object[] { element });
                                //simpleList.Add(element);
                            }
                        }

                        #endregion

                        ReflectionHelper.SetProperty(target, childNode.Attributes["name"].Value, list);
                    }
                }
            }
        }
 public void ChangeType_ThrowsIfTypeDoesNotAllowNulls()
 {
     // Act & Assert
     ExceptionAssert.Throws <InvalidCastException>(() => TypeHelper.ChangeType(null, typeof(int)));
 }
 public void ChangeType_ThrowsIfTypeIsNull()
 {
     // Act & Assert
     ExceptionAssert.ThrowsArgNull(() => TypeHelper.ChangeType(new object(), null), "type");
 }
 public void ChangeType_ThrowWhenThereIsNoConverterForEither()
 {
     // Act & Assert
     ExceptionAssert.Throws <InvalidOperationException>(() => TypeHelper.ChangeType(false, typeof(MockClass)));
 }
예제 #29
0
        internal void SetMember(object instance, string memberName, object value)
        {
            if (instance is ASObject)
            {
                ((ASObject)instance)[memberName] = value;
                return;
            }
            Type type = instance.GetType();
            //PropertyInfo propertyInfo = type.GetProperty(memberName);
            PropertyInfo propertyInfo = null;

            try
            {
                propertyInfo = type.GetProperty(memberName);
            }
            catch (AmbiguousMatchException)
            {
                //To resolve the ambiguity, include BindingFlags.DeclaredOnly to restrict the search to members that are not inherited.
                propertyInfo = type.GetProperty(memberName, BindingFlags.DeclaredOnly | BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance);
            }
            if (propertyInfo != null)
            {
                try
                {
                    if (propertyInfo.PropertyType == typeof(TimeSpan) ||
                        (propertyInfo.PropertyType == typeof(TimeSpan?) && value != null))
                    {
                        value = Util.Convert.ToTimeSpan(value);
                    }
                    else
                    {
                        value = TypeHelper.ChangeType(value, propertyInfo.PropertyType);
                    }

                    if (propertyInfo.CanWrite)
                    {
                        if (propertyInfo.GetIndexParameters() == null || propertyInfo.GetIndexParameters().Length == 0)
                        {
                            propertyInfo.SetValue(instance, value, null);
                        }
                        else
                        {
                            string msg = __Res.GetString(__Res.Reflection_PropertyIndexFail, string.Format("{0}.{1}", type.FullName, memberName));

                            if (!_faultTolerancy)
                            {
                                throw new AMFException(msg);
                            }
                            else
                            {
                                _lastError = new AMFException(msg);
                            }
                        }
                    }
                    else
                    {
                        string msg = __Res.GetString(__Res.Reflection_PropertyReadOnly, string.Format("{0}.{1}", type.FullName, memberName));
                    }
                }
                catch (Exception ex)
                {
                    string msg = __Res.GetString(__Res.Reflection_PropertySetFail, string.Format("{0}.{1}", type.FullName, memberName), ex.Message);

                    if (!_faultTolerancy)
                    {
                        throw new AMFException(msg);
                    }
                    else
                    {
                        _lastError = new AMFException(msg);
                    }
                }
            }
            else
            {
                FieldInfo fi = type.GetField(memberName, BindingFlags.Public | BindingFlags.Instance);
                try
                {
                    if (fi != null)
                    {
                        if (fi.FieldType == typeof(TimeSpan))
                        {
                            value = Util.Convert.ToTimeSpan(value);
                        }
                        else
                        {
                            value = TypeHelper.ChangeType(value, fi.FieldType);
                        }

                        fi.SetValue(instance, value);
                    }
                    else
                    {
                        string msg = __Res.GetString(__Res.Reflection_MemberNotFound, string.Format("{0}.{1}", type.FullName, memberName));
                    }
                }
                catch (Exception ex)
                {
                    string msg = __Res.GetString(__Res.Reflection_FieldSetFail, string.Format("{0}.{1}", type.FullName, memberName), ex.Message);

                    if (!_faultTolerancy)
                    {
                        throw new AMFException(msg);
                    }
                    else
                    {
                        _lastError = new AMFException(msg);
                    }
                }
            }
        }
예제 #30
0
 internal void SetMember(object instance, string memberName, object value)
 {
     if (instance is ASObject)
     {
         ((ASObject)instance)[memberName] = value;
     }
     else
     {
         string       str;
         Exception    exception;
         Type         type     = instance.GetType();
         PropertyInfo property = null;
         try
         {
             property = type.GetProperty(memberName);
         }
         catch (AmbiguousMatchException)
         {
             property = type.GetProperty(memberName, BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
         }
         if (property != null)
         {
             try
             {
                 value = TypeHelper.ChangeType(value, property.PropertyType);
                 if (property.CanWrite)
                 {
                     if ((property.GetIndexParameters() == null) || (property.GetIndexParameters().Length == 0))
                     {
                         property.SetValue(instance, value, null);
                     }
                     else
                     {
                         str = __Res.GetString("Reflection_PropertyIndexFail", new object[] { string.Format("{0}.{1}", type.FullName, memberName) });
                         if (log.get_IsErrorEnabled())
                         {
                             log.Error(str);
                         }
                         if (!this._faultTolerancy)
                         {
                             throw new FluorineException(str);
                         }
                         this._lastError = new FluorineException(str);
                     }
                 }
                 else
                 {
                     str = __Res.GetString("Reflection_PropertyReadOnly", new object[] { string.Format("{0}.{1}", type.FullName, memberName) });
                     if (log.get_IsWarnEnabled())
                     {
                         log.Warn(str);
                     }
                 }
             }
             catch (Exception exception2)
             {
                 exception = exception2;
                 str       = __Res.GetString("Reflection_PropertySetFail", new object[] { string.Format("{0}.{1}", type.FullName, memberName), exception.Message });
                 if (log.get_IsErrorEnabled())
                 {
                     log.Error(str, exception);
                 }
                 if (!this._faultTolerancy)
                 {
                     throw new FluorineException(str);
                 }
                 this._lastError = new FluorineException(str);
             }
         }
         else
         {
             FieldInfo field = type.GetField(memberName, BindingFlags.Public | BindingFlags.Instance);
             try
             {
                 if (field != null)
                 {
                     value = TypeHelper.ChangeType(value, field.FieldType);
                     field.SetValue(instance, value);
                 }
                 else
                 {
                     str = __Res.GetString("Reflection_MemberNotFound", new object[] { string.Format("{0}.{1}", type.FullName, memberName) });
                     if (log.get_IsWarnEnabled())
                     {
                         log.Warn(str);
                     }
                 }
             }
             catch (Exception exception3)
             {
                 exception = exception3;
                 str       = __Res.GetString("Reflection_FieldSetFail", new object[] { string.Format("{0}.{1}", type.FullName, memberName), exception.Message });
                 if (log.get_IsErrorEnabled())
                 {
                     log.Error(str, exception);
                 }
                 if (!this._faultTolerancy)
                 {
                     throw new FluorineException(str);
                 }
                 this._lastError = new FluorineException(str);
             }
         }
     }
 }