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); }
public virtual void ThrowException(SerializationException serializationException) { if (!serializationException.ExceptionData.CanIgnore) { throw serializationException; } }
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); }
/// <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); }
/// <summary> /// DeSerializes the specified action entity type. /// </summary> /// <typeparam name="T">The type to be serialize to</typeparam> /// <param name="message">The message.</param> /// <returns> /// Returns the de serialized object. /// </returns> public object Deserialize <T>(string message) { object deserializedObject = null; // Initialize serialize for object XmlSerializer serializer = new XmlSerializer(typeof(T)); try { using (TextReader reader = new StringReader(message)) { // de serialization of message. deserializedObject = serializer.Deserialize(reader); } } catch (SystemException ex) { SerializationException serializationException = new SerializationException(ex.Message, ex); this.IDSLogger.Log(TraceLevel.Error, serializationException.ToString()); IdsExceptionManager.HandleException(serializationException); } return(deserializedObject); }
public object PopulateFromMap(object instance, IDictionary <string, string> keyValuePairs, List <string> ignoredWarningsOnPropertyNames = null) { var errors = new List <RequestBindingError>(); 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); }
protected void TestNullCannotBeConvertedToValueType() { SearchServiceClient serviceClient = Data.GetSearchServiceClient(); Index index = new Index() { Name = SearchTestUtilities.GenerateName(), Fields = new[] { new Field("Key", DataType.String) { IsKey = true }, new Field("IntValue", DataType.Int32) } }; serviceClient.Indexes.Create(index); SearchIndexClient indexClient = Data.GetSearchIndexClient(index.Name); var doc = new ModelWithNullableInt() { Key = "123", IntValue = null }; var batch = IndexBatch.Upload(new[] { doc }); indexClient.Documents.Index(batch); SearchTestUtilities.WaitForIndexing(); SerializationException e = Assert.Throws <SerializationException>(() => indexClient.Documents.Search <ModelWithInt>("*")); Assert.Contains("Error converting value {null} to type 'System.Int32'. Path 'IntValue'.", e.ToString()); }
/// <summary> /// Serializes the specified entity in Json Format. /// </summary> /// <param name="entity">The entity.</param> /// <returns> /// Returns the serialize entity in string format. /// </returns> public string Serialize(object entity) { string data = string.Empty; JsonSerializerSettings settings = new JsonSerializerSettings(); settings.Converters.Add(new ObjectToEnumConverter()); settings.Converters.Add(new IntuitConverter()); settings.NullValueHandling = NullValueHandling.Ignore; settings.MissingMemberHandling = MissingMemberHandling.Error; settings.DateFormatHandling = DateFormatHandling.IsoDateFormat; settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc; settings.DateFormatString = "yyyy-MM-ddTHH:mm:ssK"; try { data = JsonConvert.SerializeObject(entity, settings); } catch (Exception ex) { SerializationException serializationException = new SerializationException(ex.Message, ex); this.IDSLogger.Log(TraceLevel.Error, serializationException.ToString()); IdsExceptionManager.HandleException(serializationException); } data = data.Replace("T00:00:00Z", ""); data = data.Replace("T00:00:00", ""); return(data); }
void EvalSerializationException(ref SerializationException serex, Uri url, string method) { //note: when upgrading to .NET 4.5 or greater, switch from Message prop to HResult prop, value = {-2146233076} int hresultNullValueCode = -2146233076; int hresult = 0; System.Reflection.PropertyInfo hresultProp = serex.GetType().GetProperty("HResult", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static); if (hresultProp != null) { hresult = (int)hresultProp.GetValue(serex, null); } serex.Data.Add("SerializationException", string.Format("Could not deserialize result from [{1}]: {0}.", url, method)); serex.Data.Add("HResult", hresult); if (hresult == hresultNullValueCode || serex.Message.StartsWith("Expecting element 'root' from namespace ''.. Encountered 'None' with name '', namespace ''.")) { serex.Data.Add("Resolution", "Check unexpected void/null return type/value from method."); } else { serex.Data.Add("Resolution", string.Format("Unknown error.", url, method)); } }
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); }
public void Create_Inner() { var e = new SerializationException("error", new Exception()); Assert.Equal("error", e.Message); Assert.NotNull(e.InnerException); }
/// <summary> /// DeSerializes the specified action entity type in Json Format. /// </summary> /// <typeparam name="T">The type to be serialize to</typeparam> /// <param name="message">The message.</param> /// <returns> /// Returns the de serialized object. /// </returns> public object Deserialize <T>(string message) { object deserializedObject = null; // Initialize serialize for object JsonSerializerSettings settings = new JsonSerializerSettings(); settings.Converters.Add(new ObjectToEnumConverter()); settings.Converters.Add(new IntuitConverter()); settings.NullValueHandling = NullValueHandling.Ignore; settings.MissingMemberHandling = MissingMemberHandling.Ignore; try { // de serialization of message. /* JObject o = JObject.Parse(message); * string key = o.Properties().Select(p => p.Name).Single(); * string entityString = o[key].ToString();*/ deserializedObject = JsonConvert.DeserializeObject <T>(message, settings); } catch (SystemException ex) { SerializationException serializationException = new SerializationException(ex.Message, ex); this.IDSLogger.Log(TraceLevel.Error, serializationException.ToString()); IdsExceptionManager.HandleException(serializationException); } return(deserializedObject); }
public object PopulateFromMap(object instance, INameValueCollection nameValues, List <string> ignoredWarningsOnPropertyNames = null) { var errors = new List <RequestBindingError>(); 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); }
public void Ctor_Default() { var exception = new SerializationException(); Assert.NotEmpty(exception.Message); Assert.Null(exception.InnerException); Assert.Equal(COR_E_SERIALIZATION, exception.HResult); }
public void Ctor_String(string message) { var exception = new SerializationException(message); Assert.Equal(message, exception.Message); Assert.Null(exception.InnerException); Assert.Equal(COR_E_SERIALIZATION, exception.HResult); }
protected override void before_each() { base.before_each(); json_reader = Substitute.For <JsonReader>(); the_value = null; the_result = null; the_serialization_exception = null; }
public void TestMapNotMarshalableJob() { Mode = ErrorMode.MapJobNotMarshalable; SerializationException e = ExecuteWithError() as SerializationException; Assert.IsNotNull(e); }
/// <summary> /// Called when a read error arises. /// </summary> /// <param name="ex">The exception.</param> protected void OnReadError(SerializationException ex) { // Notify the data store reader this.StreamReadError?.Invoke(this, new StreamReadErrorEventArgs() { StreamName = this.StreamName, Exception = ex }); }
public void UnitySerializationHolderWithAssemblySingleton() { const string UnitySerializationHolderAssemblyBase64String = "AAEAAAD/////AQAAAAAAAAAEAQAAAB9TeXN0ZW0uVW5pdHlTZXJpYWxpemF0aW9uSG9sZGVyAwAAAAREYXRhCVVuaXR5VHlwZQxBc3NlbWJseU5hbWUBAAEIBgIAAABLbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BgAAAAkCAAAACw=="; SerializationException se = AssertExtensions.Throws <SerializationException>(() => BinaryFormatterHelpers.FromBase64String(UnitySerializationHolderAssemblyBase64String)); Assert.IsAssignableFrom <ArgumentException>(se.InnerException); }
public void MarksSerializationExceptionAsNotAnonymized() { var exception = new SerializationException(typeof(Ultrawave.Models.User), new Exception()); var isAnonymized = exception.IsAnonymized(); isAnonymized.Should().BeFalse(); }
public static string GetSerializationExplanation(SerializationException ex) { string explanation = "The following error occured:"; explanation += "Error with serialization/Deserialization object ParentsChildren" + ex.Message; return(explanation); }
private static void AssertSerializationMemberName(string memberName, SerializationException actual, int retryCount) { // Unfortunately, SerializationException does not provide a way to get our hands on the // the actual member that was missing from the SerializationInfo, so we need to grok the // message string. // Member '[memberName]' was not found. StringAssert.Contains(actual.Message, "'" + memberName + "'", "Retry Count {0}: Expected SerializationException MemberName to be '{1}'", retryCount, memberName); }
public object PopulateFromMap(object instance, IDictionary <string, string> keyValuePairs) { string propertyName = null; string propertyTextValue = null; PropertySerializerEntry propertySerializerEntry = null; try { if (instance == null) { instance = type.CreateInstance(); } 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; } }
/// <summary> /// Attempts to create an AMQP property value for a given event property. /// </summary> /// /// <param name="eventPropertyValue">The value of the event property to create an AMQP property value for.</param> /// <param name="amqpPropertyValue">The AMQP property value that was created.</param> /// /// <returns><c>true</c> if an AMQP property value was able to be created; otherwise, <c>false</c>.</returns> /// private static bool TryCreateAmqpPropertyValueForEventProperty(object eventPropertyValue, out object amqpPropertyValue) { amqpPropertyValue = null; if (eventPropertyValue == null) { return(true); } switch (GetTypeIdentifier(eventPropertyValue)) { case AmqpProperty.Type.Byte: case AmqpProperty.Type.SByte: case AmqpProperty.Type.Int16: case AmqpProperty.Type.Int32: case AmqpProperty.Type.Int64: case AmqpProperty.Type.UInt16: case AmqpProperty.Type.UInt32: case AmqpProperty.Type.UInt64: case AmqpProperty.Type.Single: case AmqpProperty.Type.Double: case AmqpProperty.Type.Boolean: case AmqpProperty.Type.Decimal: case AmqpProperty.Type.Char: case AmqpProperty.Type.Guid: case AmqpProperty.Type.DateTime: case AmqpProperty.Type.String: amqpPropertyValue = eventPropertyValue; break; case AmqpProperty.Type.Stream: case AmqpProperty.Type.Unknown when eventPropertyValue is Stream: amqpPropertyValue = ReadStreamToArraySegment((Stream)eventPropertyValue); break; case AmqpProperty.Type.Uri: amqpPropertyValue = new DescribedType(AmqpProperty.Descriptor.Uri, ((Uri)eventPropertyValue).AbsoluteUri); break; case AmqpProperty.Type.DateTimeOffset: amqpPropertyValue = new DescribedType(AmqpProperty.Descriptor.DateTimeOffset, ((DateTimeOffset)eventPropertyValue).UtcTicks); break; case AmqpProperty.Type.TimeSpan: amqpPropertyValue = new DescribedType(AmqpProperty.Descriptor.TimeSpan, ((TimeSpan)eventPropertyValue).Ticks); break; case AmqpProperty.Type.Unknown: var exception = new SerializationException(string.Format(CultureInfo.CurrentCulture, Resources.FailedToSerializeUnsupportedType, eventPropertyValue.GetType().FullName)); EventHubsEventSource.Log.UnexpectedException(exception.Message); throw exception; } return(amqpPropertyValue != null); }
private static void AssertSerializationMemberName(string memberName, SerializationException actual, int retryCount) { // Unfortunately, SerializationException does not provide a way to get our hands on the // the actual member that was missing from the SerializationInfo, so we need to grok the // message string. // Member '[memberName]' was not found. // However, don't check for single-quotes as they can be localized AssertX.Contains(memberName, actual.Message, "Retry Count {0}: Expected SerializationException MemberName to be '{1}'", retryCount, memberName); }
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)); }
private void catch_serialisation_exception(Action action) { json_reader.Value.Returns(the_value); try { action(); } catch (SerializationException ex) { the_serialization_exception = ex; } }
public virtual bool IsSerializable(object instance) { if (instance == null) { return(true); } var type = instance.GetType(); bool isSerializable; if (!this.SerializabilityCache.TryGetValue(type, out isSerializable)) { lock (this.SerializabilityCacheLockObject) { if (!this.SerializabilityCache.TryGetValue(type, out isSerializable)) { if (this.InvestigateSerializability) { try { this.MemoryFormatter.Serialize(instance); isSerializable = true; } catch (SerializationException originalSerializationException) { isSerializable = false; var serializationException = new SerializationException(string.Format(CultureInfo.InvariantCulture, "The type \"{0}\" could not be serialized.", instance.GetType().FullName), originalSerializationException); if (this.SerializationFailures.Count == int.MaxValue) { this.SerializationFailures.RemoveAt(0); } this.SerializationFailures.Add(new SerializationFailure { Type = instance.GetType(), SerializationException = serializationException }); } } else { isSerializable = this.IsSerializable(type); } this.SerializabilityCache.Add(type, isSerializable); } } } return(isSerializable); }
/// <summary> /// Metodo para leer los datos de una universidad guardada en un archivo /// </summary> /// <param name="uni"></param>Universidad a la que se le van a pasar todos los datos /// <returns></returns>Universidad con todos los datos public static Universidad Leer(Universidad uni) { Xml <Universidad> xml = new Xml <Universidad>(); if (xml.Leer("Universidad.xml", out uni) == false) { SerializationException e = new SerializationException(); throw new ArchivosException(e); } return(uni); }
private static void TryPayload(object payload) { MemoryStream ms = new MemoryStream(); BinaryFormatter writer = new BinaryFormatter(); writer.Serialize(ms, payload); ms.Position = 0; BinaryFormatter reader = new BinaryFormatter(); SerializationException se = Assert.Throws <SerializationException>(() => reader.Deserialize(ms)); Assert.IsAssignableFrom <TargetInvocationException>(se.InnerException); }