Exemplo n.º 1
0
        internal static TaskClientCodeException CreateWithNonSerializableInnerException(
            TaskClientCodeException e, SerializationException serializationException)
        {
            var nonSerializableTaskException = NonSerializableTaskException.UnableToSerialize(e.InnerException, serializationException);

            return new TaskClientCodeException(
                e.TaskId, 
                e.ContextId, 
                string.Format("Unable to serialize Task control message. TaskClientCodeException message: {0}", e.Message), 
                nonSerializableTaskException);
        }
	    internal static SerializationException GetSerializationException(string propertyName, string propertyValueString, Type propertyType, Exception e)
	    {
	        var serializationException = new SerializationException(String.Format("Failed to set property '{0}' with '{1}'", propertyName, propertyValueString), e);
	        if (propertyName != null) {
	            serializationException.Data.Add("propertyName", propertyName);
	        }
	        if (propertyValueString != null) {
	            serializationException.Data.Add("propertyValueString", propertyValueString);
	        }
	        if (propertyType != null) {
	            serializationException.Data.Add("propertyType", propertyType);
	        }
	        return serializationException;
	    }
Exemplo n.º 3
0
		private void ThrowErrorOrWriteWarning(Exception e)
		{
			if (!PSSessionConfigurationData.IsServerManager)
			{
				this.InternalDelete();
				this.serializationErrorHasOccured = true;
				SerializationException serializationException = new SerializationException(Resources.SerializationErrorException, e);
				throw serializationException;
			}
			else
			{
				object[] message = new object[1];
				message[0] = e.Message;
				string str = string.Format(CultureInfo.CurrentCulture, Resources.SerializationWarning, message);
				this.WriteWarning(str);
				return;
			}
		}
        public object PopulateFromMap(object instance, IDictionary<string, string> keyValuePairs, List<string> ignoredWarningsOnPropertyNames = null)
        {
            var errors = new List<RequestBindingError>();

            string propertyName = null;
            string propertyTextValue = null;
            PropertySerializerEntry propertySerializerEntry = null;

            if (instance == null)
                instance = type.CreateInstance();

            foreach (var pair in keyValuePairs.Where(x => !string.IsNullOrEmpty(x.Value)))
            {
                try
                {
                    propertyName = pair.Key;
                    propertyTextValue = pair.Value;

                    if (!propertySetterMap.TryGetValue(propertyName, out propertySerializerEntry))
                    {
                        if (propertyName == "v")
                        {
                            int version;
                            var hasVersion = instance as IHasVersion;
                            if (hasVersion != null && int.TryParse(pair.Value, out version))
                            {
                                hasVersion.Version = version;
                            }
                            continue;
                        }

                        var ignoredProperty = propertyName.ToLowerInvariant();
                        if (ignoredWarningsOnPropertyNames == null ||
                            !ignoredWarningsOnPropertyNames.Contains(ignoredProperty))
                        {
                            Log.WarnFormat("Property '{0}' does not exist on type '{1}'", ignoredProperty, type.FullName);
                        }
                        continue;
                    }

                    if (propertySerializerEntry.PropertySetFn == null)
                    {
                        Log.WarnFormat("Could not set value of read-only property '{0}' on type '{1}'", propertyName,
                                       type.FullName);
                        continue;
                    }

                    if (propertySerializerEntry.PropertyType == typeof (bool))
                    {
                        //InputExtensions.cs#530 MVC Checkbox helper emits extra hidden input field, generating 2 values, first is the real value
                        propertyTextValue = propertyTextValue.LeftPart(',');
                    }

                    var value = propertySerializerEntry.PropertyParseStringFn(propertyTextValue);
                    if (value == null)
                    {
                        Log.WarnFormat("Could not create instance on '{0}' for property '{1}' with text value '{2}'",
                                       instance, propertyName, propertyTextValue);
                        continue;
                    }
                    propertySerializerEntry.PropertySetFn(instance, value);
                }
                catch (Exception ex)
                {
                    var error = new RequestBindingError();

                    if (propertyName != null)
                        error.PropertyName = propertyName;

                    if (propertyTextValue != null)
                        error.PropertyValueString = propertyTextValue;

                    if (propertySerializerEntry != null && propertySerializerEntry.PropertyType != null)
                        error.PropertyType = propertySerializerEntry.PropertyType;

                    errors.Add(error);
                }
            }

            if (errors.Count > 0)
            {
                var serializationException = new SerializationException("Unable to bind to request '{0}'".Fmt(type.Name));
                serializationException.Data.Add("errors", errors);
                throw serializationException;
            }

            return instance;
        }
Exemplo n.º 5
0
 public static TwitterApiException CreateFromException(SerializationException ex, string responseText)
     => new TwitterApiException("Invalid JSON", responseText, ex);
Exemplo n.º 6
0
 public static string Convert(SerializationException e)
 {
     return (e.Message);
 }
