public void CompileObjectInitializer(ObjectInitializer objectInit) { XmlElement tmpElement = document.CreateElement("ObjectInitializer"); ProcessPropertyInitializers(tmpElement, objectInit.PropertyInitializers); currentElement.AppendChild(tmpElement); }
private static T ReadAnyType(string line, StreamReader reader) { while ((string.IsNullOrWhiteSpace(line) || line.Split(_split, StringSplitOptions.RemoveEmptyEntries)[0] != _objectBegin) && !reader.EndOfStream) { line = reader.ReadLine(); } T value = _isValueType ? default : (T)ObjectInitializer.Create(typeof(T)); while (!reader.EndOfStream) { line = reader.ReadLine(); string[] parts = line.Split(_split, 2, StringSplitOptions.RemoveEmptyEntries); if (parts.Length > 0) { if (parts[0] == _objectEnd) { break; } else if (_readFieldActions.TryGetValue(parts[0].ToUpperInvariant(), out ReadFieldAction action)) { action(parts.Length > 1 ? parts[1] : null, reader, ref value); } } } return(value); }
/// <summary> /// Creates a new object initializer based of the given constructor meta data object. /// </summary> /// <typeparam name="T">Type of the object initializer</typeparam> /// <param name="ctor">Constructor meta data object</param> /// <returns>Object initializer</returns> public static ObjectInitializer <T> GetInitializer <T>(ConstructorInfo ctor) { // Type type = ctor.DeclaringType; ParameterInfo[] paramsInfo = ctor.GetParameters(); //create a single param of type object[] ParameterExpression param = Expression.Parameter(typeof(object[]), "args"); Expression[] argsExp = new Expression[paramsInfo.Length]; //pick each arg from the params array //and create a typed expression of them for (int i = -1; ++i < paramsInfo.Length;) { Expression index = Expression.Constant(i); Type paramType = paramsInfo[i].ParameterType; Expression paramAccessorExp = Expression.ArrayIndex(param, index); Expression paramCastExp = Expression.Convert(paramAccessorExp, paramType); argsExp[i] = paramCastExp; } //make a NewExpression that calls the //ctor with the args we just created NewExpression newExp = Expression.New(ctor, argsExp); //create a lambda with the New //Expression as body and our param object[] as arg LambdaExpression lambda = Expression.Lambda(typeof(ObjectInitializer <T>), newExp, param); //compile it ObjectInitializer <T> compiled = (ObjectInitializer <T>)lambda.Compile(); return(compiled); }
public void WithObjectInitializer() { ObjectInitializer newObject; try { newObject = new ObjectInitializer() { FirstName = firstName, LastName = lastName, Address = address, City = city, State = state, ZipCode = zipCode, BirthDate = birthDate, HireDate = hireDate, Age = GetAge(), YearsAtCompany = GetYearsAtCompany(), Salary = salary, Bonus = salary * GetYearsAtCompany() / (100 * fudgeFactor), VacationDays = GetVacationDays() / GetHoursPerDay(), HoursPerDay = GetHoursPerDay() / GetDaysPerWeek(), DaysPerWeek = GetDaysPerWeek() / GetYearsAtCompany() }; } catch (Exception e) { var error = e; throw; } Assert.IsNotNull(newObject); }
public void WithoutObjectInitializer() { var newObject = new ObjectInitializer(); try { newObject.FirstName = firstName; newObject.LastName = lastName; newObject.Address = address; newObject.City = city; newObject.State = state; newObject.ZipCode = zipCode; newObject.BirthDate = birthDate; newObject.HireDate = hireDate; newObject.Age = GetAge(); newObject.YearsAtCompany = GetYearsAtCompany(); newObject.Salary = salary; newObject.Bonus = salary * GetYearsAtCompany() / (100 * fudgeFactor); newObject.VacationDays = GetVacationDays() / GetHoursPerDay(); newObject.HoursPerDay = GetHoursPerDay() / GetDaysPerWeek(); newObject.DaysPerWeek = GetDaysPerWeek() / GetYearsAtCompany(); } catch (Exception e) { var error = e; throw; } Assert.IsNotNull(newObject); }
private void DatabaseForm_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'database1DataSet1.Maps' table. You can move, or remove it, as needed. // mapAdapter = new Database1DataSet1TableAdapters.MapsTableAdapter(); dataGridView1.AutoGenerateColumns = true; dataGridView1.DataSource = ObjectInitializer.InitializeAllMaps(); }
// Constructor called when creating or loading an object protected TP_ThirdPersonMonoCharacter(ObjectInitializer initializer) : base(initializer) { // Set size for collision capsule CapsuleComponent.SetCapsuleSize(42.0f, 96.0f); // set our turn rates for input BaseTurnRate = 45.0f; BaseLookUpRate = 45.0f; // Rotate the camera with the controller, not the character. UseControllerRotationPitch = false; UseControllerRotationYaw = false; UseControllerRotationRoll = false; // Configure character movement CharacterMovement.OrientRotationToMovement = true; // Character moves in the direction of input... CharacterMovement.RotationRate = new Rotator(0.0f, 540.0f, 0.0f); // ...at this rotation rate CharacterMovement.JumpZVelocity = 600.0f; CharacterMovement.AirControl = 0.2f; // Create a camera boom (pulls in towards the player if there is a collision) CameraBoom = initializer.CreateDefaultSubobject <SpringArmComponent> ("CameraBoom"); CameraBoom.SetupAttachment(RootComponent); CameraBoom.TargetArmLength = 300.0f; // The camera follows at this distance behind the character CameraBoom.UsePawnControlRotation = true; // Rotate the arm based on the controller // Create a follow camera FollowCamera = initializer.CreateDefaultSubobject <CameraComponent> ("FollowCamera"); FollowCamera.SetupAttachment(CameraBoom, SpringArmComponent.SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation FollowCamera.UsePawnControlRotation = false; // Camera does not rotate relative to arm // Note: The skeletal mesh and anim blueprint references on the Mesh component (inherited from Character) // are set in the derived blueprint asset named MyCharacter (to avoid direct content references in C#) }
public static int test() { var obj = new ObjectInitializer { Property = 3 }; return(obj.Property); }
// Constructor called when creating or loading an object protected TP_ThirdPersonMonoGameMode(ObjectInitializer initializer) : base(initializer) { if (initializer.TryFindClass <Pawn>("Class'/Game/Blueprints/MyCharacter.MyCharacter_C'", out var pawnClass)) { DefaultPawnClass = pawnClass; } }
public static IScopeContext LoadTypeFromFile(ObjectInitializer implementationReference) { var assembly = Assembly.LoadFile(implementationReference.AssemblyPath); if (assembly.IsIncorrectVersion(implementationReference)) throw new ModuleCreatorException(String.Format(IncorrectVersionOfTheAssemblyFound, assembly.FullName, implementationReference.AssemblyName)); var module = assembly.GetType(implementationReference.FullName); return module.ConvertToContext(); }
private static bool IsIncorrectVersion(this Assembly self, ObjectInitializer implementationReference) { if (implementationReference.AssemblyName.Contains("version")) { return(self.FullName.EqualsCaseInsensitive(implementationReference.AssemblyName)); } return(self.GetName().Name.EqualsCaseInsensitive(implementationReference.AssemblyName)); }
protected TestActor(ObjectInitializer initializer) : base(initializer) { MeshComponent = initializer.CreateDefaultSubobject <StaticMeshComponent> (new Name("StaticMeshComponent0")); SetRootComponent(MeshComponent); RotateClockwise = true; RotationRate = 20.0f; }
/// <summary> /// Recognizes expressions that start with the <b>new</b> keyword. /// </summary> /// <returns> /// An <see cref="ObjectInitializer"/> or a <see cref="ConstructorCall"/> /// </returns> protected Expression AtomStartingWithNew() { Expression expr; Token first = Match(TokenID.KW_New), last = null; SkipComments(); switch (token.TokenID) { case TokenID.LeftBrace: { Consume(1); PropertyInitializer[] fields = List <PropertyInitializer>( PropertyInitializer, true, Resources.DuplicatedProperty); last = Match(TokenID.RightBrace); expr = new ObjectInitializer(fields); } break; case TokenID.Identifier: { QualifiedName className = QualifiedName(ref first, ref last); var args = new Expression[0]; if (token.TokenID == TokenID.LeftParenthesis) { Consume(1); args = List <Expression>(Expression, false, null); last = Match(TokenID.RightParenthesis); } if (TryMatch(TokenID.LeftBrace)) { Consume(1); PropertyInitializer[] fields = List <PropertyInitializer>( PropertyInitializer, true, Resources.DuplicatedProperty); last = Match(TokenID.RightBrace); expr = new ConstructorCall(className, args, fields); } else { if (last == null) { throw new ParseException(FileName, token); } expr = new ConstructorCall(className, args, null); } } break; default: throw new ParseException(FileName, token, Resources.InvalidNewUsage); } expr.SetLocation(first.Start, last.End); return(expr); }
internal static IEnumerable<IScopeContext> GetClassList(ObjectInitializer implementationReference, Type ofType) { IEnumerable<Type> items; if (implementationReference.AssemblyName.IsNullOrEmpty()) { items = GetAllSubClassesOf(ofType); } else items = RetreiveSubTypesFromAssembly(ofType, Assembly.Load(implementationReference.AssemblyName)).ToList(); return (from i in items select i.ConvertToContext()).ToList(); }
internal static ScopeContext GetTypeFromFullName(ObjectInitializer implementationReference) { if (implementationReference.ModuleType.IsInstance()) { return(implementationReference.ModuleType.ConvertToContext().SetScope(implementationReference.Scope)); } var assembly = Assembly.Load(implementationReference.AssemblyName); var module = assembly.GetType(implementationReference.FullName).ConvertToContext().SetScope(implementationReference.Scope); return(module); }
internal static void Validate(this ObjectInitializer implementationReference) { if (implementationReference.IsNull()) { throw new ModuleCreatorException(ImplementationReferenceCannotBeNull); } if (implementationReference.Name.IsNullOrEmpty()) { throw new ModuleCreatorException(ImplementationReferenceNameCannotBeNullOrEmpty); } }
internal static ScopeContext GetTypeFromFullName(ObjectInitializer implementationReference, IDependencyResolver resolver) { if (implementationReference.ModuleType.IsInstance()) { return(implementationReference.ModuleType.ConvertToContext(null).SetScope(implementationReference.Scope)); } var assembly = Assembly.Load(implementationReference.AssemblyName); var module = assembly.GetType(implementationReference.FullName).ConvertToContext(new ContextProviders.ScopeContext(resolver)).SetScope(implementationReference.Scope); return(module); }
public static IScopeContext LoadTypeFromFile(ObjectInitializer implementationReference) { var assembly = Assembly.LoadFile(implementationReference.AssemblyPath); if (assembly.IsIncorrectVersion(implementationReference)) { throw new ModuleCreatorException(String.Format(IncorrectVersionOfTheAssemblyFound, assembly.FullName, implementationReference.AssemblyName)); } var module = assembly.GetType(implementationReference.FullName); return(module.ConvertToContext()); }
internal static IEnumerable <IScopeContext> GetClassList(ObjectInitializer implementationReference, Type ofType) { IEnumerable <Type> items; if (implementationReference.AssemblyName.IsNullOrEmpty()) { items = GetAllSubClassesOf(ofType); } else { items = RetreiveSubTypesFromAssembly(ofType, Assembly.Load(implementationReference.AssemblyName)).ToList(); } return((from i in items select i.ConvertToContext()).ToList()); }
static void Main(string[] args) { var aProblem = ProblemFactory.Get(ProblemEnmu.Rotate, SizeEnum.Small); var fileManger = new FileManager(aProblem.FileName); var input = fileManger.ReadFile(); var initializer = new ObjectInitializer(aProblem); dynamic inputProblems = typeof(ObjectInitializer) .GetMethod("InitializeObject") .MakeGenericMethod(aProblem.GetType()) .Invoke(initializer, new object[] { aProblem, input }); var printSolutions = new List <string>(); for (var index = 0; index < inputProblems.Cases; index++) { printSolutions.Add(string.Format("Case #{0}: {1}", (index + 1).ToString(), inputProblems.Problems[index].PrintSolution())); } fileManger.WriteFile(printSolutions); }
/// <summary> /// Creates a new instance of the given type with the given constructor parameters. /// </summary> /// <typeparam name="T">Type of the new instance</typeparam> /// <param name="type">Type of the object that shall be constructed</param> /// <param name="nonPublic">if TRUE a non public constructor can be used if needed</param> /// <param name="ctorValues">Constructor parameters</param> /// <returns>New instance of the type</returns> public static T NewInstance <T>(this Type type, bool nonPublic, params object[] ctorValues) { if (type == null) { throw new ArgumentNullException("type"); } if (!typeof(T).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())) { throw new InvalidCastException($"Current type '{type}' is not assignable to desired type '{typeof(T)}'"); } ConstructorInfo ctor = type.GetTypeInfo().DeclaredConstructors.FirstOrDefault(_ => _.GetParameters().Length == ctorValues.Length); // if (ctor == null && nonPublic) // ctor = type.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance) // .FirstOrDefault(_ => _.GetParameters().Length == ctorValues.Length); if (ctor == null) { throw new InvalidOperationException($"Could not resolve an constructor of type '{type}'"); } ObjectInitializer <T> initializer = GetInitializer <T>(ctor); return(initializer(ctorValues)); }
public void TestConstructor() { var problem = new Problem(); var hola = new ObjectInitializer(problem); }
public void CompileObjectInitializer(ObjectInitializer objInit) { textWriter.Write("new "); DumpPropertyInitializersList(objInit.PropertyInitializers); }
private void TravelButton_Click(object sender, EventArgs e) { List <Base> bas = ObjectInitializer.InitializeAllMaps(); MessageBox.Show(bas.Count.ToString() + " - number of bases"); }
public static int test() { var obj = new ObjectInitializer { Property = 3 }; return obj.Property; }
public static T GetInstance <T>(ObjectInitializer objectInitializer) { return((T)objectInitializer.ModuleType.Activate(objectInitializer.Scope)); }
protected virtual void AppendObjectInitializer(StringBuilder builder, ObjectInitializer objectInitializer) { builder.Append(objectInitializer); }
// Create object constructor protected MonoTestUserObject(ObjectInitializer initializer) : base(initializer) { }
// Constructor called when creating or loading an object protected TP_BlankMonoBPPlayerController(ObjectInitializer initializer) : base(initializer) { }
protected override void AppendObjectInitializer(StringBuilder builder, ObjectInitializer initializer) { builder.Append("{"); AppendAll(builder, ", ", initializer.Elements); builder.Append("}"); }
private static bool IsIncorrectVersion(this Assembly self, ObjectInitializer implementationReference) { if (implementationReference.AssemblyName.Contains("version")) return self.FullName.EqualsCaseInsensitive(implementationReference.AssemblyName); return self.GetName().Name.EqualsCaseInsensitive(implementationReference.AssemblyName); }
/// <summary> /// Converts given value in the required format (TYPE) /// </summary> /// <param name="input">value to be converted</param> /// <param name="type">format to be converted into</param> /// <returns></returns> public static object GetParametereValue(string input, string type) { return(ObjectInitializer.CastObject(input, type)); }
// Constructor called when creating or loading an object protected TP_BlankMonoGameMode(ObjectInitializer initializer) : base(initializer) { PlayerControllerClass = typeof(TP_BlankMonoPlayerController); }
/// <summary> /// Tests ObjectInitializer.cs /// </summary> public static void ObjectInitializer() { ObjectInitializer oi = new ObjectInitializer(); oi.ObjectInitializerTest(); }
internal static ScopeContext GetTypeFromFullName(ObjectInitializer implementationReference) { if (implementationReference.ModuleType.IsInstance()) return implementationReference.ModuleType.ConvertToContext().SetScope(implementationReference.Scope); var assembly = Assembly.Load(implementationReference.AssemblyName); var module = assembly.GetType(implementationReference.FullName).ConvertToContext().SetScope(implementationReference.Scope); return module; }