protected override T PerformInsert <T>(T ValueToInsert)// where T : PersistentBase { Type type = ValueToInsert.GetType(); string TableName = type.GetCustomAttribute <PersistentTableName>().TableName; string query = "INSERT INTO [" + TableName + "]("; string values = " Values ("; bool first = true; int i = 1; SQLiteCommand tmpCommand = new SQLiteCommand(); foreach (PropertyInfo PI in type.GetProperties()) { if (!PI.PropertyType.IsArray && PI.Name.ToLower() != "id" && PI.GetCustomAttribute(typeof(NonPersistent)) == null) { if (!first) { query += ", "; values += ","; } first = false; query += "[" + PI.Name + "]"; values += "@" + i.ToString(); tmpCommand.Parameters.AddWithValue("@" + i++.ToString(), PI.GetValue(ValueToInsert)); } } query += ") "; values += "); select last_insert_rowid()"; tmpCommand.CommandText = query + values; tmpCommand.Connection = Connection; //Set sql connection here ValueToInsert.Id = (int)(long)tmpCommand.ExecuteScalar(); return(ValueToInsert); }
/// <summary> /// Populates a Dictionary with information about our runtime environment. /// </summary> private static void BuildBaseEnvironmentalInfo(IDictionary <string, object> dict) { Dictionary <string, object> EnvDict = new Dictionary <string, object>(); dict["Environment"] = EnvDict; //DictTryPopulate<DebugInformationProvider>(EnvDict); //DictTryPopulate<ManagedSecurityContextInformationProvider>(EnvDict); //DictTryPopulate<UnmanagedSecurityContextInformationProvider>(EnvDict); //DictTryAdd(EnvDict, "AssemblyFullNameEntry", () => Assembly.GetEntryAssembly().InvokeUnlessDefault(A => A.FullName, null)); //DictTryAdd(EnvDict, "AssemblyFullNameExecuting", () => Assembly.GetExecutingAssembly().InvokeUnlessDefault(A => A.FullName, null)); //DictTryAdd(EnvDict, "AssemblyFullNameCalling", () => Assembly.GetCallingAssembly().InvokeUnlessDefault(A => A.FullName, null)); DictTryAdd(EnvDict, "CommandLine", () => Environment.CommandLine); DictTryAdd(EnvDict, "CurrentDirectory", () => Environment.CurrentDirectory); DictTryAdd(EnvDict, "HasShutdownStarted", () => Environment.HasShutdownStarted); DictTryAdd(EnvDict, "Is64BitOperatingSystem", () => Environment.Is64BitOperatingSystem); DictTryAdd(EnvDict, "Is64BitProcess", () => Environment.Is64BitProcess); DictTryAdd(EnvDict, "MachineName", () => Environment.MachineName); DictTryAdd(EnvDict, "OSVersion", () => Environment.OSVersion); DictTryAdd(EnvDict, "ProcessorCount", () => Environment.ProcessorCount); DictTryAdd(EnvDict, "SystemDirectory", () => Environment.SystemDirectory); DictTryAdd(EnvDict, "SystemPageSize", () => Environment.SystemPageSize); DictTryAdd(EnvDict, "TickCount", () => Environment.TickCount); DictTryAdd(EnvDict, "UserDomainName", () => Environment.UserDomainName); DictTryAdd(EnvDict, "UserInteractive", () => Environment.UserInteractive); DictTryAdd(EnvDict, "UserName", () => Environment.UserName); DictTryAdd(EnvDict, "Version", () => Environment.Version); DictTryAdd(EnvDict, "WorkingSet", () => Environment.WorkingSet); Dictionary <string, object> ConfigDict = new Dictionary <string, object>(); dict["LogConfig"] = ConfigDict; foreach (PropertyInfo PI in typeof(LocalConfig).GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static) .Where(P => P.CanRead && !P.GetIndexParameters().Any())) { DictTryAdd(ConfigDict, PI.Name, () => PI.GetValue(null, null)); } HttpContext HttpCtx = HttpContext.Current; if (HttpCtx != null) { Dictionary <string, object> HttpDict = new Dictionary <string, object>(); dict["HttpContext"] = HttpDict; DictTryAdd(HttpDict, "RequestServerVariables", () => new NameValueCollection(HttpCtx.Request.ServerVariables)); DictTryAdd(HttpDict, "RequestQueryString", () => HttpCtx.Request.QueryString); DictTryAdd(HttpDict, "RequestForm", () => HttpCtx.Request.Form); DictTryAdd(HttpDict, "RequestCookies", () => HttpCtx.Request.Cookies); } if (LogExtraInfo != null) { LogExtraInfo(new object(), new EventArgs()); } lock (ExtraEnvironmentInfo) foreach (KeyValuePair <string, object> P in ExtraEnvironmentInfo) { dict[P.Key] = P.Value; } }
/// <summary> /// Evaluates the node, using the variables provided in the <paramref name="Variables"/> collection. /// </summary> /// <param name="Variables">Variables collection.</param> /// <returns>Result.</returns> public override IElement Evaluate(Variables Variables) { IElement E = this.Argument.Evaluate(Variables); object Obj = E.AssociatedObjectValue; List <IElement> Elements = new List <IElement>(); if (Obj is Type T) { foreach (PropertyInfo PI in T.GetTypeInfo().DeclaredProperties) { Elements.Add(new StringValue(PI.Name)); } return(new ObjectVector(Elements)); } else { T = Obj.GetType(); foreach (PropertyInfo PI in T.GetTypeInfo().DeclaredProperties) { Elements.Add(new StringValue(PI.Name)); Elements.Add(Expression.Encapsulate(PI.GetValue(Obj))); } ObjectMatrix M = new ObjectMatrix(Elements.Count / 2, 2, Elements) { ColumnNames = new string[] { "Name", "Value" } }; return(M); } }
protected override T PerformInsert <T>(T ValueToInsert)// where T : PersistentBase { Type type = ValueToInsert.GetType(); string TableName = type.GetCustomAttribute <PersistentTableName>().TableName; string query = "SELECT INTO [" + TableName + "]("; string values = " output INSERTED.ID VALUES("; bool first = true; int i = 1; MySqlCommand tmpCommand = new MySqlCommand(); foreach (PropertyInfo PI in type.GetProperties()) { if (!PI.PropertyType.IsArray && PI.Name.ToLower() != "id") { if (!first) { query += ", "; values += ","; } first = false; query += "[" + PI.Name + "]"; values += "@" + i.ToString(); tmpCommand.Parameters.AddWithValue("@" + i++.ToString(), PI.GetValue(ValueToInsert)); } } query += ") "; tmpCommand.CommandText = query + values; //tmpCommand.Connection = SqlConnection //Set sql connection here ValueToInsert.Id = (int)tmpCommand.ExecuteScalar(); return(ValueToInsert); }
private void UpdateOutputControllerProperties(IOutputController OutputController) { DataTable DT = new DataTable(); DT.Columns.Add("Property", typeof(string)); DT.Columns.Add("Value", typeof(string)); if (OutputController != null) { DT.Rows.Add("Name", OutputController.Name); DT.Rows.Add("Output Count", OutputController.Outputs.Count); Type T = OutputController.GetType(); foreach (PropertyInfo PI in T.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { if (PI.Name != "Name" && PI.Name != "Outputs") { DT.Rows.Add(PI.Name, PI.GetValue(OutputController, new object[] { }).ToString()); } } } CabinetOutputControllerProperties.ClearSelection(); CabinetOutputControllerProperties.Columns.Clear(); CabinetOutputControllerProperties.AutoGenerateColumns = true; CabinetOutputControllerProperties.DataSource = DT; CabinetOutputControllerProperties.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells); CabinetOutputControllerProperties.Refresh(); }
/// <summary> /// Takes the two objects from the constructor and checks for differences between the object types decorated with the Audited attribute. /// Differences between the two objects are logged in the Changes List. /// </summary> public void Audit() { try { PropertyInfo[] propertyList = X.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach (PropertyInfo PI in propertyList) { if (IsAudited(PI)) { if (isOfSimpleType(PI.GetValue(X, null))) { Compare(new TypePropertyInfoPair(X.GetType(), PI)); } else { ChangeLogger logger = new ChangeLogger(this.Id, this.GlobalSettings, PI, PI.GetValue(X, null), PI.GetValue(Y, null)); logger.Audit(); } } if (this.GlobalSettings.PropertyChain.Count > 0 && propertyList[(propertyList.Length - 1)] == PI) this.GlobalSettings.PropertyChain.RemoveAt((this.GlobalSettings.PropertyChain.Count - 1)); } } catch (Exception ex) { this.Success = false; this.Exception = ex; } }
static ColorAttribute() { stringToColor = new Dictionary <string, SKColor>(); rgbaToName = new Dictionary <string, string>(); Type T = typeof(SKColors); foreach (PropertyInfo PI in T.GetRuntimeProperties()) { if (PI.PropertyType == typeof(SKColor)) { SKColor Color = (SKColor)PI.GetValue(null); stringToColor[PI.Name] = Color; rgbaToName[ToRGBA(Color)] = PI.Name; } } foreach (FieldInfo FI in T.GetRuntimeFields()) { if (FI.FieldType == typeof(SKColor)) { SKColor Color = (SKColor)FI.GetValue(null); stringToColor[FI.Name] = Color; rgbaToName[ToRGBA(Color)] = FI.Name; } } }
private void UpdateEffectProperties(IEffect Effect) { DataTable DT = new DataTable(); DT.Columns.Add("Property", typeof(string)); DT.Columns.Add("Value", typeof(string)); if (Effect != null) { DT.Rows.Add("Name", Effect.Name); Type T = Effect.GetType(); DT.Rows.Add("Type", T.Name); foreach (PropertyInfo PI in T.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { if (PI.Name != "Name") { DT.Rows.Add(PI.Name, PI.GetValue(Effect, new object[] { }).ToString()); } } } TableEffectProperties.ClearSelection(); TableEffectProperties.Columns.Clear(); TableEffectProperties.AutoGenerateColumns = true; TableEffectProperties.DataSource = DT; TableEffectProperties.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells); TableEffectProperties.Refresh(); }
/// <summary> /// This method is used to set the DirtyStatus to NoChange to item and it's child items /// </summary> public void SetDirtyStatusToNoChange() { DirtyStatus = eDirtyStatus.NoChange; // Properties foreach (PropertyInfo PI in this.GetType().GetProperties()) { var token = PI.GetCustomAttribute(typeof(IsSerializedForLocalRepositoryAttribute)); if (token == null) { continue; } if (typeof(IObservableList).IsAssignableFrom(PI.PropertyType)) { IObservableList obj = (IObservableList)PI.GetValue(this); if (obj == null) { continue; } foreach (object o in obj) { if (o is RepositoryItemBase) { ((RepositoryItemBase)o).SetDirtyStatusToNoChange(); } } } } // Fields foreach (FieldInfo FI in this.GetType().GetFields()) { var token = FI.GetCustomAttribute(typeof(IsSerializedForLocalRepositoryAttribute)); if (token == null) { continue; } if (typeof(IObservableList).IsAssignableFrom(FI.FieldType)) { IObservableList obj = (IObservableList)FI.GetValue(this); if (obj == null) { return; } foreach (object o in obj) { if (o is RepositoryItemBase) { ((RepositoryItemBase)o).SetDirtyStatusToNoChange(); } } } } }
protected async Task <IDictionary <string, string> > ExtractQueryParameters <T>(T item) where T : ModelElement { IDictionary <string, string> data = new Dictionary <string, string>(); await Task.Run(() => { foreach (PropertyInfo PI in item.GetType().GetProperties()) { string propertyValue = JsonConvert.SerializeObject(PI.GetValue(item)).Trim('\"'); data.Add(PI.Name, propertyValue); } }); return(data); }
//метод для установки Childs и ChildType public virtual void SetNodes() { foreach (PropertyInfo PI in GetType().GetProperties()) { //атрибут текущего объекта (false - без родителей) ChildsAttribute ChildsAttribute = PI.GetCustomAttribute <ChildsAttribute>(false); if (ChildsAttribute != null) { Childs = PI.GetValue(this); ChildType = ChildsAttribute.ChildType; break; } } }
public NewPayLoad GetObjectAsPayLoad(string PLName, Attribute attr) { NewPayLoad PL = new NewPayLoad(PLName); PL.AddValue(mObj.GetType().FullName); List <PropertyInfo> list = GetProperties(attr); foreach (PropertyInfo PI in list) { dynamic v = PI.GetValue(mObj); // Enum might be unknown = not set - so no need to write to xml, like null for object if (PI.PropertyType.IsEnum) { string vs = v.ToString(); // No need to write enum unknown = null if (vs != "Unknown") { PL.AddEnumValue(v); } } else if (v is IObservableList) { List <NewPayLoad> lst = new List <NewPayLoad>(); foreach (object o in v) { ObjectReflectionHelper ORHItem = new ObjectReflectionHelper(); ORHItem.obj = o; NewPayLoad PL1 = ORHItem.GetObjectAsPayLoad("Item", attr); lst.Add(PL1); } PL.AddListPayLoad(lst); } else if (PI.PropertyType.Name == "String") { PL.AddValue((string)v); } else { throw new Exception("Unknown type to handle - " + v); } } PL.ClosePackage(); return(PL); }
public object ObjectToLisp(object prim) { OSD data = OSD.FromObject(prim); if (data.Type != OSDType.Unknown) { return(SerializeLisp(data)); } Type t = prim.GetType(); foreach (FieldInfo PI in t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)) { object value = ToLispValue(PI.FieldType, PI.GetValue(prim)); object kv = new Cons(PI.Name, new Cons(value, null)); } return(prim); }
public static Dictionary <object, object> GetProperties(object source, bool canWriteCheck = true, bool canReadCheck = true) { Type TSource = source.GetType(); PropertyInfo[] APInfo = TSource.GetProperties(); Dictionary <object, object> DSOData = new Dictionary <object, object>(); List <Exception> LExceptions = new List <Exception>(); foreach (PropertyInfo PI in APInfo) { if (canWriteCheck && !PI.CanWrite) { continue; } else if (canReadCheck && !PI.CanRead) { continue; } else { try { object oValue = PI.GetValue(source, null); string sName = nameof(oValue); if (sName == null) { sName = PI.Name; } if (!DSOData.ContainsKey(sName)) { DSOData.Add(sName, oValue);//PI.PropertyType.FullName + " " + } } catch (Exception e) { LExceptions.Add(e); continue; } } } return(DSOData); }
//получить коллекцию ячеек для заголовка таблицы public List <CellContainer> GetCellContainers() { List <CellContainer> CellContainers = new List <CellContainer>(); //словарь для выпадающего списка var DictCombobox = new Dictionary <string, List <string> >(); foreach (PropertyInfo PI in GetType().GetProperties()) { object oVal = PI.GetValue(this); //перебор атрибутов (false - без родителей) //заполнение колекций выпадающий списков foreach (ColumnComboboxDataAttribute ColumnCombobox in PI.GetCustomAttributes <ColumnComboboxDataAttribute>(false)) { if (oVal == null) { return(null); } List <string> ComboboxVals = (List <string>)oVal; if (ComboboxVals.Count == 0) { return(null); } string headerPropName = ColumnCombobox.headerPropName; if (DictCombobox.ContainsKey(headerPropName)) { continue; } DictCombobox.Add(headerPropName, ComboboxVals); } } foreach (PropertyInfo PI in GetType().GetProperties()) { object oVal = PI.GetValue(this); //перебор атрибутов (false - без родителей) //заполнение коллекции заголовков ячеек таблицы (HeaderCellContainer) foreach (ColumnAttribute Column in PI.GetCustomAttributes <ColumnAttribute>(false)) { CellContainer CC = GetCellContainer(Column, oVal, DictCombobox); CellContainers.Add(CC); } } return(CellContainers.OrderBy(q => q.CI.columnIndex).ToList()); }
protected async Task <string> ExtractJsonQueryBody <T, R>(T item) where T : ModelElement where R : ExportField { string body = "{ "; await Task.Run(() => { foreach (PropertyInfo PI in item.GetType().GetProperties()) { if (PI.CustomAttributes.Select(A => A.AttributeType).Contains(typeof(R))) { string propertyValue = JsonConvert.SerializeObject(PI.GetValue(item)); body += '"' + PI.Name + '"' + " : " + propertyValue + ", "; } } }); return(body.Length <= 2 ? "{ }" : (body.Substring(0, body.Length - 2) + " }")); }
protected async Task <IDictionary <string, string> > ExtractQueryParameters <T, R>(T item) where T : ModelElement where R : ExportField { IDictionary <string, string> data = new Dictionary <string, string>(); await Task.Run(() => { foreach (PropertyInfo PI in item.GetType().GetProperties()) { if (PI.CustomAttributes.Select(A => A.AttributeType).Contains(typeof(R))) { string propertyValue = JsonConvert.SerializeObject(PI.GetValue(item)).Trim('\"'); data.Add(PI.Name, propertyValue); } } }); return(data); }
private void UpdateOutputs(IOutputController OutputController) { DataTable DT = new DataTable(); DT.Columns.Add("Name", typeof(string)); if (OutputController != null) { if (OutputController.Outputs.Count > 0) { Type T = OutputController.Outputs[0].GetType(); foreach (PropertyInfo PI in T.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { if (PI.Name != "Name") { DT.Columns.Add(PI.Name, PI.PropertyType); } } foreach (IOutput O in OutputController.Outputs) { object[] values = new object[DT.Columns.Count]; values[0] = O.Name; int Index = 1; foreach (PropertyInfo PI in T.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { if (PI.Name != "Name") { values[Index] = PI.GetValue(O, new object[] { }); Index++; } } DT.Rows.Add(values); } } CabinetOutputControllerOutputs.ClearSelection(); CabinetOutputControllerOutputs.Columns.Clear(); CabinetOutputControllerOutputs.AutoGenerateColumns = true; CabinetOutputControllerOutputs.DataSource = DT; CabinetOutputControllerOutputs.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells); CabinetOutputControllerOutputs.Refresh(); } }
/// <summary> /// 根据实体类生成SqlParameter集合,用于大量参数(返回自增后的主键时使用) /// </summary> /// <param name="mouob">实体类</param> /// <returns>SqlParameter[]</returns> public static SqlParameter[] ParmsByModuleAddId(object mouob) { PropertyInfo[] Fields = mouob.GetType().GetProperties(); SqlParameter[] parms = new SqlParameter[Fields.Length + 1]; int i = 0; foreach (PropertyInfo PI in Fields) { parms[i] = new SqlParameter(); parms[i].ParameterName = "@" + PI.Name; if (PI.PropertyType == typeof(System.Int32)) { parms[i].SqlDbType = SqlDbType.Int; } else if (PI.PropertyType == typeof(System.String)) { parms[i].SqlDbType = SqlDbType.VarChar; } else if (PI.PropertyType == typeof(System.DateTime)) { parms[i].SqlDbType = SqlDbType.DateTime; } else if (PI.PropertyType == typeof(System.Double)) { parms[i].SqlDbType = SqlDbType.Float; } else if (PI.PropertyType == typeof(System.Boolean)) { parms[i].SqlDbType = SqlDbType.Bit; } parms[i].Value = PI.GetValue(mouob, null); i++; } //插入后自增ID parms[i] = new SqlParameter(); parms[i].ParameterName = "@InsertId"; parms[i].SqlDbType = SqlDbType.Int; parms[i].Value = 0; parms[i].Direction = ParameterDirection.Output; return(parms); }
public object GetMocks() { Mocker mock = new Mocker(); List <object> list = new List <object>(); var generatedObject = _builder.CreateDynamicClass(PropertyNames, TypesString); Type TP = generatedObject.GetType(); foreach (PropertyInfo PI in TP.GetProperties()) { var businessObjectPropValue = PI.GetValue(generatedObject, null); PI.SetValue(generatedObject, mock.Name.FirstName(), null); //PI.SetValue("FirstName", mock.Name.FirstName()); list.Add(PI.Name); } //var testEmployee = new MockerGeneric<TempEmployee>() // .Condition(o => o.FirstName, m => m.Name.FirstName()) // .Condition(o => o.LastName, m => m.Name.LastName()) // .Condition(o => o.id, m => m.Random.Number(1, 100)); //var user = testEmployee.Mock(1000); return(generatedObject); }
protected override T PerformInsert <T>(T ValueToInsert) //where T:PersistentBase { Type type = ValueToInsert.GetType(); string TableName = type.GetCustomAttribute <PersistentTableName>().TableName; string query = "INSERT INTO [" + TableName + "]("; string values = " OUTPUT INSERTED.ID VALUES("; bool first = true; int i = 1; SqlCommand tmpCommand = new SqlCommand(); foreach (PropertyInfo PI in type.GetProperties()) { if (!PI.PropertyType.IsArray && PI.Name.ToLower() != "id" && !Attribute.IsDefined(PI, typeof(NonPersistent))) { if (!first) { query += ", "; values += ","; } first = false; query += "[" + PI.Name + "]"; values += "@" + i.ToString(); object val = (PI.GetValue(ValueToInsert)); /*if (val is decimal) * tmpCommand.Parameters.AddWithValue("@"+i++.ToString(), ((decimal)val).ToString("#############00.0000000000#####")); * else*/ tmpCommand.Parameters.AddWithValue("@" + i++.ToString(), val ?? DBNull.Value); } } query += ") "; values += ")"; tmpCommand.CommandText = query + values; tmpCommand.Connection = Connection; ValueToInsert.Id = (int)tmpCommand.ExecuteScalar(); return(ValueToInsert); }
private bool compare(Virus a, Virus b) { var virusAprop = typeof(Virus).GetProperties(); foreach (PropertyInfo PI in virusAprop) { //object? is een var die null mag zijn object?valueA = PI.GetValue(a); object?valueB = PI.GetValue(b); if (PI.PropertyType.Name == "double") {// als double afronden valueA = Math.Round((double)PI.GetValue(a), 1); valueB = Math.Round((double)PI.GetValue(b), 1); } if (valueA != valueB) { return(false); } } return(true); }
/// <summary> /// Enumerates the properties of an object (of a type it supports). /// </summary> /// <param name="Object">Object</param> /// <returns>Property enumeration as a script element.</returns> public IElement EnumerateProperties(object Object) { List <IElement> Elements = new List <IElement>(); Type T = Object.GetType(); foreach (PropertyInfo PI in T.GetRuntimeProperties()) { if (PI.GetIndexParameters().Length > 0) { continue; } Elements.Add(new StringValue(PI.Name)); Elements.Add(Expression.Encapsulate(PI.GetValue(Object))); } ObjectMatrix M = new ObjectMatrix(Elements.Count / 2, 2, Elements) { ColumnNames = new string[] { "Name", "Value" } }; return(M); }
protected override T PerformUpdate <T>(T ValueToUpdate)// where T : PersistentBase { if (ValueToUpdate.Id <= 0) { return(PerformInsert <T>(ValueToUpdate)); } Type type = ValueToUpdate.GetType(); string TableName = type.GetCustomAttribute <PersistentTableName>().TableName; string query = "UPDATE [" + TableName + "] set"; bool first = true; int i = 1; MySqlCommand tmpCommand = new MySqlCommand(); foreach (PropertyInfo PI in type.GetProperties()) { if (!PI.PropertyType.IsArray && PI.Name.ToLower() != "id") { if (!first) { query += ", "; } first = false; query += "[" + PI.Name + "] = @" + i.ToString(); tmpCommand.Parameters.AddWithValue("@" + i++.ToString(), PI.GetValue(ValueToUpdate)); } } query += " WHERE [" + TableName + "].Id = @" + i.ToString(); tmpCommand.Parameters.AddWithValue("@" + i++.ToString(), ValueToUpdate.Id); tmpCommand.CommandText = query; //tmpCommand.Connection = SqlConnection //Set sql connection here ValueToUpdate.Id = (int)tmpCommand.ExecuteScalar(); return(ValueToUpdate); }
private void UpdateRepoItemGuids(RepositoryItemBase item, List <GuidMapper> guidMappingList) { foreach (FieldInfo PI in item.GetType().GetFields()) { var token = PI.GetCustomAttribute(typeof(IsSerializedForLocalRepositoryAttribute)); if (token == null) { continue; } // we drill down to ObservableList if (typeof(IObservableList).IsAssignableFrom(PI.FieldType)) { IObservableList obj = (IObservableList)PI.GetValue(item); if (obj == null) { return; } List <object> items = ((IObservableList)obj).ListItems; if ((items != null) && (items.Count > 0) && (items[0].GetType().IsSubclassOf(typeof(RepositoryItemBase)))) { foreach (RepositoryItemBase ri in items.Cast <RepositoryItemBase>()) { GuidMapper mapping = new GuidMapper(); mapping.Original = ri.Guid; ri.Guid = Guid.NewGuid(); mapping.newGuid = ri.Guid; guidMappingList.Add(mapping); UpdateRepoItemGuids(ri, guidMappingList); } } } } }
internal void UpdateObjectFromPayLoad(NewPayLoad PL, Attribute attr) { List <PropertyInfo> list = GetProperties(attr); //TODO: unpack the Payload and update the obj foreach (PropertyInfo PI in list) { object v = PI.GetValue(mObj); if (PI.PropertyType.IsEnum) { string s = PL.GetValueEnum(); object o = Enum.Parse(PI.PropertyType, s); PI.SetValue(mObj, o); } else if (v is IObservableList) { List <NewPayLoad> lst = PL.GetListPayLoad(); foreach (NewPayLoad PL1 in lst) { ObjectReflectionHelper ORH1 = new ObjectReflectionHelper(); ORH1.CreateObjectFromPayLoad(PL1, attr); ((IObservableList)v).Add(ORH1.obj); } } else if (PI.PropertyType.Name == "String") { string s = PL.GetValueString(); PI.SetValue(mObj, s); } else { throw new Exception("Unknown type to handle - " + PI.PropertyType); } } }
public void CheckPropertyChangedTriggered() { // Scan all RIs for each prop marked with [IsSerializedForLocalRepositoryAttribute] try to change and verify prop changed triggered //Arrange // Get all Repository items IEnumerable <Type> list = GetRepoItems(); ErrCounter = 0; //Act foreach (Type type in list) { Console.WriteLine("CheckPropertyChangedTriggered for type: " + type.FullName); if (type.IsAbstract) { continue; } RepositoryItemBase RI = (RepositoryItemBase)Activator.CreateInstance(type); RI.PropertyChanged += RIPropertyChanged; RI.StartDirtyTracking(); // Properties foreach (PropertyInfo PI in RI.GetType().GetProperties()) { var token = PI.GetCustomAttribute(typeof(IsSerializedForLocalRepositoryAttribute)); if (token == null) { continue; } Console.WriteLine("CheckPropertyChangedTriggered for property: " + PI.Name); object newValue = GetNewValue(PI.PropertyType, PI.GetValue(RI)); if (newValue != null) { RI.DirtyStatus = eDirtyStatus.NoChange; prop = null; PI.SetValue(RI, newValue); CheckChanges(RI, PI.Name, newValue); } } // Fields foreach (FieldInfo FI in RI.GetType().GetFields()) { var token = FI.GetCustomAttribute(typeof(IsSerializedForLocalRepositoryAttribute)); if (token == null) { continue; } Console.WriteLine("CheckPropertyChangedTriggered for property: " + FI.Name); object newValue = GetNewValue(FI.FieldType, FI.GetValue(RI)); if (newValue != null) { RI.DirtyStatus = eDirtyStatus.NoChange; prop = null; FI.SetValue(RI, newValue); CheckChanges(RI, FI.Name, newValue); } } } //Assert Assert.AreEqual(0, ErrCounter); }
private void UpdateTypeXml() { string S = ""; if (ScriptTypes.SelectedRows.Count > 0) { string N = ScriptTypes.SelectedRows[0].Cells[0].Value.ToString(); General.TypeList Types = new General.TypeList(AppDomain.CurrentDomain.GetAssemblies().ToList().SelectMany(s => s.GetTypes()).Where(p => (typeof(IEffect).IsAssignableFrom(p) || typeof(IToy).IsAssignableFrom(p)) && !p.IsAbstract)); if (Types.Contains(N)) { Type T = Types[N]; object O = Activator.CreateInstance(T); foreach (PropertyInfo PI in T.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { if (PI.CanWrite) { if (PI.PropertyType == typeof(string) && PI.Name == "Name") { if (typeof(IEffect).IsAssignableFrom(T)) { PI.SetValue(O, "Effect Name", null); } else if (typeof(IToy).IsAssignableFrom(T)) { PI.SetValue(O, "Toy Name", null); } else { PI.SetValue(O, "Name", null); } } else if (PI.PropertyType.IsNumber()) { } else if (PI.PropertyType == typeof(bool)) { PI.SetValue(O, false, null); } else if (PI.PropertyType == typeof(string) && PI.Name.ToLower().Contains("output")) { PI.SetValue(O, "Name of a output", null); } else if (PI.PropertyType == typeof(string) && PI.Name.ToLower().Contains("toy")) { PI.SetValue(O, "Name of a toy", null); } else if (PI.PropertyType == typeof(string)) { string V = (string)PI.GetValue(O, null); if (V.IsNullOrWhiteSpace()) { PI.SetValue(O, "{0} value".Build(PI.Name), null); } } else if (PI.PropertyType == typeof(DateTime)) { PI.SetValue(O, DateTime.MaxValue, null); } } } try { XmlSerializerNamespaces EmptyNamepsaces = new XmlSerializerNamespaces(new[] { System.Xml.XmlQualifiedName.Empty }); var Serializer = new XmlSerializer(T); var Settings = new System.Xml.XmlWriterSettings(); Settings.Indent = true; Settings.OmitXmlDeclaration = true; using (var Stream = new StringWriter()) using (var Writer = System.Xml.XmlWriter.Create(Stream, Settings)) { Serializer.Serialize(Writer, O, EmptyNamepsaces); S = Stream.ToString(); } } catch (Exception E) { S = "XML Serialization failed.\nException:\n{0}".Build(E.Message); } } else { S = "Type not found"; } } TypeXml.Text = S; }
//[Ignore] //[TestMethod] [Timeout(60000)] //public void NewRepositorySerializer_ReadOldXML() //{ // // Using new SR2 to load and write old XML but load old object, save with the style // //Arrange // //GingerCore.Repository.RepositorySerializerInitilizer OldSR = new GingerCore.Repository.RepositorySerializerInitilizer(); // //GingerCore.Repository.RepositorySerializerInitilizer.InitClassTypesDictionary(); // NewRepositorySerializer RS2 = new NewRepositorySerializer(); // string fileName = Common.getGingerUnitTesterDocumentsFolder() + @"Repository\BigFlow1.Ginger.BusinessFlow.xml"; // //Act // string txt = System.IO.File.ReadAllText(fileName); // BusinessFlow BF = (BusinessFlow)NewRepositorySerializer.DeserializeFromText(txt); // //load with new // // BusinessFlow BF = (BusinessFlow)RS2.DeserializeFromFile(fileName); // //Serialize to new style // //string s = RS2.SerializeToString(BF); // // cretae from new style SR2 // BusinessFlow BF2 = (BusinessFlow)RS2.DeserializeFromText(typeof(BusinessFlow), txt, filePath: fileName); // //to test the compare change something in b like below // // BF2.Activities[5].Description = "aaa"; // // BF2.Activities.Remove(BF2.Activities[10]); // //Assert // // System.IO.File.WriteAllText(@"c:\temp\BF1.xml", s); // // Assert.AreEqual(78, BF.Activities.Count); // //Assert.AreEqual(78, BF2.Activities.Count); // CompareRepoItem(BF, BF2); //} private void CompareRepoItem(RepositoryItemBase a, RepositoryItemBase b) { var props = a.GetType().GetProperties(); foreach (PropertyInfo PI in props) { var token = PI.GetCustomAttribute(typeof(IsSerializedForLocalRepositoryAttribute)); if (token != null) { Console.WriteLine("compare: " + a.ToString() + " " + PI.Name); object aProp = PI.GetValue(a); object bProp = b.GetType().GetProperty(PI.Name).GetValue(b); if (aProp == null && bProp == null) { continue; } if (aProp.ToString() != bProp.ToString()) { throw new Exception("Items no match tostring: " + a.ItemName + " attr: " + PI.Name + " a=" + aProp.ToString() + " b=" + bProp.ToString()); } //if (aProp != bProp) //{ // throw new Exception("Items no match: " + a.ItemName + " attr: " + PI.Name + " a=" + aProp.ToString() + " b=" + bProp.ToString()); //} } } var fields = a.GetType().GetFields(); foreach (FieldInfo FI in fields) { var token = FI.GetCustomAttribute(typeof(IsSerializedForLocalRepositoryAttribute)); if (token != null) { Console.WriteLine("compare: " + a.ToString() + " " + FI.Name); object aFiled = FI.GetValue(a); object bField = b.GetType().GetField(FI.Name).GetValue(b); if (aFiled == null && bField == null) { continue; } if (aFiled.ToString() != bField.ToString()) { throw new Exception("Items no match tostring: " + a.ItemName + " attr: " + FI.Name + " a=" + aFiled.ToString() + " b=" + bField.ToString()); } //if (aFiled != bField) //{ // throw new Exception("Items no match: " + a.ItemName + " attr: " + FI.Name + " a=" + aFiled.ToString() + " b=" + bField.ToString()); //} if (aFiled is IObservableList) { if (((IObservableList)aFiled).Count != ((IObservableList)bField).Count) { throw new Exception("Items in list count do not match: " + a.ItemName + " attr: " + FI.Name + " a=" + aFiled.ToString() + " b=" + bField.ToString()); } var aList = ((IObservableList)aFiled).GetEnumerator(); var bList = ((IObservableList)bField).GetEnumerator(); while (aList.MoveNext()) { bList.MoveNext(); RepositoryItemBase o1 = (RepositoryItemBase)aList.Current; RepositoryItemBase o2 = (RepositoryItemBase)bList.Current; CompareRepoItem(o1, o2); } } } } }
private object GetSampleReferenceType(Type RefType) { Type T = RefType; if (T.IsInterface) { DirectOutput.General.TypeList Types = new DirectOutput.General.TypeList(AppDomain.CurrentDomain.GetAssemblies().ToList().SelectMany(s => s.GetTypes()).Where(p => T.IsAssignableFrom(p) && !p.IsAbstract)); if (Types.Count > 0) { T = Types[0]; } else { return(null); } } Object O = Activator.CreateInstance(T); foreach (PropertyInfo PI in O.GetType().GetXMLSerializableProperties()) { if (PI.PropertyType == typeof(string)) { string V = (string)PI.GetValue(O, null); if (V.IsNullOrWhiteSpace()) { if (PI.Name.ToUpper() == "NAME") { PI.SetValue(O, "Name of {0}".Build(O.GetType().Name), null); } else if (PI.Name.ToUpper().EndsWith("NAME")) { PI.SetValue(O, "Name of {0}".Build(PI.Name.Substring(0, PI.Name.Length - 4)), null); } else { PI.SetValue(O, "{0} string".Build(PI.Name), null); } } } else if (PI.PropertyType.IsArray) { object A = PI.GetValue(O, null); if (A == null) { object[] SampleArray = GetSampleArray(PI.PropertyType); PI.SetValue(O, SampleArray, null); } } else if (PI.PropertyType.IsGenericList()) { IList EN = GetSampleGenericList(PI.PropertyType); PI.SetValue(O, EN, null); } else if (typeof(IDictionary).IsAssignableFrom(PI.PropertyType) && PI.PropertyType.IsGenericType) { IDictionary EN = GetSampleGenericDictionary(PI.PropertyType); PI.SetValue(O, EN, null); } else if (PI.PropertyType.IsValueType) { if (PI.PropertyType == typeof(char)) { PI.SetValue(O, GetSampleValueType(PI.PropertyType), null); } } else if (PI.PropertyType == typeof(DateTime)) { PI.SetValue(O, DateTime.Now, null); } else if (PI.PropertyType == typeof(TimeSpan)) { PI.SetValue(O, TimeSpan.Zero, null); } else if (!PI.PropertyType.IsValueType) { PI.SetValue(O, GetSampleReferenceType(PI.PropertyType), null); } else { throw new Exception("Unknow type {0}".Build(PI.PropertyType.Name)); } } return(O); }