Exemplo n.º 7
0
 private NonSerializableTaskException(Exception originalException, SerializationException serializationException)
     : base(GetNonSerializableExceptionMessage(originalException), serializationException)
 {
 }
        public object PopulateFromMap(object instance, IDictionary<string, string> keyValuePairs)
        {
            string propertyName = null;
            string propertyTextValue = null;
            PropertySerializerEntry propertySerializerEntry = null;

            try
            {
                if (instance == null) instance = ReflectionUtils.CreateInstance(type);

                foreach (var pair in keyValuePairs)
                {
                    propertyName = pair.Key;
                    propertyTextValue = pair.Value;

                    if (!propertySetterMap.TryGetValue(propertyName, out propertySerializerEntry))
                    {
                        if (propertyName != "format" && propertyName != "callback" && propertyName != "debug")
                        {
                            Log.WarnFormat("Property '{0}' does not exist on type '{1}'", propertyName, type.FullName);
                        }
                        continue;
                    }

                    var value = propertySerializerEntry.PropertyParseStringFn(propertyTextValue);
                    if (value == null)
                    {
                        Log.WarnFormat("Could not create instance on '{0}' for property '{1}' with text value '{2}'",
                                       instance, propertyName, propertyTextValue);
                        continue;
                    }
                    propertySerializerEntry.PropertySetFn(instance, value);
                }
                return instance;

            }
            catch (Exception ex)
            {
                var serializationException = new SerializationException("KeyValueDataContractDeserializer: Error converting to type: " + ex.Message, ex);
                if (propertyName != null) {
                    serializationException.Data.Add("propertyName", propertyName);
                }
                if (propertyTextValue != null) {
                    serializationException.Data.Add("propertyValueString", propertyTextValue);
                }
                if (propertySerializerEntry != null && propertySerializerEntry.PropertyType != null) {
                    serializationException.Data.Add("propertyType", propertySerializerEntry.PropertyType);
                }
                throw serializationException;
            }
        }
        private void ParseXml(XmlTextReader reader) {
            bool success = false;
            try {
                try {
                    while (reader.Read()) {
                        if (reader.NodeType == XmlNodeType.Element) {
                            string s = reader.LocalName;
                            
                            if (reader.LocalName.Equals(ResXResourceWriter.AssemblyStr)) {
                                ParseAssemblyNode(reader, false);
                            }
                            else if (reader.LocalName.Equals(ResXResourceWriter.DataStr)) {
                                ParseDataNode(reader, false);
                            }
                            else if (reader.LocalName.Equals(ResXResourceWriter.ResHeaderStr)) {
                                ParseResHeaderNode(reader);
                            }
                            else if (reader.LocalName.Equals(ResXResourceWriter.MetadataStr)) {
                                ParseDataNode(reader, true);
                            }
                        }
                    }

                    success = true;
                }
                catch (SerializationException se) {
                    Point pt = GetPosition(reader);
                    string newMessage = SR.GetString(SR.SerializationException, reader[ResXResourceWriter.TypeStr], pt.Y, pt.X, se.Message);
                    XmlException xml = new XmlException(newMessage, se, pt.Y, pt.X);
                    SerializationException newSe = new SerializationException(newMessage, xml);

                    throw newSe;
                }
                catch (TargetInvocationException tie) {
                    Point pt = GetPosition(reader);
                    string newMessage = SR.GetString(SR.InvocationException, reader[ResXResourceWriter.TypeStr], pt.Y, pt.X, tie.InnerException.Message);
                    XmlException xml = new XmlException(newMessage, tie.InnerException, pt.Y, pt.X);
                    TargetInvocationException newTie = new TargetInvocationException(newMessage, xml);

                    throw newTie;
                }
                catch (XmlException e) {
                    throw new ArgumentException(SR.GetString(SR.InvalidResXFile, e.Message), e);
                }
                catch (Exception e) {
                    if (ClientUtils.IsSecurityOrCriticalException(e)) {
                        throw;
                    } else {
                        Point pt = GetPosition(reader);
                        XmlException xmlEx = new XmlException(e.Message, e, pt.Y, pt.X);
                        throw new ArgumentException(SR.GetString(SR.InvalidResXFile, xmlEx.Message), xmlEx);
                    }
                }
            }
            finally {
                if (!success) {
                    resData = null;
                    resMetadata = null;
                }
            }

            bool validFile = false;

            if (object.Equals(resHeaderMimeType, ResXResourceWriter.ResMimeType)) {

                Type readerType = typeof(ResXResourceReader);
                Type writerType = typeof(ResXResourceWriter);

                string readerTypeName = resHeaderReaderType;
                string writerTypeName = resHeaderWriterType;
                if (readerTypeName != null &&readerTypeName.IndexOf(',') != -1) {
                    readerTypeName = readerTypeName.Split(new char[] {','})[0].Trim();
                }
                if (writerTypeName != null && writerTypeName.IndexOf(',') != -1) {
                    writerTypeName = writerTypeName.Split(new char[] {','})[0].Trim();
                }

// Don't check validity, since our reader/writer classes are in System.Web.Compilation,
// while the file format has them in System.Resources.  
#if SYSTEM_WEB
                validFile = true;
#else
                if (readerTypeName != null && 
                    writerTypeName != null && 
                    readerTypeName.Equals(readerType.FullName) && 
                    writerTypeName.Equals(writerType.FullName)) {
                    validFile = true;
                }
#endif
            }

            if (!validFile) {
                resData = null;
                resMetadata = null;
                throw new ArgumentException(SR.GetString(SR.InvalidResXFileReaderWriterTypes));
            }
        }
        public void Save_Wraps_SerializationException_As_IOException()
        {
            // Arrange
            var testBundle = new SettingsRepositoryTestBundle();
            var mockLog = new Mock<ILog>();
            var settings = new SettingsRoot();
            var testException = new SerializationException("test exception");
            IOException thrownException = null;

            testBundle.MockLogProvider.Setup(x => x.GetLogger(It.IsAny<Type>())).Returns(mockLog.Object);
            testBundle.MockXmlSerializer.Setup(x => x.Serialize(It.IsAny<TextWriter>(), It.IsAny<object>())).Throws(testException);

            // Act
            try
            {
                testBundle.SettingsManager.Save(settings);
            }
            catch (IOException ex)
            {
                thrownException = ex;
            }

            // Assert
            testBundle.MockXmlSerializer.Verify(x => x.Serialize(It.IsAny<TextWriter>(), It.IsAny<object>()), Times.Once);
            Assert.IsNotNull(thrownException);
        }
 object IDesignerSerializationManager.CreateInstance(Type type, ICollection arguments, string name, bool addToContainer)
 {
     this.CheckSession();
     if (((name != null) && (this.instancesByName != null)) && this.instancesByName.ContainsKey(name))
     {
         Exception exception = new SerializationException(System.Design.SR.GetString("SerializationManagerDuplicateComponentDecl", new object[] { name })) {
             HelpLink = "SerializationManagerDuplicateComponentDecl"
         };
         throw exception;
     }
     object obj2 = this.CreateInstance(type, arguments, name, addToContainer);
     if ((name != null) && (!(obj2 is IComponent) || !this.RecycleInstances))
     {
         if (this.instancesByName == null)
         {
             this.instancesByName = new Hashtable();
             this.namesByInstance = new Hashtable(new ReferenceComparer());
         }
         this.instancesByName[name] = obj2;
         this.namesByInstance[obj2] = name;
     }
     return obj2;
 }
 protected virtual object CreateInstance(Type type, ICollection arguments, string name, bool addToContainer)
 {
     object[] array = null;
     if ((arguments != null) && (arguments.Count > 0))
     {
         array = new object[arguments.Count];
         arguments.CopyTo(array, 0);
     }
     object obj2 = null;
     if (this.RecycleInstances && (name != null))
     {
         if (this.instancesByName != null)
         {
             obj2 = this.instancesByName[name];
         }
         if (((obj2 == null) && addToContainer) && (this.Container != null))
         {
             obj2 = this.Container.Components[name];
         }
         if (((obj2 != null) && this.ValidateRecycledTypes) && (obj2.GetType() != type))
         {
             obj2 = null;
         }
     }
     if ((((obj2 == null) && addToContainer) && typeof(IComponent).IsAssignableFrom(type)) && (((array == null) || (array.Length == 0)) || ((array.Length == 1) && (array[0] == this.Container))))
     {
         IDesignerHost service = this.GetService(typeof(IDesignerHost)) as IDesignerHost;
         if ((service != null) && (service.Container == this.Container))
         {
             bool flag = false;
             if ((!this.PreserveNames && (name != null)) && (this.Container.Components[name] != null))
             {
                 flag = true;
             }
             if ((name == null) || flag)
             {
                 obj2 = service.CreateComponent(type);
             }
             else
             {
                 obj2 = service.CreateComponent(type, name);
             }
         }
     }
     if (obj2 == null)
     {
         try
         {
             try
             {
                 obj2 = TypeDescriptor.CreateInstance(this.provider, type, null, array);
             }
             catch (MissingMethodException exception)
             {
                 Type[] typeArray = new Type[array.Length];
                 for (int i = 0; i < array.Length; i++)
                 {
                     if (array[i] != null)
                     {
                         typeArray[i] = array[i].GetType();
                     }
                 }
                 object[] args = new object[array.Length];
                 foreach (ConstructorInfo info in TypeDescriptor.GetReflectionType(type).GetConstructors(BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.Instance))
                 {
                     ParameterInfo[] parameters = info.GetParameters();
                     if ((parameters != null) && (parameters.Length == typeArray.Length))
                     {
                         bool flag2 = true;
                         for (int j = 0; j < typeArray.Length; j++)
                         {
                             if ((typeArray[j] == null) || parameters[j].ParameterType.IsAssignableFrom(typeArray[j]))
                             {
                                 args[j] = array[j];
                             }
                             else
                             {
                                 if (array[j] is IConvertible)
                                 {
                                     try
                                     {
                                         args[j] = ((IConvertible) array[j]).ToType(parameters[j].ParameterType, null);
                                         goto Label_0217;
                                     }
                                     catch (InvalidCastException)
                                     {
                                     }
                                 }
                                 flag2 = false;
                                 break;
                             Label_0217:;
                             }
                         }
                         if (flag2)
                         {
                             obj2 = TypeDescriptor.CreateInstance(this.provider, type, null, args);
                             break;
                         }
                     }
                 }
                 if (obj2 == null)
                 {
                     throw exception;
                 }
             }
         }
         catch (MissingMethodException)
         {
             StringBuilder builder = new StringBuilder();
             foreach (object obj3 in array)
             {
                 if (builder.Length > 0)
                 {
                     builder.Append(", ");
                 }
                 if (obj3 != null)
                 {
                     builder.Append(obj3.GetType().Name);
                 }
                 else
                 {
                     builder.Append("null");
                 }
             }
             Exception exception2 = new SerializationException(System.Design.SR.GetString("SerializationManagerNoMatchingCtor", new object[] { type.FullName, builder.ToString() })) {
                 HelpLink = "SerializationManagerNoMatchingCtor"
             };
             throw exception2;
         }
         if ((!addToContainer || !(obj2 is IComponent)) || (this.Container == null))
         {
             return obj2;
         }
         bool flag3 = false;
         if ((!this.PreserveNames && (name != null)) && (this.Container.Components[name] != null))
         {
             flag3 = true;
         }
         if ((name == null) || flag3)
         {
             this.Container.Add((IComponent) obj2);
             return obj2;
         }
         this.Container.Add((IComponent) obj2, name);
     }
     return obj2;
 }
 private Hashtable CreateResourceSet(IResourceReader reader, CultureInfo culture)
 {
     Hashtable hashtable = new Hashtable();
     try
     {
         IDictionaryEnumerator enumerator = reader.GetEnumerator();
         while (enumerator.MoveNext())
         {
             string key = (string) enumerator.Key;
             object obj2 = enumerator.Value;
             hashtable[key] = obj2;
         }
     }
     catch (Exception exception)
     {
         Exception exception2;
         string message = exception.Message;
         if ((message == null) || (message.Length == 0))
         {
             message = exception.GetType().Name;
         }
         if (culture == CultureInfo.InvariantCulture)
         {
             exception2 = new SerializationException(System.Design.SR.GetString("SerializerResourceExceptionInvariant", new object[] { message }), exception);
         }
         else
         {
             exception2 = new SerializationException(System.Design.SR.GetString("SerializerResourceException", new object[] { culture.ToString(), message }), exception);
         }
         this.manager.ReportError(exception2);
     }
     return hashtable;
 }
		/// <summary>
		/// Converts the given <see cref="Stream"/> into a list of <see cref="RelayMessage"/>.
		/// </summary>
		/// <param name="stream">The given <see cref="Stream"/></param>
		/// <param name="evaluateMethod">A method to evaluate each <see cref="RelayMessage"/> as it's deserialized.</param>
		/// <returns>A list of <see cref="RelayMessage"/>.</returns>
		public static List<RelayMessage> ReadRelayMessageList(Stream stream, Action<RelayMessage> evaluateMethod)
		{
			BinaryReader bread = new BinaryReader(stream);
			CompactBinaryReader br = new CompactBinaryReader(bread);
			int objectCount = br.ReadInt32();
			List<RelayMessage> messages = new List<RelayMessage>(objectCount);
			for (int i = 0; i < objectCount; i++)
			{
				RelayMessage nextMessage = new RelayMessage();
				try
				{
					br.Read<RelayMessage>(nextMessage, false);
				}
				catch (SerializationException exc)
				{
					//try and add some context to this object
					//Id and TypeId most likely got correctly deserialized so we're providing that much
					string message = string.Format("Deserialization failed for RelayMessage of Id='{0}', ExtendedId='{1}', TypeId='{2}' and StreamLength='{3}'",
						nextMessage.Id, Algorithm.ToHex(nextMessage.ExtendedId), nextMessage.TypeId, stream.Length);
					SerializationException newException = new SerializationException(message, exc);
					throw newException;
				}
				messages.Add(nextMessage);
				if (evaluateMethod != null) evaluateMethod(nextMessage);
			}
			return messages;
		}
 private NonSerializableEvaluatorException(string exceptionString, SerializationException serializationException)
     : base(exceptionString, serializationException)
 {
 }
