private void Add_Click(object sender, RoutedEventArgs e) { var type = (Type)Types.SelectedItem; if (typeof(Utilities.Trigger).IsAssignableFrom(type)) { var newTrigger = (Utilities.Trigger)FormatterServices.GetSafeUninitializedObject(type); newTrigger.Entity = new Trigger { Enabled = false, Type = type.FullName }; App.AppContext.Triggers.InsertOnSubmit(newTrigger.Entity); App.Triggers.Add(newTrigger); } if (!typeof(Utilities.Activity).IsAssignableFrom(type)) { return; } var newActivity = (Utilities.Activity)FormatterServices.GetSafeUninitializedObject(type); newActivity.Entity = new Life.Activity { Enabled = false, Type = type.FullName }; App.AppContext.Activities.InsertOnSubmit(newActivity.Entity); App.Activities.Add(newActivity); }
/// <summary> /// Creates a <see cref="T:Newtonsoft.Json.Serialization.JsonObjectContract"/> for the given type. /// </summary> /// <param name="objectType">Type of the object.</param> /// <returns> /// A <see cref="T:Newtonsoft.Json.Serialization.JsonObjectContract"/> for the given type. /// </returns> protected override JsonObjectContract CreateObjectContract(Type objectType) { // prepare contract using default resolver var objectContract = base.CreateObjectContract(objectType); // if type has constructor marked with JsonConstructor attribute or can't be instantiated, return default contract if (objectContract.OverrideConstructor != null || objectContract.CreatedType.IsInterface || objectContract.CreatedType.IsAbstract) { return(objectContract); } // prepare function to check that specified constructor parameter corresponds to non writable property on a type Func <JsonProperty, bool> isParameterForNonWritableProperty = parameter => { var propertyForParameter = objectContract.Properties.FirstOrDefault(property => property.PropertyName == parameter.PropertyName); if (propertyForParameter == null) { return(false); } return(!propertyForParameter.Writable); }; // if type has parameterized constructor and any of constructor parameters corresponds to non writable property, return default contract // this is needed to handle special cases for types that can be initialized only via constructor, i.e. Tuple<> if (objectContract.ParametrizedConstructor != null && objectContract.ConstructorParameters.Any(parameter => isParameterForNonWritableProperty(parameter))) { return(objectContract); } // override default creation method to create object without constructor call objectContract.DefaultCreatorNonPublic = false; objectContract.DefaultCreator = () => FormatterServices.GetSafeUninitializedObject(objectContract.CreatedType); return(objectContract); }
public ITool getControlType(string controlId) { Type controlType = null; if (listTools.ContainsKey(controlId)) { controlType = listTools[controlId]; } ITool control = (ITool)FormatterServices.GetSafeUninitializedObject(controlType); ConstructorInfo constructor = controlType.GetConstructor(Type.EmptyTypes); MethodBase method = (MethodBase)constructor; method.Invoke(control, null); control.InitiateSettings(eibFormDesigner); if (control.GetType().GetInterface(typeof(IEIBControl).Name) != null) { PropertyInfo propertyInfo = control.GetType().GetProperty("Name"); if (propertyInfo != null) { string name = (string)propertyInfo.GetGetMethod().Invoke(control, null); ((IEIBControl)control).ControlName = name; } } return(control); }
public static T[] ReadFile <T>(string path, char delim = ',') { var props = typeof(T).GetProperties(); T CreateInstanceFromRow(string[] row) { if (props.Length != row.Length) { throw new Exception("Unequivalent count of properties and rows"); } var ret = (T)FormatterServices.GetSafeUninitializedObject(typeof(T)); for (int i = 0; i < props.Length; i++) { props[i].SetValue(ret, Convert.ChangeType(row[i], props[i].PropertyType)); } return(ret); } return(File.ReadAllLines(path) .Select(l => l.Split(delim)) .Select(r => CreateInstanceFromRow(r)) .ToArray()); }
public object RecreateInterfaceProxy(string generatorType) { var @interface = DeserializeTypeFromString("__theInterface"); var targetType = DeserializeTypeFromString("__targetFieldType"); InterfaceProxyWithTargetGenerator generator; if (generatorType == ProxyTypeConstants.InterfaceWithTarget) { generator = new InterfaceProxyWithTargetGenerator(scope, @interface); } else if (generatorType == ProxyTypeConstants.InterfaceWithoutTarget) { generator = new InterfaceProxyWithoutTargetGenerator(scope, @interface); } else if (generatorType == ProxyTypeConstants.InterfaceWithTargetInterface) { generator = new InterfaceProxyWithTargetInterfaceGenerator(scope, @interface); } else { throw new InvalidOperationException( string.Format( "Got value {0} for the interface generator type, which is not known for the purpose of serialization.", generatorType)); } var proxyType = generator.GenerateCode(targetType, interfaces, proxyGenerationOptions); return(FormatterServices.GetSafeUninitializedObject(proxyType)); }
static void Run() { // Create an instance of a Book class // with a title and author. Book Book1 = new Book("Book Title 1", "Masato Kawai"); // Store data about the serializable members in a // MemberInfo array. The MemberInfo type holds // only type data, not instance data. MemberInfo[] members = FormatterServices.GetSerializableMembers (typeof(Book)); // Copy the data from the first book into an // array of objects. object[] data = FormatterServices.GetObjectData(Book1, members); // Create an uninitialized instance of the Book class. Book Book1Copy = (Book)FormatterServices.GetSafeUninitializedObject (typeof(Book)); // Call the PopuluateObjectMembers to copy the // data into the new Book instance. FormatterServices.PopulateObjectMembers (Book1Copy, members, data); // Print the data from the copy. Console.WriteLine("Title: {0}", Book1Copy.Title); Console.WriteLine("Author: {0}", Book1Copy.Author); }
private static object DeserializeStart(JObject jObject) { JToken typeToken = jObject["type"]; JToken originToken = jObject["origin"]; string typeString = typeToken.Value <string>(); string assemblyString = originToken.Value <string>(); string combined = Assembly.CreateQualifiedName(assemblyString, typeString); Type type = Type.GetType(combined); if (type == null) { return(null); } object objInstance = null; if (type.IsSubclassOf(typeof(ScriptableObject))) { objInstance = ScriptableObject.CreateInstance(type); } if (objInstance == null) { objInstance = FormatterServices.GetSafeUninitializedObject(type); } if (objInstance == null) { return(null); } IAdventuresUnknownSerializeCallback auSerializeCB = objInstance as IAdventuresUnknownSerializeCallback; if (auSerializeCB != null) { auSerializeCB.InitializeObject(); } return(objInstance); }
public void Add_Should_NotThrowException_WhenPassedArgumentIsValid() { // Arrange var mockedSet = new Mock <DbSet <IAdvert> >(); var mockedAdvert = new Mock <IAdvert>(); mockedSet.SetupAllProperties(); var mockedDbContext = new Mock <ICarSystemEfDbContext>(); var fakeEntry = (DbEntityEntry <IAdvert>)FormatterServices.GetSafeUninitializedObject(typeof(DbEntityEntry <IAdvert>)); // Act mockedDbContext.Setup(x => x.Set <IAdvert>()).Returns(mockedSet.Object); mockedDbContext.Setup(x => x.Entry(It.IsAny <IAdvert>())).Returns(fakeEntry); var mockedDbSet = new EfCarSystemDbSetCocoon <IAdvert>(mockedDbContext.Object); try { mockedDbSet.Add(mockedAdvert.Object); } catch (NullReferenceException e) { } // Assert mockedDbContext.Verify(x => x.Entry(mockedAdvert.Object), Times.AtLeastOnce); }
public void CompareFormatterServicesActivationAndDynamicFactoryMethod() { int iterations = 1000000; Stopwatch stopwatch1 = new Stopwatch(); Stopwatch stopwatch2 = new Stopwatch(); ConstructorInfo constructor = typeof(BenchmarkObject).GetConstructor(new Type[] { typeof(int), typeof(string) }); FactoryMethod factoryMethod = DynamicMethodFactory.CreateFactoryMethod(constructor); for (int index = 0; index < iterations; index++) { stopwatch1.Start(); BenchmarkObject mock1 = (BenchmarkObject)FormatterServices.GetSafeUninitializedObject(typeof(BenchmarkObject)); constructor.Invoke(mock1, new object[] { 42, "foobar" }); stopwatch1.Stop(); stopwatch2.Start(); BenchmarkObject mock2 = (BenchmarkObject)factoryMethod(42, "foobar"); stopwatch2.Stop(); } Console.WriteLine("{0:0,0} iterations:", iterations); Console.WriteLine("FormatterServices/Constructor.Invoke: {0:0,0} ms", stopwatch1.ElapsedMilliseconds); Console.WriteLine("Dynamic FactoryMethod: {0:0,0} ms", stopwatch2.ElapsedMilliseconds); Console.WriteLine("Speedup: {0:f}x", ((double)stopwatch1.ElapsedMilliseconds / (double)stopwatch2.ElapsedMilliseconds)); }
static DocumentTypeFactory() { if (FormatterServices.GetSafeUninitializedObject(typeof(T)) is T type) { Types[typeof(T)] = type.DocumentType; } }
public void UniqueTags() { var operators = (from t in typeof(Subscribable).Assembly.GetTypes() let b = t.BaseType where b != null && b.IsGenericType let d = b.IsGenericTypeDefinition ? b : b.GetGenericTypeDefinition() where d == typeof(SubscribableBase <>) select t) .ToArray(); var sinks = (from o in operators from i in o.GetNestedTypes(BindingFlags.NonPublic) where typeof(IVersioned).IsAssignableFrom(i) where !i.IsAbstract let j = i.IsGenericTypeDefinition ? i.MakeGenericType(i.GetGenericArguments().Select(_ => typeof(object)).ToArray()) : i let v = (IVersioned)FormatterServices.GetSafeUninitializedObject(j) select(Operator: o, Sink: i, v.Version, v.Name)) .ToArray(); var minVer = new Version(1, 0, 0, 0); var tooOld = sinks.Where(s => s.Version < minVer).ToList(); if (tooOld.Count > 0) { Assert.Fail("Operators with version < " + minVer + " detected: " + string.Join(", ", tooOld.Select(t => t.Name))); } var conflictingNames = sinks.GroupBy(g => g.Name).Where(g => g.Count() > 1).ToList(); if (conflictingNames.Count > 0) { Assert.Fail("Operators with conflicting names detected: " + string.Join(", ", conflictingNames.Select(t => t.Key))); } }
public override T Create(Type objectType) { var type = Type.GetType(objectType.Name); var safeUninitializedObject = FormatterServices.GetSafeUninitializedObject(objectType); return((T)safeUninitializedObject); }
public DomainObject CreateObjectReference(IObjectInitializationContext objectInitializationContext, ClientTransaction clientTransaction) { ArgumentUtility.CheckNotNull("objectInitializationContext", objectInitializationContext); ArgumentUtility.CheckNotNull("clientTransaction", clientTransaction); var objectID = objectInitializationContext.ObjectID; CheckDomainTypeAndClassDefinition(objectID.ClassDefinition.ClassType); objectID.ClassDefinition.ValidateCurrentMixinConfiguration(); var concreteType = Pipeline.ReflectionService.GetAssembledType(objectID.ClassDefinition.ClassType); var instance = (DomainObject)FormatterServices.GetSafeUninitializedObject(concreteType); Pipeline.ReflectionService.PrepareExternalUninitializedObject(instance, InitializationSemantics.Construction); // These calls are normally performed by DomainObject's ctor instance.Initialize(objectID, objectInitializationContext.RootTransaction); objectInitializationContext.RegisterObject(instance); using (clientTransaction.EnterNonDiscardingScope()) { instance.RaiseReferenceInitializatingEvent(); } return(instance); }
public static T ReadClass <T>(this PacketReader packet) where T : IPacketDeserializable { T type = (T)FormatterServices.GetSafeUninitializedObject(typeof(T)); type.ReadFrom(packet); return(type); }
public IQueryable <TAggregateRoot> Set <TAggregateRoot>() where TAggregateRoot : AggregateRoot { var aggregates = new List <TAggregateRoot>(); var aggregateName = typeof(TAggregateRoot).Name; var storedEventsGroups = from storedEvent in GetStoredEvents(aggregateName) group storedEvent by storedEvent.StreamId into storedEventsGroup orderby storedEventsGroup.Key select storedEventsGroup; foreach (var storedEventGroup in storedEventsGroups) { var aggregate = (TAggregateRoot)FormatterServices .GetSafeUninitializedObject(typeof(TAggregateRoot)); foreach (var storedEvent in storedEventGroup.OrderBy(x => x.CreatedAt)) { aggregate.Apply( JsonConvert.DeserializeObject( storedEvent.Data, Type.GetType(storedEvent.DotNetType))); } aggregates.Add(aggregate); } return(aggregates.AsQueryable()); }
public MixinSerializationHelper(SerializationInfo info, StreamingContext context) { ArgumentUtility.CheckNotNull("info", info); _context = context; var identifierDeserializer = new SerializationInfoConcreteMixinTypeIdentifierDeserializer(info, "__identifier"); var identifier = ConcreteMixinTypeIdentifier.Deserialize(identifierDeserializer); var pipelineIdentifier = info.GetString("__participantConfigurationID"); var pipeline = SafeServiceLocator.Current.GetInstance <IPipelineRegistry>().Get(pipelineIdentifier); var mixinType = pipeline.ReflectionService.GetAdditionalType(identifier); _baseMemberValues = (object[])info.GetValue("__baseMemberValues", typeof(object[])); // Usually, instantiate a deserialized object using GetSafeUninitializedObject. // However, _baseMemberValues being null means that the object itself manages its member deserialization via ISerializable. In such a case, we // need to use the deserialization constructor to instantiate the object. if (_baseMemberValues != null) { _deserializedObject = FormatterServices.GetSafeUninitializedObject(mixinType); } else { Assertion.IsTrue(typeof(ISerializable).IsAssignableFrom(mixinType)); _deserializedObject = Activator.CreateInstance( mixinType, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] { info, context }, null); } SerializationImplementer.RaiseOnDeserializing(_deserializedObject, _context); }
public object Deserialize(Stream stream) { ResultDTO safeUninitializedObject = (ResultDTO)FormatterServices.GetSafeUninitializedObject(typeof(ResultDTO)); this.Transfer(safeUninitializedObject, new Reader(stream)); return(safeUninitializedObject); }
public object Desirialize(int offset, DynamicBuffer buffer, Dictionary <int, object> referenceMaping) { short position = (short)offset == 0 ? (short)0 : BitConverter.ToInt16(buffer.CurrentBuffer, offset); if (position == -1) { return(null); } object entity; if (referenceMaping.TryGetValue(position, out entity)) { return(entity); } else { entity = FormatterServices.GetSafeUninitializedObject(typeInfo.Type); } referenceMaping.Add(position, entity); ObjectFlag flag = (ObjectFlag)buffer.CurrentBuffer[offset]; position++; foreach (var member in typeInfo.Fields) { var memberTypeInfo = TypeInfo.instanse(member.FieldType); object innerObject = memberTypeInfo.Resolver.Desirialize(position, buffer, referenceMaping); entity = typeInfo.SetValue(entity, innerObject, member); position += (short)memberTypeInfo.SizeInBuffer; } return(entity); }
private void AddToSerializationInfo(string[] dataLine, SerializationInfo _info) { string[] keyValue = dataLine[0].Split('='); object obj; if (Regex.IsMatch(keyValue[1], @"^href[$]\d*")) { Type type = Binder.BindToType(dataLine[2], dataLine[1]); if (!deserializedObjects.ContainsKey(keyValue[1])) { obj = FormatterServices.GetSafeUninitializedObject(type); deserializedObjects.Add(keyValue[1], obj); } else { obj = deserializedObjects[keyValue[1]]; } _info.AddValue(keyValue[0], obj, type); } else { Type type = Type.GetType(dataLine[1]); ParseAndAddToSerializationInfo(type, keyValue[0], keyValue[1], _info); } }
public override ResourceEvent <T> Read( ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType != JsonTokenType.StartObject) { throw new JsonException("Unexpected end when reading JSON."); } // Ignore the fact that we have no empty constructors. We fill in all the properties anyway var resourceEvent = (ResourceEvent <T>)FormatterServices.GetSafeUninitializedObject(typeToConvert); // We do not serialise this to JSON, but given this is a typed read we can set in behind the scenes here resourceEvent.ResourceType = typeof(T); while (reader.Read() && reader.TokenType != JsonTokenType.EndObject) { ReadValue(ref reader, resourceEvent, options); } if (reader.TokenType != JsonTokenType.EndObject) { throw new JsonException("Unexpected end when reading JSON."); } return(resourceEvent); }
public static void FormatterServices_GetUninitializedObject_Throws() { // Like String, shouldn't be able to create an uninitialized Utf8String. Assert.Throws <ArgumentException>(() => FormatterServices.GetSafeUninitializedObject(typeof(Utf8String))); Assert.Throws <ArgumentException>(() => FormatterServices.GetUninitializedObject(typeof(Utf8String))); }
public object Deserialize(Stream stream) { ResultDTO resultDTO = (ResultDTO)FormatterServices.GetSafeUninitializedObject(typeof(ResultDTO)); Transfer(resultDTO, new Reader(stream)); return(resultDTO); }
static GenericInterpolation() { const string interpolation_method = nameof(GenericInterpolation <TEasing> .ValueAt); var parameters = typeof(InterpolationFunc <TValue, TEasing>) .GetMethod(nameof(InterpolationFunc <TValue, TEasing> .Invoke)) ?.GetParameters().Select(p => p.ParameterType).ToArray(); MethodInfo valueAtMethod = typeof(GenericInterpolation <TEasing>).GetMethod(interpolation_method, parameters); if (valueAtMethod != null) { FUNCTION = (InterpolationFunc <TValue, TEasing>)valueAtMethod.CreateDelegate(typeof(InterpolationFunc <TValue, TEasing>)); } else { var typeRef = FormatterServices.GetSafeUninitializedObject(typeof(TValue)) as IInterpolable <TValue>; if (typeRef == null) { throw new NotSupportedException($"Type {typeof(TValue)} has no interpolation function. Implement the interface {typeof(IInterpolable<TValue>)} interface on the object."); } FUNCTION = typeRef.ValueAt; } }
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { if (!base.TryInvokeMember(binder, args, out result)) { var memberName = (binder.Name == "ctor" || binder.Name == "cctor") ? "." + binder.Name : binder.Name; var method = FindBestMatch(binder, memberName, args); if (method != null) { if (binder.Name == "ctor") { var instance = this.target; if (instance == null) { instance = FormatterServices.GetSafeUninitializedObject(this.targetType); } result = Invoke(method, instance, args); result = instance.AsDynamicReflection(); } else { result = AsDynamicIfNecessary(Invoke(method, this.target, args)); } return(true); } } result = default(object); return(false); }
private void ReadObjectContent(BinaryReader reader, ObjectReader.TypeMetadata metadata, long objectId, out object objectInstance, out SerializationInfo info) { if (this._filterLevel == TypeFilterLevel.Low) { objectInstance = FormatterServices.GetSafeUninitializedObject(metadata.Type); } else { objectInstance = FormatterServices.GetUninitializedObject(metadata.Type); } this._manager.RaiseOnDeserializingEvent(objectInstance); info = ((!metadata.NeedsSerializationInfo) ? null : new SerializationInfo(metadata.Type, new FormatterConverter())); if (metadata.MemberNames != null) { for (int i = 0; i < metadata.FieldCount; i++) { this.ReadValue(reader, objectInstance, objectId, info, metadata.MemberTypes[i], metadata.MemberNames[i], null, null); } } else { for (int j = 0; j < metadata.FieldCount; j++) { this.ReadValue(reader, objectInstance, objectId, info, metadata.MemberTypes[j], metadata.MemberInfos[j].Name, metadata.MemberInfos[j], null); } } }
private void ReadObjectContent(BinaryReader reader, TypeMetadata metadata, long objectId, out object objectInstance, out SerializationInfo info) { #if NET_1_1 if (_filterLevel == TypeFilterLevel.Low) { objectInstance = FormatterServices.GetSafeUninitializedObject(metadata.Type); } else #endif objectInstance = FormatterServices.GetUninitializedObject(metadata.Type); #if NET_2_0 _manager.RaiseOnDeserializingEvent(objectInstance); #endif info = metadata.NeedsSerializationInfo ? new SerializationInfo(metadata.Type, new FormatterConverter()) : null; if (metadata.MemberNames != null) { for (int n = 0; n < metadata.FieldCount; n++) { ReadValue(reader, objectInstance, objectId, info, metadata.MemberTypes[n], metadata.MemberNames[n], null, null); } } else { for (int n = 0; n < metadata.FieldCount; n++) { ReadValue(reader, objectInstance, objectId, info, metadata.MemberTypes[n], metadata.MemberInfos[n].Name, metadata.MemberInfos[n], null); } } }
public void NotThrow_WhenArgumentIsValid() { // Arrange var mockedSet = new Mock <IDbSet <IProject> >(); var mockedModel = new Mock <IProject>(); mockedModel.SetupAllProperties(); var fakeEntry = (DbEntityEntry <IProject>)FormatterServices .GetSafeUninitializedObject(typeof(DbEntityEntry <IProject>)); var mockedContext = new Mock <IPortfolioCmsDbContext>(); mockedContext.Setup(x => x.Set <IProject>()).Returns(mockedSet.Object); mockedContext.Setup(x => x.Entry(It.IsAny <IProject>())).Returns(fakeEntry); // Act var repository = new EFRepository <IProject>(mockedContext.Object); try { repository.Add(mockedModel.Object); } catch (NullReferenceException e) { }; // Assert mockedContext.Verify(x => x.Entry(mockedModel.Object), Times.AtLeastOnce); }
public virtual void Init() { data.instance = CreateInstance(data.appInfo); var ptrProp = (typeof(IMarshalling)).GetProperty("Handle"); var ptr = (IntPtr)ptrProp.GetValue(data.instance); SDL.SDL_Vulkan_CreateSurface(data.windowPtr, ptr, out IntPtr surface); data.surface = (SurfaceKhr)FormatterServices.GetSafeUninitializedObject(typeof(SurfaceKhr)); var surfFld = typeof(SurfaceKhr).GetRuntimeFields().First(); surfFld.SetValue(data.surface, (UInt64)surface.ToInt64()); var devices = data.instance.EnumeratePhysicalDevices(); if (devices.Length == 0) { throw new Exception("No devices found"); } data.physicalDevice = devices.FirstOrDefault(IsDeviceSuitable); if (data.physicalDevice == null) { throw new Exception("No Suitable Device found"); } data.view.Initialize(data); gameInit.Set(); }
private object BuildUpNewObject(IBuilderContext context, Type typeToBuild, object existing, string idToBuild) { ICreationPolicy policy = context.Policies.Get <ICreationPolicy>(typeToBuild, idToBuild); if (policy == null) { if (idToBuild == null) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Properties.Resources.MissingPolicyUnnamed, typeToBuild)); } else { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Properties.Resources.MissingPolicyNamed, typeToBuild, idToBuild)); } } try { existing = FormatterServices.GetSafeUninitializedObject(typeToBuild); } catch (MemberAccessException exception) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Properties.Resources.CannotCreateInstanceOfType, typeToBuild), exception); } RegisterObject(context, typeToBuild, existing, idToBuild); InitializeObject(context, existing, idToBuild, policy); return(existing); }
public void NotThrowExceptionWhenPassedArgumentIsValid() { // Arrange var mockedSet = new Mock <DbSet <ICreature> >(); var mockedAdvert = new Mock <ICreature>(); mockedSet.SetupAllProperties(); var mockedDbContext = new Mock <IAquaWorldDbContext>(); var fakeEntry = (DbEntityEntry <ICreature>)FormatterServices.GetSafeUninitializedObject(typeof(DbEntityEntry <ICreature>)); // Act mockedDbContext.Setup(x => x.Set <ICreature>()).Returns(mockedSet.Object); mockedDbContext.Setup(x => x.Entry(It.IsAny <ICreature>())).Returns(fakeEntry); var dataProvider = new EfAquaWorldDataProvider <ICreature>(mockedDbContext.Object); try { dataProvider.Add(mockedAdvert.Object); } catch (NullReferenceException) { } // Assert mockedDbContext.Verify(x => x.Entry(mockedAdvert.Object), Times.AtLeastOnce); }