private static void ParseProperties(PropertyCollection source, object target) { foreach (var key in target._GetPropertyNames()) { var type = target._GetPropertyType(key); var isGraph = IsGraph(type); if (isGraph) { var writable = target._CanWrite(key); if (writable && source.ContainsKey(key) && source[key].Value is PropertyCollection newSource) { var newTarget = target._SetNew(key); ParseProperties(newSource, newTarget); } } else { if (source.ContainsKey(key)) { var value = source[key].Value; target._Set(key, value); } } } }
public bool getShowContext() { if (!localSettings.ContainsKey("SHOW_CONTEXT")) { localSettings.Add("SHOW_CONTEXT", System.Configuration.ConfigurationManager.AppSettings["SHOW_CONTEXT"]); } return(Boolean.Parse(localSettings["SHOW_CONTEXT"].ToString())); }
/// <summary> /// Sets to object. /// </summary> /// <param name="source">The source.</param> /// <param name="target">The target.</param> /// <param name="field">The field.</param> /// <param name="prefix">The prefix that will help more efficient execution</param> /// <returns></returns> public static Boolean setToObject(this PropertyCollection source, Object target, Enum field, String prefix = "") { if (!source.ContainsKey(field)) { return(false); } String fname = ""; var fieldName = field.ToString(); if (prefix.isNullOrEmpty()) { var prts = imbSciStringExtensions.SplitOnce(fieldName, "_"); fname = prts.LastOrDefault(); prefix = prts.FirstOrDefault(); } if (fname == "" && fieldName.StartsWith(prefix)) { fname = imbSciStringExtensions.removeStartsWith(field.ToString(), prefix); } if (fname.isNullOrEmpty()) { return(false); } target.imbSetPropertySafe(fname, source.get(field)); return(false); }
/// <summary> /// Adds or replaces values of existing with values from data. Overwrite is off if <c>skipExistingKeys</c> is TRUE /// </summary> /// <param name="existing">Collection to modify</param> /// <param name="data">input data</param> /// <param name="skipExistingKeys">on TRUE it will not replace existing values</param> /// <returns>Number of newly added key/value pairs. -1 if <c>data</c> is <c>null</c></returns> /// \ingroup_disabled ace_ext_collections public static Int32 AddRange(this PropertyCollection existing, PropertyCollection data, Boolean skipExistingKeys = false) { Int32 c = 0; if (data == null) { return(-1); } if (existing == data) { return(-1); } foreach (DictionaryEntry input in data) { if (existing.ContainsKey(input.Key)) { if (!skipExistingKeys) { //c++; existing[input.Key] = input.Value; } } else { c++; existing.Add(input.Key, input.Value); } } return(c); }
/// <summary> Добавить команду сохранения изменений DataRow </summary> public DataBulkCommand <T> AddSaveCommands(DataRow row, string command, DataRowVersion version, string outKey = "") { if (row != null && !command.IsEmpty()) { var dataCommand = DataCommand <T> .CreateCommand(command); var commandParams = dataCommand.DeriveParameters(); PropertyCollection prop = null; foreach (DataColumn column in row.Table.Columns) { if (Array.Exists(commandParams, cmd => column.Caption.Equals(cmd, StringComparison.InvariantCultureIgnoreCase))) { prop = column.ExtendedProperties; if (prop.ContainsKey(outKey) && "out".Equals(prop[outKey] + "", StringComparison.InvariantCultureIgnoreCase)) { dataCommand.AddOut(column.DataType, column.Caption); } else { dataCommand.AddIn(row[column, version], column.Caption); } } } Add(dataCommand); } return(this); }
public static T getProperEnum <T>(this PropertyCollection source, T defaultValue, params Enum[] fields) where T : struct, IConvertible { for (int i = 0; i < fields.Length; i++) { if (source.ContainsKey(fields[i])) { Object output = fields[i]; return((T)output); } } return(defaultValue); /* * Object result = source.getProperField(fields); * if (result == null) * { * return source.getFirstOfType<T>(false, defaultValue); * } * * if (result is Enum) * { * return (T)result; * } else * { * return defaultValue; * }*/ }
//[Obsolete("for 2.0")] /// <summary> /// for version 2.0 /// </summary> private void ReadTableInfoVersion2(XmlSchemaComplexType complexType, CremaDataTable dataTable) { string textValue; dataTable.InternalCreationInfo = complexType.ReadAppInfoAsSigunatureDate(CremaSchema.TableInfo, CremaSchemaObsolete.CreatorObsolete, CremaSchema.CreatedDateTime); dataTable.InternalModificationInfo = complexType.ReadAppInfoAsSigunatureDate(CremaSchema.TableInfo, CremaSchema.Modifier, CremaSchema.ModifiedDateTime); textValue = complexType.ReadAppInfoAsString(CremaSchema.TableInfo, CremaSchema.ID); if (textValue != null) { dataTable.InternalTableID = Guid.Parse(textValue); } else { dataTable.InternalTableID = GuidUtility.FromName(dataTable.Name); } dataTable.InternalTags = complexType.ReadAppInfoAsTagInfo(CremaSchema.TableInfo, CremaSchema.Tags); dataTable.InternalComment = complexType.ReadDescription(); var properties = new PropertyCollection(); this.ReadExtendedProperties(complexType, properties); if (properties.ContainsKey(CremaSchemaObsolete.DataLocation) == true) { dataTable.InternalTags = new TagInfo(properties[CremaSchemaObsolete.DataLocation] as string); properties.Remove(CremaSchemaObsolete.DataLocation); } }
/// <summary> /// Gets the custom data property. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">The key.</param> /// <returns></returns> public T GetCustomDataProperty <T>(String key) { if (!customDataProperties.ContainsKey(key)) { lock (customDataEntryLock) { if (!customDataProperties.ContainsKey(key)) { customDataProperties.Add(key, default(T)); } } } Object output = customDataProperties[key]; return((T)output); }
// -----------------------------CONTAINs KEYS /// <summary> /// Determines whether the specified key contains key - by testing ToString() value it direct test returns false /// </summary> /// <param name="source">The source.</param> /// <param name="key">The key.</param> /// <returns> /// <c>true</c> if the specified key contains key; otherwise, <c>false</c>. /// </returns> public static Boolean containsKey(this PropertyCollection source, Enum key) { Boolean output = false; if (source.ContainsKey(key)) { output = true; } else { String str = key.keyToString(); if (source.ContainsKey(str)) { output = true; } } return(output); }
/// <summary> /// Gets value using the specified key or its <c>ToString()</c> form if not found on first try /// </summary> /// <param name="source">The source.</param> /// <param name="key">The key.</param> /// <param name="defaultValue">The default value.</param> /// <returns>Value for the key or default value</returns> /// \ingroup_disabled ace_ext_collections public static Object get(this PropertyCollection source, Object key, Object defaultValue = null) { Object output = null; if (source.ContainsKey(key)) { return(source[key]); } else { String kstr = key.keyToString(); if (source.ContainsKey(kstr)) { return(source[kstr]); } } return(defaultValue); }
/// <summary> /// Builds a <see cref="settingsPropertyEntry"/> from contained data /// </summary> /// <param name="column">The column.</param> /// <param name="skipExisting">if set to <c>true</c> [skip existing].</param> /// <param name="log">The log.</param> /// <returns></returns> public settingsPropertyEntry BuildPCE(DataColumn column, Boolean skipExisting = true, ILogBuilder log = null) { settingsPropertyEntry pce = new settingsPropertyEntry(column); PropertyCollection pc = pce.exportPropertyCollection(); foreach (var pair in definitions.keyValuePairs) { if (skipExisting) { if (pc.ContainsKey(pair.resolvedKey)) { if (!pc[pair.resolvedKey].toStringSafe().isNullOrEmpty()) { if (log != null) { log.log(" Deploy [" + pair.key + "] = false, because destination is not empty (skipExisting=" + skipExisting.ToString() + ")"); } continue; } } } switch (pair.resolvedKey) { default: if (pair.resolvedKey is imbAttributeName attName) { pce.deploy(attName, pair.value); if (log != null) { log.log("Set[" + pair.key + "] = " + pair.value.toStringSafe()); } } else if (pair.resolvedKey is templateFieldDataTable tfdt) { pce.deploy(tfdt, pair.value); if (log != null) { log.log("Set[" + pair.key + "] = " + pair.value.toStringSafe()); } } else { if (log != null) { log.log(column.Table.GetTitle() + "." + column.ColumnName + " <- entry not recognized [" + pair.key + "]"); } } break; } } return(pce); }
public static Object getAndRemove(this PropertyCollection source, String field, String defaultValue = "") { Object output = defaultValue; if (source.ContainsKey(field)) { output = source[field]; source.Remove(field); } return(output); }
public IPropertyMapping GetProperty(string name) { if (string.IsNullOrEmpty(name)) { return(null); } var nl = name.ToLower(); return(mProperties.ContainsKey(nl) ? mProperties[nl] : null); }
/// <summary> /// Finds the first proper value (not empty, not null) in <c>source</c> using fiven <c>fields</c> /// </summary> /// <param name="source">The source.</param> /// <param name="fields">The fields to test for proper value. Follows the given order</param> /// <returns>First proper value found</returns> /// \ingroup_disabled ace_ext_collections_highlight public static Object getProperField(this PropertyCollection source, params Enum[] fields) { //fields = fields.getFlatArray<Enum>(); for (int i = 0; i < fields.Length; i++) { if (source.ContainsKey(fields[i])) { return(source[fields[i]]); } } for (int i = 0; i < fields.Length; i++) { String str = fields[i].keyToString(); if (source.ContainsKey(str)) { return(source[fields[i]]); } } return(""); }
/// <summary> /// Combines <c>getProperString()</c> results and separator string to create output. /// </summary> /// <param name="source">The source.</param> /// <param name="separator">The separator.</param> /// <param name="fields">The fields.</param> /// <returns></returns> /// \ingroup_disabled ace_ext_collections_highlight public static String getStringLine(this PropertyCollection source, String separator = "-", params Enum[] fields) { String outStr = ""; for (int i = 0; i < fields.Length; i++) { if (source.ContainsKey(fields[i])) { outStr = outStr.add(fields[i].toStringSafe(), separator); } } return(outStr); }
public static PropertyCollection GetPropertyCollection(DbDataReader reader) { var props = new PropertyCollection(); // getting properties and cleaning up any underscores while (reader.Read()) { for (int i = 0; i < reader.FieldCount; i++) { if (!props.ContainsKey(reader.GetName(i).Replace("_", ""))) { props.Add(reader.GetName(i).Replace("_", ""), reader.GetDataTypeName(i)); } } } return(props); }
/// <summary> /// for version 2.0 /// </summary> private void ReadColumnInfoVersion2(XmlSchemaAnnotated annotated, CremaDataColumn dataColumn) { dataColumn.InternalCreationInfo = annotated.ReadAppInfoAsSigunatureDate(CremaSchema.ColumnInfo, CremaSchemaObsolete.CreatorObsolete, CremaSchema.CreatedDateTime); dataColumn.InternalModificationInfo = annotated.ReadAppInfoAsSigunatureDate(CremaSchema.ColumnInfo, CremaSchema.Modifier, CremaSchema.ModifiedDateTime); dataColumn.InternalAutoIncrement = annotated.ReadAppInfoAsBoolean(CremaSchema.ColumnInfo, CremaSchema.AutoIncrement); dataColumn.InternalColumnID = annotated.ReadAppInfoAsGuidVersion2(CremaSchema.ColumnInfo, CremaSchema.ID, dataColumn.ColumnName); dataColumn.InternalTags = annotated.ReadAppInfoAsTagInfo(CremaSchema.ColumnInfo, CremaSchema.Tags); var properties = new PropertyCollection(); this.ReadExtendedProperties(annotated, properties); if (properties.ContainsKey(CremaSchemaObsolete.DataLocation) == true) { dataColumn.InternalTags = new TagInfo(properties[CremaSchemaObsolete.DataLocation] as string); properties.Remove(CremaSchemaObsolete.DataLocation); } }
/// <summary> /// for 1.0 /// </summary> private bool ReadTableInfoVersion1(XmlSchemaElement element, CremaDataTable dataTable) { var modifier = element.ReadAppInfoAsString(CremaSchema.TableInfo, CremaSchema.Modifier); if (modifier != null) { string modifiedDateTime = element.ReadAppInfoAsString(CremaSchema.TableInfo, CremaSchema.ModifiedDateTime); if (DateTime.TryParse(modifiedDateTime, out DateTime dateTime) == true) { dataTable.InternalModificationInfo = new SignatureDate(modifier, dateTime); } } var creator = element.ReadAppInfoAsString(CremaSchema.TableInfo, CremaSchema.Creator); if (creator == null) { creator = element.ReadAppInfoAsString(CremaSchema.TableInfo, CremaSchemaObsolete.CreatorObsolete); } if (creator != null) { var createdDateTime = element.ReadAppInfoAsString(CremaSchema.TableInfo, CremaSchema.CreatedDateTime); if (DateTime.TryParse(createdDateTime, out DateTime dateTime) == true) { dataTable.InternalCreationInfo = new SignatureDate(creator, dateTime); } } if (modifier != null || creator != null) { var properties = new PropertyCollection(); this.ReadExtendedProperties(element, properties); if (properties.ContainsKey(CremaSchemaObsolete.DataLocation) == true) { dataTable.InternalTags = new TagInfo(properties[CremaSchemaObsolete.DataLocation] as string); properties.Remove(CremaSchemaObsolete.DataLocation); } foreach (DictionaryEntry item in properties) { dataTable.ExtendedProperties.Add(item.Key, item.Value); } } return(modifier != null || creator != null); }
/// <summary> /// Safe way to add or update /// </summary> /// <param name="existing">The existing.</param> /// <param name="key">The key.</param> /// <param name="data">The data.</param> /// <param name="skipExistingKeys">if set to <c>true</c> [skip existing keys].</param> /// <returns>TRUE if it was added, and FALSE if criteria never met</returns> /// \ingroup_disabled ace_ext_collections public static Boolean add(this PropertyCollection existing, Enum key, Object data, Boolean skipExistingKeys = false) { if (existing.ContainsKey(key)) { if (!skipExistingKeys) { //c++; existing[key] = data; return(true); } } else { existing.Add(key, data); return(true); } return(false); }
/// <summary> /// Gets the field in proper <c>T</c> type /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="fields">The fields.</param> /// <returns>Typed object</returns> public static T getProperObject <T>(this PropertyCollection source, params Enum[] fields) where T : class { fields = fields.getFlatArray <Enum>(); if (!fields.Any()) { return(source.getFirstOfType <T>(false, null, true)); } for (int i = 0; i < fields.Length; i++) { if (source.ContainsKey(fields[i])) { Object obj = source[fields[i]]; return((T)obj); } } return(null); }
internal static bool GetBooleanPropertyValue(this PropertyCollection props, string property) { var result = true; if (props.ContainsKey(property)) { var value = props[property]; try { result = Convert.ToBoolean(value); } catch (FormatException) { // ignore } catch (InvalidCastException) { // ignore } } return(result); }
/// <summary> /// Adds the object to multiple keys /// </summary> /// <param name="existing">The existing.</param> /// <param name="data">The data.</param> /// <param name="skipExistingKeys">if set to <c>true</c> [skip existing keys].</param> /// <param name="keys">The keys to set this </param> /// <returns>Number of fields updated</returns> public static Int32 addObjectToMultikeys(this PropertyCollection existing, Object data, Boolean skipExistingKeys, params Enum[] keys) { List <Enum> keyList = keys.getFlatList <Enum>(); Int32 c = 0; foreach (Enum key in keyList) { if (existing.ContainsKey(key)) { if (!skipExistingKeys) { //c++; existing[key] = data; c++; } } else { existing.Add(key, data); c++; } } return(c); }
/// <summary> /// Determines whether the specified key has property value. A list of standard keys are accessible from <see cref="MaterialKeys"/>. /// </summary> /// <typeparam name="T">Type of the property.</typeparam> /// <param name="key">The key.</param> /// <returns><c>true</c> if the specified key has property; otherwise, <c>false</c>.</returns> public bool HasProperty <T>(PropertyKey <T> key) { return(Properties.ContainsKey(key)); }
private List <Field> PanelFields(int idPanel) { DataTable tbl = fetchAll("SELECT * FROM fields JOIN field_types USING(id_field) WHERE id_panel = ", idPanel); List <Field> res = new List <Field>(); foreach (DataRow row in tbl.Rows) { int typeId = (int)row["id_type"]; int fieldId = (int)row["id_field"]; PropertyCollection properties = new PropertyCollection(); PropertyCollection rules = new PropertyCollection(); PropertyCollection controlOptions = new PropertyCollection(); DataTable propsTab = fetchAll("SELECT name, val, concerns FROM fields_meta WHERE id_field = ", fieldId); foreach (DataRow propRow in propsTab.Rows) { switch ((string)propRow["concerns"]) { case "view": properties.Add(propRow["name"], propRow["val"]); break; case "validation": rules.Add(propRow["name"], propRow["val"]); break; case "controls": controlOptions.Add(propRow["name"], propRow["val"]); break; default: throw new Exception("Cannot handle metadata about " + propRow["concerns"].ToString() + " (yet)."); } } properties.Add("caption", row["caption"] as string); string typeName = row["type_name"] as string; if (!controlOptions.ContainsKey("isFK") && !controlOptions.ContainsKey("isM2NMapping")) { res.Add(new Field(fieldId, (string)row["column_name"], typeId, (string)row["type_name"], idPanel, properties, rules)); continue; // just a standard field } // FK or M2NMapping string myTable = fetchSingle("SELECT table_name FORM panels WHERE id_panel = ", idPanel) as string; string myColumn = row["column_name"] as string; string refTable = controlOptions[CC.FIELD_REF_TABLE] as string; string refColumn = controlOptions[CC.FIELD_REF_COLUMN] as string; string displayColumn = controlOptions[CC.FIELD_DISPLAY_COLUMN] as string; if (controlOptions.ContainsKey("isFK")) // foreign key { FKMySql fk = new FKMySql(myTable, myColumn, refTable, refColumn, displayColumn); res.Add(new FKField(fieldId, myColumn, typeId, typeName, idPanel, fk, properties, rules)); } // M2NMapping string mapTable = controlOptions[CC.FIELD_MAP_TABLE] as string; string mapMyColumn = controlOptions[CC.FIELD_MAP_MY_COLUMN] as string; string mapRefColumn = controlOptions[CC.FIELD_REF_COLUMN] as string; M2NMappingMySql mapping = new M2NMappingMySql(myTable, myColumn, refTable, refColumn, mapTable, displayColumn, mapMyColumn, mapRefColumn); res.Add(new M2NMappingField(fieldId, myColumn, typeId, typeName, idPanel, mapping, properties, rules)); } return(res); }
protected static void OnRowUpdated(object sender, VistaDBRowUpdatedEventArgs e) { try { PropertyCollection props = e.Row.Table.ExtendedProperties; if (props.ContainsKey("props")) { props = (PropertyCollection)props["props"]; } if (e.Status == UpdateStatus.Continue && (e.StatementType == StatementType.Insert || e.StatementType == StatementType.Update)) { esDataRequest request = props["esDataRequest"] as esDataRequest; esEntitySavePacket packet = (esEntitySavePacket)props["esEntityData"]; string source = props["Source"] as string; if (e.StatementType == StatementType.Insert) { if (props.Contains("AutoInc")) { string autoInc = props["AutoInc"] as string; VistaDBCommand cmd = new VistaDBCommand(); cmd.Connection = e.Command.Connection; cmd.Transaction = e.Command.Transaction; cmd.CommandText = "SELECT LastIdentity([" + autoInc + "]) FROM [" + source + "]"; object o = null; o = cmd.ExecuteScalar(); if (o != null) { e.Row[autoInc] = o; e.Command.Parameters["@" + autoInc].Value = o; } } if (props.Contains("EntitySpacesConcurrency")) { string esConcurrencyColumn = props["EntitySpacesConcurrency"] as string; packet.CurrentValues[esConcurrencyColumn] = 1; } } if (props.Contains("Timestamp")) { string column = props["Timestamp"] as string; VistaDBCommand cmd = new VistaDBCommand(); cmd.Connection = e.Command.Connection; cmd.Transaction = e.Command.Transaction; cmd.CommandText = "SELECT LastTimestamp('" + source + "');"; object o = null; o = cmd.ExecuteScalar(); if (o != null) { e.Command.Parameters["@" + column].Value = o; } } //------------------------------------------------------------------------------------------------- // Fetch any defaults, SQLite doesn't support output parameters so we gotta do this the hard way //------------------------------------------------------------------------------------------------- if (props.Contains("Defaults")) { // Build the Where parameter and parameters VistaDBCommand cmd = new VistaDBCommand(); cmd.Connection = e.Command.Connection; cmd.Transaction = e.Command.Transaction; string select = (string)props["Defaults"]; string[] whereParameters = ((string)props["Where"]).Split(','); string comma = String.Empty; string where = String.Empty; int i = 1; foreach (string parameter in whereParameters) { VistaDBParameter p = new VistaDBParameter("@p" + i++.ToString(), e.Row[parameter]); cmd.Parameters.Add(p); where += comma + "[" + parameter + "]=" + p.ParameterName; comma = " AND "; } // Okay, now we can execute the sql and get any values that have defaults that were // null at the time of the insert and/or our timestamp cmd.CommandText = "SELECT " + select + " FROM [" + request.ProviderMetadata.Source + "] WHERE " + where + ";"; VistaDBDataReader rdr = null; try { rdr = cmd.ExecuteReader(CommandBehavior.SingleResult); if (rdr.Read()) { select = select.Replace("[", String.Empty).Replace("]", String.Empty); string[] selectCols = select.Split(','); for (int k = 0; k < selectCols.Length; k++) { packet.CurrentValues[selectCols[k]] = rdr.GetValue(k); } } } finally { // Make sure we close the reader no matter what if (rdr != null) { rdr.Close(); } } } if (e.StatementType == StatementType.Update) { string colName = props["EntitySpacesConcurrency"] as string; object o = e.Row[colName]; VistaDBParameter p = e.Command.Parameters["@" + colName]; object v = null; switch (Type.GetTypeCode(o.GetType())) { case TypeCode.Int16: v = ((System.Int16)o) + 1; break; case TypeCode.Int32: v = ((System.Int32)o) + 1; break; case TypeCode.Int64: v = ((System.Int64)o) + 1; break; case TypeCode.UInt16: v = ((System.UInt16)o) + 1; break; case TypeCode.UInt32: v = ((System.UInt32)o) + 1; break; case TypeCode.UInt64: v = ((System.UInt64)o) + 1; break; } p.Value = v; } } } catch { } }
/// <summary> /// checks if edited fields exist in webDB and their types are adequate, checks constraints on FKs and mapping tables, /// also checks if controls` dataTables` columns exist and everything that has to be inserted in DB is a required field, /// whether attributes don`t colide and every panel has something to display. /// As it goes through the Panel, it fires an ArchitectureError event. /// </summary> /// <param name="proposalPanel"></param> /// <param name="recursive">run itself on panel children</param> /// <returns>true if no errors found, true othervise</returns> public bool checkPanelProposal(IPanel proposalPanel, bool recursive = true) // non-recursive checking after the initial check - after panel modification { string messageBeginning = "In panel " + (proposalPanel.viewAttr.ContainsKey(CC.PANEL_NAME) ? (proposalPanel.viewAttr[CC.PANEL_NAME] + " (" + proposalPanel.tableName + ") ") : ("of type " + proposalPanel.typeName + " for " + proposalPanel.tableName)) + ": "; DataColumnCollection cols = stats.columnTypes(proposalPanel.tableName); if (cols.Count == 0) { Error(this, new ArchitectureErrorEventArgs(messageBeginning + "table not found or has 0 columns", proposalPanel.tableName)); return(false); } List <IFK> FKs = stats.foreignKeys(proposalPanel.tableName); bool good = true; if (proposalPanel.typeName == PanelTypes.Editable.ToString() || proposalPanel.typeName == PanelTypes.NavTable.ToString()) // this is indeed the only panelType containing fields { bool isNavTable = proposalPanel.typeName == PanelTypes.NavTable.ToString(); foreach (IField field in proposalPanel.fields) { if (field.typeName == FieldTypes.Holder.ToString()) { continue; } if (!cols.Contains(field.column)) { Error(this, new ArchitectureErrorEventArgs(messageBeginning + "the column " + field.column + "managed by the field does not exist in table", proposalPanel, field)); good = false; } else { if (!(field is IFKField) && !(field is IM2NMapping) && !isNavTable) // NavTable won`t be edited in the panel { PropertyCollection r = field.rules; if (cols[field.column].AllowDBNull == false && !r.ContainsKey(CC.RULES_REQUIRED)) { Error(this, new ArchitectureErrorEventArgs(messageBeginning + "the column " + field.column + " cannot be set to null, but the coresponding field is not required", proposalPanel, field)); good = false; } if ((r.ContainsKey(CC.RULUES_DECIMAL) || r.ContainsKey(CC.RULES_ORDINAL)) && !(typeof(long).IsAssignableFrom(cols[field.column].DataType))) { Error(this, new ArchitectureErrorEventArgs(messageBeginning + "the column " + field.column + " is of type " + cols[field.column].DataType.ToString() + ", thus cannot be edited as a decimalnumber", proposalPanel, field)); good = false; } if ((r.ContainsKey(CC.RULES_DATE) || r.ContainsKey(CC.RULES_DATETIME)) && !(cols[field.column].DataType == typeof(DateTime))) { Error(this, new ArchitectureErrorEventArgs(messageBeginning + "the column " + field.column + " is not a date / datetime, thus cannot be edited as a date", proposalPanel, field)); good = false; } } else if (field is IM2NMappingField) { // just cannot occur in a NavTable, but just in case... if (isNavTable) { throw new Exception("Cannot display a M2NMapping in NavTable"); } IM2NMapping thisMapping = ((IM2NMappingField)field).mapping; if (!mappings.Contains(thisMapping)) { Error(this, new ArchitectureErrorEventArgs(messageBeginning + "the schema " + "does not define an usual M2NMapping batween tables " + thisMapping.myTable + " and " + thisMapping.refTable + " using " + thisMapping.mapTable + " as a map table", proposalPanel, field)); good = false; } } else if (field is IFKField) { IFK fieldFK = ((IFKField)field).fk; if (!FKs.Contains(fieldFK)) { Error(this, new ArchitectureErrorEventArgs(messageBeginning + "the column " + field.column + " is not a foreign key representable by the FK field", proposalPanel, field)); good = false; } } } } } // controls... PanelTypes PTEnum = (PanelTypes)Enum.Parse(typeof(PanelTypes), proposalPanel.typeName); if (PTEnum == PanelTypes.NavTable || PTEnum == PanelTypes.NavTree || PTEnum == PanelTypes.MenuDrop) { if (proposalPanel.controlAttr.ContainsKey(CC.NAV_THROUGH_PANELS)) { if (proposalPanel.tableName != null) { Error(this, new ArchitectureErrorEventArgs(messageBeginning + "Panel that navigates through panels " + "cannot have tableName set", proposalPanel.tableName)); good = false; } } else if (proposalPanel.controlAttr.ContainsKey(CC.NAV_THROUGH_RECORDS)) { if (!proposalPanel.controlAttr.ContainsKey(CC.NAV_PANEL_ID)) { Error(this, new ArchitectureErrorEventArgs(messageBeginning + "Navigation panel " + "that does not navigate through panels must have target panel id set", proposalPanel, proposalPanel.controls[0])); good = false; } } } // TODO & TODO & TODO (CONTROLS & OTHER PROPERTIES) // OR allow the admin-user take valid steps only (?) if (recursive) { foreach (IPanel child in proposalPanel.children) { good = good && checkPanelProposal(child, true); } } return(good); }
/// <summary> /// propose the editable panel for a table, if table will probably not be self-editable /// (such as an M2N mapping), return null /// </summary> /// <param name="tableName"></param> /// <returns>IPanel (or null)</returns> public IPanel proposeForTable(string tableName) { // dont care for indexes for now DataColumnCollection cols = stats.columnTypes(tableName); List <IFK> FKs = stats.foreignKeys(tableName); List <string> PKCols = stats.primaryKeyCols(tableName); while (PKCols.Count == 0) { Dictionary <string, object> options = new Dictionary <string, object>(); options.Add("Try again", 1); options.Add("Ommit table", 2); ArchitectQuestionEventArgs args = new ArchitectQuestionEventArgs( "The table " + tableName + " does not have a primary key defined and therefore " + "cannot be used in the administration. Is this intentional or will you add the primary key? (OMMIT TABLE)", options); Question(this, args); //int answer = (int)questionAnswer; int answer = 2; if (answer == 1) { PKCols = stats.primaryKeyCols(tableName); } else { return(null); } } if (cols.Count == 2 && FKs.Count == 2) { return(null); // seems like mapping table } // FK ~> mapping ? List <IField> fields = new List <IField>(); foreach (IM2NMapping mapping in mappings) { if (mapping.myTable == tableName && !usedMappings.Exists(m => mapping == m)) // && (stats.TableCreation(mapping.myTable) > stats.TableCreation(mapping.refTable) // the later-created table would get to edit the mapping // but I`d better ask the user { Dictionary <string, object> options = new Dictionary <string, object>(); options.Add("Include in this panel", 1); options.Add("Include in this panel only", 2); options.Add("Do not include", 3); ArchitectQuestionEventArgs args = new ArchitectQuestionEventArgs( "While proposing administration panel for the table " + mapping.myTable + ", the system found out that the table " + mapping.mapTable + " is likely to be a M to N mapping between this table and " + mapping.refTable + ". Do you want to include an interface to manage this mapping in this panel? (INCLUDE IN THIS PANEL ONLY)", options); Question(this, args); // ask questions! //int answer = (int)questionAnswer; int answer = 2; if (answer == 1 || answer == 2) { // no potentional field from cols is removed by this, though List <string> displayColOrder = DisplayColOrder(mapping.refTable); mapping.displayColumn = displayColOrder[0]; fields.Add(new M2NMappingField(0, mapping.myColumn, fieldTypeIdMap[FieldTypes.M2NMapping], FieldTypes.M2NMapping.ToString(), 0, mapping)); } if (answer == 2) { usedMappings.Add(mapping); } } } // standard FKs foreach (IFK actFK in FKs) { List <string> displayColOrder = DisplayColOrder(actFK.refTable); actFK.displayColumn = displayColOrder[0]; fields.Add(new FKField(0, actFK.myColumn, fieldTypeIdMap[FieldTypes.FK], FieldTypes.FK.ToString(), 0, actFK)); cols.Remove(actFK.myColumn); // will be edited as a foreign key } // editable fields in the order as defined in table; don`t edit AI foreach (DataColumn col in cols) { PropertyCollection validation = new PropertyCollection(); if (!col.ExtendedProperties.ContainsKey(CC.COLUMN_EDITABLE)) { continue; } if (!col.AllowDBNull) { validation.Add(CC.RULES_REQUIRED, true); } FieldTypes fieldType; // default => standard textBox if (col.DataType == typeof(string)) { if (col.MaxLength <= 255) { fieldType = FieldTypes.Varchar; } else { fieldType = FieldTypes.Text; } } else if (col.DataType == typeof(int) || col.DataType == typeof(long) || col.DataType == typeof(short)) { fieldType = FieldTypes.Ordinal; validation.Add(fieldType.ToString(), true); } else if (col.DataType == typeof(float) || col.DataType == typeof(double)) { fieldType = FieldTypes.Decimal; validation.Add(fieldType.ToString(), true); } else if (col.DataType == typeof(bool)) { fieldType = FieldTypes.Bool; } else if (col.DataType == typeof(DateTime)) { if (col.ExtendedProperties.ContainsKey(CC.FIELD_DATE_ONLY)) { fieldType = FieldTypes.Date; } // should DATETIME, BUT DATETIME is usually used for date only...or is it? else { fieldType = FieldTypes.Date; } validation.Add(fieldType.ToString(), true); } else if (col.DataType == typeof(Enum)) { // cannot happen, since column properties are taken from Stats if (!col.ExtendedProperties.ContainsKey(CC.COLUMN_ENUM_VALUES)) { throw new Exception("Missing enum options for field " + col.ColumnName); } fieldType = FieldTypes.Enum; } else { throw new Exception("Unrecognised column type " + col.DataType.ToString()); } fields.Add(new Field(0, col.ColumnName, fieldTypeIdMap[fieldType], fieldType.ToString(), 0, col.ExtendedProperties, validation)); // don`t add any properties, just copy from Stat } fields.OrderBy(x => ((int)(x.attr[CC.FIELD_POSITION]))); // setup controls as properies PropertyCollection controlProps = new PropertyCollection(); PropertyCollection viewProps = new PropertyCollection(); viewProps.Add(CC.PANEL_NAME, tableName + " Editation"); List <Control> controls = new List <Control>(); string actionName = UserAction.View.ToString(); controlProps.Add(actionName, actionName); controlProps.Add(actionName + CC.CONTROL_ACCESS_LEVEL_REQUIRED_SUFFIX, 1); actionName = UserAction.Insert.ToString(); controlProps.Add(actionName, actionName); controlProps.Add(actionName + CC.CONTROL_ACCESS_LEVEL_REQUIRED_SUFFIX, 3); actionName = UserAction.Update.ToString(); controlProps.Add(actionName, actionName); controlProps.Add(actionName + CC.CONTROL_ACCESS_LEVEL_REQUIRED_SUFFIX, 5); actionName = UserAction.Delete.ToString(); controlProps.Add(actionName, actionName); controlProps.Add(actionName + CC.CONTROL_ACCESS_LEVEL_REQUIRED_SUFFIX, 5); foreach (string actName in Enum.GetNames(typeof(UserAction))) { if (controlProps.ContainsKey(actName)) { controls.Add(new Control(actName, (UserAction)Enum.Parse(typeof(UserAction), actName))); } } List <IControl> controlsAsIControl = new List <IControl>(controls); //set additional properties // the order of fields in edit form (if defined), if doesn`t cover all editable columns, display the remaining // at the begining, non-editable columns are skipped //viewProps[CC.PANEL_DISPLAY_COLUMN_ORDER] = String.Join(",", DisplayColOrder(tableName)); Panel res = new Panel(tableName, 0, panelTypeIdMp[PanelTypes.Editable], PanelTypes.Editable.ToString(), new List <IPanel>(), fields, controlsAsIControl, PKCols, null, viewProps, controlProps); return(res); }
/// <summary> /// Combines two PropertyCollections according <c>policy</c> specified /// </summary> /// <param name="existing">Collection that will be changed</param> /// <param name="data">New data to append</param> /// <param name="policy">How to manage key duplicates</param> /// \ingroup_disabled ace_ext_collections_highlight public static void AppendData(this PropertyCollection existing, PropertyCollection data, existingDataMode policy, Boolean showException = true) { PropertyCollection temp = new PropertyCollection(); if ((data == null) && showException) { throw new ArgumentNullException("data", "AppendData failed because data is null"); return; } if (data == null) { return; } switch (policy) { case existingDataMode.clearExisting: existing.Clear(); existing.AddRange(data); break; case existingDataMode.filterAndLeaveExisting: foreach (DictionaryEntry input in data) { if (existing.ContainsKey(input.Key)) { temp.Add(input.Key, existing[input.Key]); } } existing.Clear(); existing.AddRange(temp); break; case existingDataMode.filterNewOverwriteExisting: foreach (DictionaryEntry input in data) { if (existing.ContainsKey(input.Key)) { existing[input.Key] = input.Value; } } break; case existingDataMode.leaveExisting: existing.AddRange(data, true); break; case existingDataMode.overwriteExistingIfEmptyOrNull: foreach (DictionaryEntry input in data) { if (existing.ContainsKey(input.Key)) { if (imbSciStringExtensions.isNullOrEmptyString(existing[input.Key].toStringSafe(""))) { existing[input.Key] = input.Value; } } else { existing.Add(input.Key, input.Value); } } break; case existingDataMode.overwriteExisting: foreach (DictionaryEntry input in data) { if (existing.ContainsKey(input.Key)) { existing[input.Key] = input.Value; } else { existing.Add(input.Key, input.Value); } } break; case existingDataMode.sumWithExisting: foreach (DictionaryEntry input in data) { if (existing.ContainsKey(input.Key)) { Object result = existing[input.Key].sumValues(input.Value); } else { existing.Add(input.Key, input.Value); } } break; default: throw new NotImplementedException(imbStringFormats.toStringSafe(policy) + " called but not implemented"); break; } }
// -------------------------- ADD and APPEND #pragma warning disable CS1574 // XML comment has cref attribute 'existingDataMode' that could not be resolved /// <summary> /// Appends the specified key and value accordint the specified <see cref="aceCommonTypes.enums.existingDataMode"/>. Returns TRUE if <c>newValueCandidate</c> was written as result of the <c>policy</c> specified. /// </summary> /// <param name="data">The data.</param> /// <param name="key">The key.</param> /// <param name="newValueCandidate">The new value candidate - it will be or not written under specified <c>key</c> depending on <c>policy</c> and current <c>data</c> </param> /// <param name="policy">The policy on handling existing entry for the <c>key</c> specified</param> /// <returns>FALSE if <c>newValueCandidate</c> was not written into <c>data</c> collection</returns> public static Boolean Append(this PropertyCollection data, Object key, Object newValueCandidate, existingDataMode policy) #pragma warning restore CS1574 // XML comment has cref attribute 'existingDataMode' that could not be resolved { if (newValueCandidate == null) { return(false); } switch (policy) { case existingDataMode.clearExisting: data.Clear(); data.Add(key, data); break; case existingDataMode.filterAndLeaveExisting: if (data.ContainsKey(key)) { //data[key] = newValueCandidate; return(false); } else { if (key is Enum) { data.add((Enum)key, newValueCandidate, false); } else { data.Add(key.toStringSafe(), newValueCandidate); } } break; case existingDataMode.filterNewOverwriteExisting: if (data.ContainsKey(key)) { data[key] = newValueCandidate; } return(false); break; case existingDataMode.leaveExisting: return(false); break; case existingDataMode.overwriteExistingIfEmptyOrNull: if (data.ContainsKey(key)) { if (imbSciStringExtensions.isNullOrEmptyString(data[key])) { data[key] = newValueCandidate; } else { return(false); } } else { data.Add(key, newValueCandidate); } break; case existingDataMode.overwriteExisting: if (data.ContainsKey(key)) { data[key] = newValueCandidate; } else { data.Add(key, newValueCandidate); } break; case existingDataMode.sumWithExisting: if (data.ContainsKey(key)) { Object result = data[key].sumValues(newValueCandidate); } else { data.Add(key, newValueCandidate); } break; } return(true); }