Exemplo n.º 16
0
		// used by the client
		internal IMessage FormatResponse(ISoapMessage soapMsg, IMethodCallMessage mcm) 
		{
			IMessage rtnMsg;
			
			if(soapMsg.MethodName == "Fault") {
				// an exception was thrown by the server
				Exception e = new SerializationException();
				int i = Array.IndexOf(soapMsg.ParamNames, "detail");
				if(_serverFaultExceptionField != null)
					// todo: revue this 'cause it's not safe
					e = (Exception) _serverFaultExceptionField.GetValue(
							soapMsg.ParamValues[i]);
				
				rtnMsg = new ReturnMessage((System.Exception)e, mcm);
			}
			else {
				object rtnObject = null;
				//RemMessageType messageType;
				
				// Get the output of the function if it is not *void*
				if(_methodCallInfo.ReturnType != typeof(void)){
					int index = Array.IndexOf(soapMsg.ParamNames, "return");
					rtnObject = soapMsg.ParamValues[index];
					if(rtnObject is IConvertible) 
						rtnObject = Convert.ChangeType(
								rtnObject, 
								_methodCallInfo.ReturnType);
				}
				
				object[] outParams = new object [_methodCallParameters.Length];
				int n=0;
				
				// check if there are *out* parameters
				foreach(ParameterInfo paramInfo in _methodCallParameters) {
					
					if(paramInfo.ParameterType.IsByRef || paramInfo.IsOut) {
						int index = Array.IndexOf(soapMsg.ParamNames, paramInfo.Name);
						object outParam = soapMsg.ParamValues[index];
						if(outParam is IConvertible)
							outParam = Convert.ChangeType (outParam, paramInfo.ParameterType.GetElementType());
						outParams[n] = outParam;
					}
					else
						outParams [n] = null;
					n++;
				}
				
				Header[] headers = new Header [2 + (soapMsg.Headers != null ? soapMsg.Headers.Length : 0)];
				headers [0] = new Header ("__Return", rtnObject);
				headers [1] = new Header ("__OutArgs", outParams);
				
				if (soapMsg.Headers != null)
					soapMsg.Headers.CopyTo (headers, 2);
					
				rtnMsg = new MethodResponse (headers, mcm);
			}
			return rtnMsg;
		}
Exemplo n.º 17
0
 internal static NonSerializableTaskException UnableToSerialize(Exception originalException, SerializationException serializationException)
 {
     return new NonSerializableTaskException(originalException, serializationException);
 }
 public override object Deserialize(IDesignerSerializationManager manager, object codeObject)
 {
     if ((manager == null) || (codeObject == null))
     {
         throw new ArgumentNullException((manager == null) ? "manager" : "codeObject");
     }
     object obj2 = null;
     using (CodeDomSerializerBase.TraceScope("RootCodeDomSerializer::Deserialize"))
     {
         if (!(codeObject is CodeTypeDeclaration))
         {
             throw new ArgumentException(System.Design.SR.GetString("SerializerBadElementType", new object[] { typeof(CodeTypeDeclaration).FullName }));
         }
         bool caseInsensitive = false;
         CodeDomProvider service = manager.GetService(typeof(CodeDomProvider)) as CodeDomProvider;
         if (service != null)
         {
             caseInsensitive = (service.LanguageOptions & LanguageOptions.CaseInsensitive) != LanguageOptions.None;
         }
         CodeTypeDeclaration declaration = (CodeTypeDeclaration) codeObject;
         CodeTypeReference reference = null;
         Type type = null;
         foreach (CodeTypeReference reference2 in declaration.BaseTypes)
         {
             Type type2 = manager.GetType(CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, reference2));
             if ((type2 != null) && !type2.IsInterface)
             {
                 reference = reference2;
                 type = type2;
                 break;
             }
         }
         if (type == null)
         {
             Exception exception = new SerializationException(System.Design.SR.GetString("SerializerTypeNotFound", new object[] { reference.BaseType })) {
                 HelpLink = "SerializerTypeNotFound"
             };
             throw exception;
         }
         if (type.IsAbstract)
         {
             Exception exception2 = new SerializationException(System.Design.SR.GetString("SerializerTypeAbstract", new object[] { type.FullName })) {
                 HelpLink = "SerializerTypeAbstract"
             };
             throw exception2;
         }
         ResolveNameEventHandler handler = new ResolveNameEventHandler(this.OnResolveName);
         manager.ResolveName += handler;
         if (!(manager is DesignerSerializationManager))
         {
             manager.AddSerializationProvider(new CodeDomSerializationProvider());
         }
         obj2 = manager.CreateInstance(type, null, declaration.Name, true);
         this.nameTable = new HybridDictionary(declaration.Members.Count, caseInsensitive);
         this.statementTable = new HybridDictionary(declaration.Members.Count, caseInsensitive);
         this.initMethod = null;
         RootContext context = new RootContext(new CodeThisReferenceExpression(), obj2);
         manager.Context.Push(context);
         try
         {
             foreach (CodeTypeMember member in declaration.Members)
             {
                 if (member is CodeMemberField)
                 {
                     if (string.Compare(member.Name, declaration.Name, caseInsensitive, CultureInfo.InvariantCulture) != 0)
                     {
                         this.nameTable[member.Name] = member;
                     }
                 }
                 else if ((this.initMethod == null) && (member is CodeMemberMethod))
                 {
                     CodeMemberMethod method = (CodeMemberMethod) member;
                     if ((string.Compare(method.Name, this.InitMethodName, caseInsensitive, CultureInfo.InvariantCulture) == 0) && (method.Parameters.Count == 0))
                     {
                         this.initMethod = method;
                     }
                 }
             }
             if (this.initMethod != null)
             {
                 foreach (CodeStatement statement in this.initMethod.Statements)
                 {
                     CodeVariableDeclarationStatement statement2 = statement as CodeVariableDeclarationStatement;
                     if (statement2 != null)
                     {
                         this.nameTable[statement2.Name] = statement;
                     }
                 }
             }
             if (this.nameTable[declaration.Name] != null)
             {
                 this.nameTable[declaration.Name] = obj2;
             }
             if (this.initMethod != null)
             {
                 this.FillStatementTable(this.initMethod, declaration.Name);
             }
             PropertyDescriptor descriptor = manager.Properties["SupportsStatementGeneration"];
             if (((descriptor != null) && (descriptor.PropertyType == typeof(bool))) && ((bool) descriptor.GetValue(manager)))
             {
                 foreach (string str in this.nameTable.Keys)
                 {
                     CodeDomSerializerBase.OrderedCodeStatementCollection statements = (CodeDomSerializerBase.OrderedCodeStatementCollection) this.statementTable[str];
                     if (statements != null)
                     {
                         bool flag2 = false;
                         foreach (CodeStatement statement3 in statements)
                         {
                             object obj3 = statement3.UserData["GeneratedStatement"];
                             if (((obj3 == null) || !(obj3 is bool)) || !((bool) obj3))
                             {
                                 flag2 = true;
                                 break;
                             }
                         }
                         if (!flag2)
                         {
                             this.statementTable.Remove(str);
                         }
                     }
                 }
             }
             IContainer container = (IContainer) manager.GetService(typeof(IContainer));
             if (container != null)
             {
                 foreach (object obj4 in container.Components)
                 {
                     base.DeserializePropertiesFromResources(manager, obj4, designTimeProperties);
                 }
             }
             object[] array = new object[this.statementTable.Values.Count];
             this.statementTable.Values.CopyTo(array, 0);
             Array.Sort(array, StatementOrderComparer.Default);
             foreach (CodeDomSerializerBase.OrderedCodeStatementCollection statements2 in array)
             {
                 string name = statements2.Name;
                 if ((name != null) && !name.Equals(declaration.Name))
                 {
                     this.DeserializeName(manager, name);
                 }
             }
             CodeStatementCollection statements3 = (CodeStatementCollection) this.statementTable[declaration.Name];
             if ((statements3 != null) && (statements3.Count > 0))
             {
                 foreach (CodeStatement statement4 in statements3)
                 {
                     base.DeserializeStatement(manager, statement4);
                 }
             }
             return obj2;
         }
         finally
         {
             manager.ResolveName -= handler;
             this.initMethod = null;
             this.nameTable = null;
             this.statementTable = null;
             manager.Context.Pop();
         }
     }
     return obj2;
 }
		//a private helper function to handle serialization exceptions that denotes missing fields, 
		//checks if the DeserializationDefaultValueAttribute or the DeserializationOldNameAttribute
		//were defined over the new field and if so handle the field.
		private void handleSerializationException(SerializationException ex, FieldInfo fieldInfo, Object obj
													, SerializationInfo info, Type t)
		{
			//this is ugly...for some reason they did not defined a MemberNotFoundSerializationException
			//so to make sure this is indeed this exception and not an actual error we need to check the message
			//and compare strings.
			if(!ex.Message.EndsWith("not found."))
				throw ex;
			//check to see if the custume attribute DeserializationDefaultValueAttribute was placed on this new field
			//and if so set it's default value in the field
			Object[] fieldAttributes = fieldInfo.GetCustomAttributes(true);
			foreach(Object attribute in fieldAttributes)
			{
				//see if this is a DeserializationDefaultValueAttribute
				if(attribute.GetType() == typeof(DeserializationDefaultValueAttribute))
				{
					//set the Default Value in the field
					fieldInfo.SetValue(obj, ((DeserializationDefaultValueAttribute)attribute).DefaultValue);
				}
				//see if this is a DeserializationOldNameAttribute
				if(attribute.GetType() == typeof(DeserializationOldNameAttribute))
				{
					object storedValue;
					//get the old name field value
					//check if this is a private field and if so append the class name to access the field
					if(fieldInfo.Attributes == FieldAttributes.Public)
						storedValue =  info.GetValue(((DeserializationOldNameAttribute)attribute).OldName, fieldInfo.FieldType);
					else
						storedValue = info.GetValue(t.Name + "+" + ((DeserializationOldNameAttribute)attribute).OldName
							, fieldInfo.FieldType);
					//set the old field name value to the new field name.
					fieldInfo.SetValue(obj, storedValue);
				}
			}
		}
Exemplo n.º 20
0
        private void ThrowWrappedSerializationException(
            Type messageType,
            SerializationException serializationException)
        {
            string logMessage = string.Format(
                "A serialization exception occured while sending or publishing a message: {0}. " +
                "Ensure that all classes used in the message meet the criteria defined in " +
                "Brnkly.Platform.Framework.ServiceBus.Core.MessageTypeLoader. " +
                "See the inner exception for details.",
                messageType.FullName);

            throw new InvalidOperationException(logMessage, serializationException);
        }
        public object PopulateFromMap(object instance, INameValueCollection nameValues, List<string> ignoredWarningsOnPropertyNames = null)
        {
            var errors = new List<RequestBindingError>();

            PropertySerializerEntry propertySerializerEntry = null;

            if (instance == null)
                instance = type.CreateInstance();

            foreach (var key in nameValues.AllKeys)
            {
                string value = nameValues[key];
                if (!string.IsNullOrEmpty(value))
                {
                    instance = PopulateFromKeyValue(instance, key, value, 
                            out propertySerializerEntry, errors, ignoredWarningsOnPropertyNames);
                }
            }

            if (errors.Count > 0)
            {
                var serializationException = new SerializationException($"Unable to bind to request '{type.Name}'");
                serializationException.Data.Add("errors", errors);
                throw serializationException;
            }

            return instance;
        }
Exemplo n.º 22
0
 internal static NonSerializableTaskException UnableToDeserialize(string exceptionString, SerializationException serializationException)
 {
     return new NonSerializableTaskException(exceptionString, serializationException);
 }
        public object PopulateFromMap(object instance, IDictionary<string, string> keyValuePairs, List<string> ignoredWarningsOnPropertyNames = null)
        {
            var errors = new List<RequestBindingError>();

            PropertySerializerEntry propertySerializerEntry = null;

            if (instance == null)
                instance = type.CreateInstance();

            foreach (var pair in keyValuePairs)
            {
                if (!string.IsNullOrEmpty(pair.Value))
                {
                    instance = PopulateFromKeyValue(instance, pair.Key, pair.Value, 
                            out propertySerializerEntry, errors, ignoredWarningsOnPropertyNames);
                }
            }

            if (errors.Count > 0)
            {
                var serializationException = new SerializationException($"Unable to bind to request '{type.Name}'");
                serializationException.Data.Add("errors", errors);
                throw serializationException;
            }

            return instance;
        }
Exemplo n.º 24
0
 private NonSerializableTaskException(string exceptionString, SerializationException serializationException)
     : base(exceptionString, serializationException)
 {
 }
Exemplo n.º 25
0
 private void OnException(BrokeredMessage message, SerializationException exception)
 {
     throw new NotImplementedException();
     //message.DeadLetterAsync()
 }
Exemplo n.º 26
0
        public object PopulateFromMap(object instance, IDictionary<string, string> keyValuePairs, List<string> ignoredWarningsOnPropertyNames = null)
        {
            string propertyName = null;
            string propertyTextValue = null;
            PropertySerializerEntry propertySerializerEntry = null;

            try
            {
                if (instance == null) instance = type.CreateInstance();

                foreach (var pair in keyValuePairs.Where(x => !string.IsNullOrEmpty(x.Value)))
                {
                    propertyName = pair.Key;
                    propertyTextValue = pair.Value;

                    if (!propertySetterMap.TryGetValue(propertyName, out propertySerializerEntry))
                    {
                        var ignoredProperty = propertyName.ToLowerInvariant();
                        if (ignoredWarningsOnPropertyNames == null || !ignoredWarningsOnPropertyNames.Contains(ignoredProperty))
                        {
                            Log.WarnFormat("Property '{0}' does not exist on type '{1}'", ignoredProperty, type.FullName);
                        }
                        continue;
                    }

                    if (propertySerializerEntry.PropertySetFn == null)
                    {
                        Log.WarnFormat("Could not set value of read-only property '{0}' on type '{1}'", propertyName, type.FullName);
                        continue;
                    }

                    if (Type.GetTypeCode(propertySerializerEntry.PropertyType) == TypeCode.Boolean)
                    {
                        //InputExtensions.cs#530 MVC Checkbox helper emits extra hidden input field, generating 2 values, first is the real value
                        propertyTextValue = propertyTextValue.SplitOnFirst(',').First(); 
                    }

                    var value = propertySerializerEntry.PropertyParseStringFn(propertyTextValue);
                    if (value == null)
                    {
                        Log.WarnFormat("Could not create instance on '{0}' for property '{1}' with text value '{2}'",
                                       instance, propertyName, propertyTextValue);
                        continue;
                    }
                    propertySerializerEntry.PropertySetFn(instance, value);
                }
                return instance;

            }
            catch (Exception ex)
            {
                var serializationException = new SerializationException("KeyValueDataContractDeserializer: Error converting to type: " + ex.Message, ex);
                if (propertyName != null) {
                    serializationException.Data.Add("propertyName", propertyName);
                }
                if (propertyTextValue != null) {
                    serializationException.Data.Add("propertyValueString", propertyTextValue);
                }
                if (propertySerializerEntry != null && propertySerializerEntry.PropertyType != null) {
                    serializationException.Data.Add("propertyType", propertySerializerEntry.PropertyType);
                }
                throw serializationException;
            }
        }
 private void ParseXml(XmlTextReader reader)
 {
     bool flag = false;
     try
     {
         while (reader.Read())
         {
             if (reader.NodeType == XmlNodeType.Element)
             {
                 string localName = reader.LocalName;
                 if (reader.LocalName.Equals("assembly"))
                 {
                     this.ParseAssemblyNode(reader, false);
                 }
                 else
                 {
                     if (reader.LocalName.Equals("data"))
                     {
                         this.ParseDataNode(reader, false);
                         continue;
                     }
                     if (reader.LocalName.Equals("resheader"))
                     {
                         this.ParseResHeaderNode(reader);
                         continue;
                     }
                     if (reader.LocalName.Equals("metadata"))
                     {
                         this.ParseDataNode(reader, true);
                     }
                 }
             }
         }
         flag = true;
     }
     catch (SerializationException exception)
     {
         Point position = this.GetPosition(reader);
         string message = System.Windows.Forms.SR.GetString("SerializationException", new object[] { reader["type"], position.Y, position.X, exception.Message });
         XmlException innerException = new XmlException(message, exception, position.Y, position.X);
         SerializationException exception3 = new SerializationException(message, innerException);
         throw exception3;
     }
     catch (TargetInvocationException exception4)
     {
         Point point2 = this.GetPosition(reader);
         string str2 = System.Windows.Forms.SR.GetString("InvocationException", new object[] { reader["type"], point2.Y, point2.X, exception4.InnerException.Message });
         XmlException inner = new XmlException(str2, exception4.InnerException, point2.Y, point2.X);
         TargetInvocationException exception6 = new TargetInvocationException(str2, inner);
         throw exception6;
     }
     catch (XmlException exception7)
     {
         throw new ArgumentException(System.Windows.Forms.SR.GetString("InvalidResXFile", new object[] { exception7.Message }), exception7);
     }
     catch (Exception exception8)
     {
         if (System.Windows.Forms.ClientUtils.IsSecurityOrCriticalException(exception8))
         {
             throw;
         }
         Point point3 = this.GetPosition(reader);
         XmlException exception9 = new XmlException(exception8.Message, exception8, point3.Y, point3.X);
         throw new ArgumentException(System.Windows.Forms.SR.GetString("InvalidResXFile", new object[] { exception9.Message }), exception9);
     }
     finally
     {
         if (!flag)
         {
             this.resData = null;
             this.resMetadata = null;
         }
     }
     bool flag2 = false;
     if (object.Equals(this.resHeaderMimeType, ResXResourceWriter.ResMimeType))
     {
         System.Type type = typeof(ResXResourceReader);
         System.Type type2 = typeof(ResXResourceWriter);
         string resHeaderReaderType = this.resHeaderReaderType;
         string resHeaderWriterType = this.resHeaderWriterType;
         if ((resHeaderReaderType != null) && (resHeaderReaderType.IndexOf(',') != -1))
         {
             resHeaderReaderType = resHeaderReaderType.Split(new char[] { ',' })[0].Trim();
         }
         if ((resHeaderWriterType != null) && (resHeaderWriterType.IndexOf(',') != -1))
         {
             resHeaderWriterType = resHeaderWriterType.Split(new char[] { ',' })[0].Trim();
         }
         if (((resHeaderReaderType != null) && (resHeaderWriterType != null)) && (resHeaderReaderType.Equals(type.FullName) && resHeaderWriterType.Equals(type2.FullName)))
         {
             flag2 = true;
         }
     }
     if (!flag2)
     {
         this.resData = null;
         this.resMetadata = null;
         throw new ArgumentException(System.Windows.Forms.SR.GetString("InvalidResXFileReaderWriterTypes"));
     }
 }