public static T RetrieveDataObjectByParameter(string connectionName, string query, out string errMsg, bool isUnique = false, params object[] args) { T result = default(T); errMsg = string.Empty; try { using (Database = DatabaseManager.GetDatabaseByName(connectionName, true)) { var intResult = Database.Fetch <T>(query, args); if (intResult != null && intResult.Count == 1) { result = intResult.FirstOrDefault(); } else if (intResult.Count > 1 && isUnique == false) { throw new Exception("Result not unique"); } else if (intResult.Count > 1 && isUnique == true) { result = intResult.FirstOrDefault(); } else if (intResult.Count < 0) { throw new Exception("Invalid Result"); } } } catch (Exception e) { errMsg = e.Message; } return(result); }
public static bool Save(IDatabaseObject databaseObject) { if (string.IsNullOrWhiteSpace(m_databasePath)) { Log.Error("Select or create database must be called before saving is possible"); return(false); } var filename = Path.Combine(m_databasePath, string.Format("{0}.bos", databaseObject.TableName.ToString())); var row = databaseObject.RowInfo.OrderBy(r => r.Key).Select(r => r.Value); var colums = new List <string>(); foreach (var columnInfo in row) { colums.Add(string.Format("{0}={1}", columnInfo.ColumnName, columnInfo.ColumnValue.ToString())); } var rowstring = string.Join(";", colums); using (StreamWriter sw = File.AppendText(filename)) { sw.WriteLine(rowstring); } return(true); }
public static IDatabaseObject GetDatabaseByName(string connectionName, bool isSpecific = true) { IDatabaseObject result = null; ObjectCache cache = MemoryCache.Default; if (cache != null) { result = cache[_defaultConnectionKey] as IDatabaseObject; if (result == null) { result = new DatabaseObject(connectionName); result.ConnectionStringName = connectionName; cache[_defaultConnectionKey] = result; } else { result.ConnectionStringName = _defaultConnectionKey; } } else { throw new Exception("Unable to initialize memory cache"); } return(result); }
private void AssignObjectName(IDatabaseObject dbObject) { if (!string.IsNullOrEmpty(dbObject.Name)) { return; } var nameProperty = _cfg.GetConfigValue($"{dbObject.Type}.Name"); if (string.IsNullOrEmpty(nameProperty)) { return; } nameProperty = nameProperty.Replace("{", string.Empty).Replace("}", string.Empty).ToLowerInvariant(); var namePropertyParts = nameProperty.Split(".".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); var namePropertyTableName = namePropertyParts.Length > 0 ? namePropertyParts[0] : string.Empty; var namePropertyColumnName = namePropertyParts.Length > 1 ? namePropertyParts[1] : string.Empty; if (string.IsNullOrEmpty(namePropertyTableName) || string.IsNullOrEmpty(namePropertyColumnName)) { return; } var properties = dbObject.Properties; while (null != properties) { if (properties.ContainsKey(namePropertyTableName) && properties[namePropertyTableName].ContainsKey(namePropertyColumnName)) { dbObject.Name = properties[namePropertyTableName][namePropertyColumnName].ToString(); break; } properties = dbObject.ParentObject?.Properties; } }
public static IDatabaseObject GetDatabaseByKey(string key) { IDatabaseObject result = null; ObjectCache cache = MemoryCache.Default; if (cache != null) { result = cache[key] as IDatabaseObject; if (result == null) { result = new DatabaseObject(_defaultKey); result.ConnectionKey = _defaultKey; cache[_defaultConnectionKey] = result; } else { result.ConnectionKey = key; } } else { throw new Exception("Unable to initialize memory cache"); } return(result); }
private void AssignEditorItem(Guid id) { if (id != Guid.Empty) { IDatabaseObject obj = null; if (rdoPlayerVariables.Checked) { obj = PlayerVariableBase.Get(id); } else if (rdoGlobalVariables.Checked) { obj = ServerVariableBase.Get(id); } if (obj != null) { mEditorItem = obj; if (!mChanged.Contains(obj)) { mChanged.Add(obj); obj.MakeBackup(); } } } UpdateEditor(); }
public static void AddData <T>(this IDatabaseObject <T> source) where T : class { string name = typeof(T).Name; string sql = "[" + name + "]"; ADODB.Recordset rs = DataSeverConnection.Instance.Recordset(sql, ADODB.CursorTypeEnum.adOpenDynamic, ADODB.LockTypeEnum.adLockOptimistic); rs.AddNew(); PropertyInfo[] properties = typeof(T).GetProperties(); for (int i = 0; i < rs.Fields.Count; i++) { PropertyInfo property = null; properties.Each(f => { if (f.Name == rs.Fields[i].Name) { property = f; return; } }); rs.Fields[i].Value = property.GetValue(source); } rs.Update(); rs.Close(); }
protected virtual void AddObject(IDatabaseObject obj) { if (CreatedObj) { NeedsInserted.Add(obj); } }
public IEnumerable <IScriptBlock> AlterTo(IDatabaseObject obj, Options options) { return(new List <IScriptBlock>() { this.CreateProcedure() }); }
void _db_OnSchemaProcess(IDatabase database, Schema schema, IDatabaseObject obj) { dispatcherUI.BeginInvoke(new Action(() => { statusBar.Text = schema.Name + "." + obj.Name + " Oluşturuldu"; })); }
void Stickers_BeforeWriting(IDatabaseObject item, IDBObjectWritingOptions writingOptions, ref bool cancel) { if (IsModified) { Description = string.Format("{0} - {2}; кол-во - {1}", Nomenclature.Description, Quantity, ExpiryDate.ToString(DATE_FORMAT)); } }
public static IList <T> RetrieveAllWithPaging(string connectionName, string query, string sort, Direction direction, int page, int pageSize, out int itemsCount, out string errMsg, params object[] args) { IList <T> result = null; errMsg = string.Empty; itemsCount = 0; try { using (Database = DatabaseManager.GetDatabaseByName(connectionName, true)) { pageSize = pageSize <= 0 ? 10 : pageSize; var subResult = Database.Page <T>(page, pageSize, query, args); itemsCount = (int)subResult.TotalItems; result = subResult.Items; } if (direction == Direction.Default) { if (string.IsNullOrWhiteSpace(sort)) { result.OrderBy(x => x.ID); } else { result.OrderBy(x => x.GetType().GetProperties().Where(p => p.Name.ToLower() == sort.ToLower())); } } else { if (direction == Direction.Descending) { if (string.IsNullOrWhiteSpace(sort)) { result.OrderByDescending(x => x.ID); } else { result.OrderByDescending(x => x.GetType().GetProperties().Where(p => p.Name.ToLower() == sort.ToLower())); } } else { if (string.IsNullOrWhiteSpace(sort)) { result.OrderByDescending(x => x.ID); } else { result.OrderByDescending(x => x.GetType().GetProperties().Where(p => p.Name.ToLower() == sort.ToLower())); } } } } catch (Exception e) { errMsg = e.Message; } return(result); }
public static ICollection <T> GetAll <T>(this IDatabaseObject <T> source) where T : class, new() { string sql = "SELECT * FROM [" + typeof(T).Name + "]"; ICollection <T> retVal = GetDataCollection <T>(sql, "", DataSeverConnection.Instance); //DataSeverConnection.Instance.Connection.Close(); return(retVal); }
public void UpdateDbObject(IDatabaseObject dbObject) { var conn = GetOpenConnection(); if (dbObject.Exists(conn)) { dbObject.Drop(conn); } dbObject.Create(conn); dbObject.SetConstraints(conn); }
public AddNewObject(Form previousForm, IDatabaseObject databaseObject) { this.databaseObject = databaseObject; this.previousForm = previousForm; InitializeComponent(); foreach (KeyValuePair <string, Type> attribute in databaseObject.ObjectData["contentsData"] as Dictionary <string, Type> ) { AddAttributeTextBox(attributePanel, attribute, -1); } }
public static IDatabaseObject Create(Type _type) { IDatabaseObject database = (IDatabaseObject)_type.Assembly.CreateInstance(_type.FullName); if (ListLastUID.ContainsKey(_type) == false) { ListLastUID[_type] = 0; } database.ID = ++ListLastUID[_type]; return(database); }
public BoekEdit(Form previousForm, IDatabaseObject databaseObject) { this.previousForm = previousForm; this.databaseObject = databaseObject; InitializeComponent(); this.attributePanel.AutoScroll = true; this.idLabel.Text = "Id: " + databaseObject.Id; foreach (KeyValuePair <string, Type> attribute in databaseObject.RequiredData) { AddAttributeTextBox(attributePanel, attribute, databaseObject.ObjectData[attribute.Key]); } }
public bool Equals(IDatabaseObject obj, Options options) { if (obj is ColumnObject otherCol) { if (this.TableSchema != otherCol.TableSchema) { return(false); } if (this.ColumnName != otherCol.ColumnName) { return(false); } if (this.IsNullable != otherCol.IsNullable) { return(false); } if (this.DataType != otherCol.DataType) { return(false); } if (this.MaxCharacters != otherCol.MaxCharacters) { return(false); } if (this.DatetimePrecision != otherCol.DatetimePrecision) { return(false); } if (this.NumericPrecision != otherCol.NumericPrecision) { return(false); } if (this.NumericScale != otherCol.NumericScale) { return(false); } return(true); } return(false); }
public static string GetNullOrIDStringFromObject(IDatabaseObject obj) { if (obj is null) { return("null"); } else { if (obj.ID < 0) { return("null"); } return(obj.ID.ToString()); } }
private void AddObjectToListView(ListView listView, IDatabaseObject dbObject) { listView.BeginUpdate(); listView.Items.Clear(); foreach (var row in dbObject.ToArrayList()) { var item = new ListViewItem { Text = row[0] }; item.SubItems.Add(row[1]); listView.Items.Add(item); } listView.EndUpdate(); }
public IDatabaseObject CreateObject(ObjectTypeEnum typeEnum, string Name, Schema schemaOwner) { var item = _objectTypes.FirstOrDefault(p => p.Key == typeEnum); if (item.Value != null) { IDatabaseObject dbObject = GetInstance(item.Value); dbObject.Name = Name; dbObject.Owner = schemaOwner; dbObject.BuildObject(); return(dbObject); } return(null); }
private void LoadObject(IDatabaseObject dbObject) { if (null == dbObject) { return; } var objectType = dbObject.Type; var dataDictionaryTablesString = _cfg.GetMandatoryConfigValue($"{objectType}.DataDictionaryTables"); var dataDictionaryTables = dataDictionaryTablesString.Split(",;".ToCharArray(),StringSplitOptions.RemoveEmptyEntries); foreach (var dataDictionaryTable in dataDictionaryTables) { if (dbObject.Properties.ContainsKey(dataDictionaryTable)) { continue; } var sqlCmd = _cfg.GetConfigValue($"{objectType}.{dataDictionaryTable}.SQL"); sqlCmd = ApplyContentToCriteria(dbObject, sqlCmd); var propertiesDictionary = new Dictionary<string, object>(); using (var cmd = new OracleCommand()) { cmd.Connection = GetDbConnection(); cmd.CommandType = CommandType.Text; cmd.CommandText = sqlCmd; var reader = cmd.ExecuteReader(); if (reader.Read()) { for (var fieldIndex = 0; fieldIndex < reader.FieldCount; fieldIndex++) { propertiesDictionary.Add(reader.GetName(fieldIndex).ToLowerInvariant(), reader.GetValue(fieldIndex)); } } } dbObject.Properties.Add(dataDictionaryTable.ToLowerInvariant(), propertiesDictionary); } AssignObjectName(dbObject); // ermitteln der child objects LoadChildObjects(dbObject); }
public static ICollection <T> Where <T>(this IDatabaseObject <T> source, string sqlstatement) where T : class, new() { string tblName = typeof(T).Name; int idx = tblName.IndexOf("`"); if (idx > 0) { tblName = tblName.Substring(0, idx); } string sql = "SELECT * FROM [" + tblName + "]"; ICollection <T> retVal = GetDataCollection <T>(sql, sqlstatement, DataSeverConnection.Instance); //DataSeverConnection.Instance.Connection.Close(); return(retVal); }
public bool Equals(IDatabaseObject obj, Options options) { // If the object isn't a table object, it won't be equal if (obj is TableObject == false) { return(false); } var tblObj = obj as TableObject; // Check all the columns are the same if (!ColumnsEqual(this.Columns, tblObj.Columns, options)) { return(false); } return(true);; }
public static IList <T> RetrieveAllByParameters(string connectionName, string query, out string errMsg, params object[] args) { IList <T> result = null; errMsg = string.Empty; try { using (Database = DatabaseManager.GetDatabaseByName(connectionName, true)) { result = Database.Fetch <T>(query, args); } } catch (Exception e) { errMsg = e.Message; } return(result); }
/// <summary> /// Tests a query on an in memory sql lite /// </summary> /// <param name="setup">A list of queries to run prior to running a find query</param> /// <param name="query"></param> /// <param name="expected"></param> public void TestFindQuery(IEnumerable<IDatabaseObject> setup, IDatabaseObject query, JArray expected) { IDriver driver = new SqLiteDriver() { Settings = new DriverSettings() { Memory = true } }; driver.Connect(); foreach (var item in setup) { driver.Query(item); } List<IDatabaseObject> results = driver.Query(query); Assert.AreEqual(expected.ToString(Formatting.None), ((CollectionValue)results.First()).ToJArray().ToString(Formatting.None)); driver.Close(); }
private void FindAndPaintNode(IDatabaseObject dbObject) { if (dbObject.GetType() == typeof(Table)) { foreach (var item in ((Table)dbObject).Columns) { FindAndPaintNode(item); } } else { var treeNodes = treeView1.Nodes.Find(dbObject.Name, true); if (treeNodes.Count() > 0) { var treeNode = treeNodes[0]; PaintNode(treeNode); } } }
private void lstVariables_AfterSelect(object sender, TreeViewEventArgs e) { if (mChangingName) { return; } if (lstVariables.SelectedNode == null || lstVariables.SelectedNode.Tag == null) { mEditorItem = null; UpdateEditor(); return; } var id = (Guid)lstVariables.SelectedNode.Tag; if (id != Guid.Empty) { IDatabaseObject obj = null; if (rdoPlayerVariables.Checked) { obj = PlayerVariableBase.Get(id); } else if (rdoGlobalVariables.Checked) { obj = ServerVariableBase.Get(id); } if (obj != null) { mEditorItem = obj; if (!mChanged.Contains(obj)) { mChanged.Add(obj); obj.MakeBackup(); } } } UpdateEditor(); }
public bool Equals(IDatabaseObject obj, Options options) { if (obj is FunctionObject == false) { return(false); } var otherFunction = obj as FunctionObject; if (this.FullyQualifiedName != otherFunction.FullyQualifiedName) { return(false); } if (!this.FunctionDefinition.Equals(otherFunction.FunctionDefinition)) { return(false); } return(true); }
public NavigatieScherm(Form previousForm, IDatabaseObject databaseObject) { this.previousForm = previousForm; this.databaseObject = databaseObject; InitializeComponent(); this.attributePanel.AutoScroll = true; this.idLabel.Text = "Id: " + databaseObject.Id; this.primaryObjectName.Text = databaseObject.GetType().Name; foreach (KeyValuePair <string, Type> attribute in databaseObject.RequiredData) { AddAttributeTextBox(attributePanel, attribute, databaseObject.ObjectData[attribute.Key]); } secondaryObjectName.Text = databaseObject.ObjectData["contentsNaam"].ToString(); secondaryObjectSelection.DisplayMember = "Naam"; secondaryObjectSelection.DataSource = this.databaseObject.ObjectData["contents"]; }
protected override void GameObjectUpdatedDelegate(GameObjectType type) { if (type == GameObjectType.PlayerVariable) { InitEditor(); if (mEditorItem != null && !PlayerVariableBase.Lookup.Values.Contains(mEditorItem)) { mEditorItem = null; UpdateEditor(); } } else if (type == GameObjectType.ServerVariable) { InitEditor(); if (mEditorItem != null && !ServerVariableBase.Lookup.Values.Contains(mEditorItem)) { mEditorItem = null; UpdateEditor(); } } }
public bool Equals(IDatabaseObject obj, Options options) { if (obj is ProcedureObject == false) { return(false); } var otherProcedure = obj as ProcedureObject; if (this.FullyQualifiedName != otherProcedure.FullyQualifiedName) { return(false); } if (!this.ProcedureDefinition.Equals(otherProcedure.ProcedureDefinition)) { return(false); } return(true); }
public static IDatabaseObject[] LoadAll(Type _type) { List <IDatabaseObject> databaseObjects = new List <IDatabaseObject>(); FileInfo[] files = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "/Database/" + _type.Name).GetFiles(); for (var i = 0; i < files.Length; ++i) { try { IDatabaseObject databaseObject = Load(_type, uint.Parse(files[i].Name.Substring(0, files[i].Name.IndexOf('.')))); if (databaseObject != null) { databaseObjects.Add(databaseObject); } } catch (Exception ex) { ConsoleSystem.LogError($"[Database.Manager]: Exception from load {_type.Name} file {files[i].Name}: " + ex.Message); } } return(databaseObjects.ToArray()); }
private void LoadChildObjects(IDatabaseObject dbObject) { if (null == dbObject) { return; } var objectType = dbObject.Type; var childObjectsString = _cfg.GetConfigValue($"{objectType}.ChildObjectTypes"); if (string.IsNullOrEmpty(childObjectsString)) { return; } var childObjectTypes = childObjectsString.Split(",;".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); foreach (var childObjectType in childObjectTypes) { var dataDictionaryTablesString = _cfg.GetMandatoryConfigValue($"{childObjectType}.DataDictionaryTables"); var dataDictionaryTables = dataDictionaryTablesString.Split(",;".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); var primaryDataDictionaryTable = dataDictionaryTables.First(); var sqlCmd = _cfg.GetConfigValue($"{childObjectType}.{primaryDataDictionaryTable}.SQL"); sqlCmd = ApplyContentToCriteria(dbObject, sqlCmd); using (var cmd = new OracleCommand()) { cmd.Connection = GetDbConnection(); cmd.CommandType = CommandType.Text; cmd.CommandText = sqlCmd; var reader = cmd.ExecuteReader(); while (reader.Read()) { var childObject = new DatabaseObject { Type = childObjectType, ParentObject = dbObject }; var propertiesDictionary = new Dictionary<string, object>(); for (var fieldIndex = 0; fieldIndex < reader.FieldCount; fieldIndex++) { propertiesDictionary.Add(reader.GetName(fieldIndex).ToLowerInvariant(), reader.GetValue(fieldIndex)); } childObject.Properties.Add(primaryDataDictionaryTable.ToLowerInvariant(),propertiesDictionary); LoadObject(childObject); dbObject.ChildObjects.Add(childObject); } } } }
/// <summary> /// Alias for Parse(Method method) without requirement of caller to convert type. /// </summary> /// <param name="query"></param> /// <returns></returns> public ISerializer Parse(IDatabaseObject query) { this.Parse(query as Method); return this; }
/// <summary> /// Loop through escaping all StringValue database objects anywhere in the tree. /// </summary> /// <param name="query"></param> /// <returns></returns> public abstract IDatabaseObject EscapeStringValues(IDatabaseObject query);
protected override void AddObject(IDatabaseObject obj) { var spawn = obj as Spawn2; if (!Spawns.Contains(spawn)) { base.AddObject(spawn); Spawns.Add(spawn); } }
protected override void RemoveObject(IDatabaseObject obj) { var spawn = obj as Spawn2; if (Spawns.Contains(spawn)) { base.RemoveObject(spawn); Spawns.Remove(spawn); } }
public override string AddMotions(IDatabaseObject databaseObject) { if (databaseObject is AcceptanceOfGoods) { var item = databaseObject as AcceptanceOfGoods; AddMotion(Nomenclature, item.Nomenclature); AddMotion(Cell, item.NomenclatureCell); AddMotion(State, item.NomenclatureState); AddMotion(Party, item.NomenclatureParty); AddMotion(Code, item.NomenclatureCode); AddMotion(Quantity, item.NomenclatureFact); SetExceptionsValues("MarkForDeleting", 1); SetRequirementValue(item.NomenclatureState, RowsStates.Completed); return item.NomenclatureRowDate.ColumnName; } else if (databaseObject is Inventory) { var item = databaseObject as Inventory; AddMotion(Nomenclature, item.Nomenclature); AddMotion(Cell, item.FinalCell); AddMotion(State, item.RowState); AddMotion(Party, item.Party); AddMotion(Code, item.PalletCode); AddMotion(Quantity, item.FactValue); SetExceptionsValues("MarkForDeleting", 1); SetExceptionsValues(item.FactValue, 0); SetRequirementValue(item.RowState, RowsStates.Completed); StartNewMotionsCollection(); AddMotion(Nomenclature, item.Nomenclature); AddMotion(Cell, item.StartCell); AddMotion(State, item.RowState); AddMotion(Party, item.Party); AddMotion(Code, item.PalletCode); AddMotion(Quantity, item.PlanValue, true); SetExceptionsValues("MarkForDeleting", 1); SetExceptionsValues(item.PlanValue, 0); SetRequirementValue(item.RowState, RowsStates.Completed); return item.RowDate.ColumnName; } else if (databaseObject is Moving) { var item = databaseObject as Moving; AddMotion(Nomenclature, item.Nomenclature); AddMotion(Cell, item.FinalCell); AddMotion(State, item.RowState); AddMotion(Party, item.Party); AddMotion(Code, item.PalletCode); AddMotion(Quantity, item.FactValue); SetExceptionsValues("MarkForDeleting", 1); SetExceptionsValues(item.FinalCell, Consts.RedemptionCell.Id); SetExceptionsValues(item.FactValue, 0); SetRequirementValue(item.RowState, RowsStates.Completed); StartNewMotionsCollection(); AddMotion(Nomenclature, item.Nomenclature); AddMotion(Cell, item.StartCell); AddMotion(State, item.RowState); AddMotion(Party, item.Party); AddMotion(Code, item.PalletCode); AddMotion(Quantity, item.FactValue, true); SetExceptionsValues("MarkForDeleting", 1); SetExceptionsValues(item.PlanValue, 0); SetRequirementValue(item.RowState, RowsStates.Completed); return item.RowDate.ColumnName; } return null; }
private bool LockRecordExists(string strTableName, IDatabaseObject objObject, SQL.SQLCondition objAdditionalCondition = null) { SQL.SQLSelect objSelect = new SQL.SQLSelect(); objSelect.Fields.Add(string.Empty, SQL.AggregateFunction.Count); objSelect.Tables.Add(pstrLockTableName); objSelect.Where.Add("TableName", SQL.ComparisonOperator.EqualTo, strTableName); objSelect.Where.Add("RecordID", SQL.ComparisonOperator.EqualTo, objObject.DistinctValue.ToString()); if (objAdditionalCondition != null) objSelect.Where.Add(objAdditionalCondition); using (ConnectionScope connection = new ConnectionScope(pobjDatabase)) { using (IDataReader objReader = connection.Execute(objSelect)) { objReader.Read(); return System.Convert.ToInt32(objReader[0]) != 0; } } }
public DatabaseTransferEventArgs(IDatabaseObject databaseobject) { _databaseobject = databaseobject; }
/// <summary> /// Parses the list of indexes /// </summary> /// <param name="query"></param> /// <returns></returns> protected virtual List<String> ParseIndices(IDatabaseObject query) { return query.Where(statement => statement is Index).Union(new List<IDatabaseObject>() { query }.Where(owner => owner is Index)).Select(index => this.ParseIndex(index as Index)).Where(index => String.IsNullOrEmpty(index) == false).ToList(); }
public override IDatabaseObject EscapeStringValues(IDatabaseObject query) { // No escaping is required return query; }
/// <summary> /// Parses the list of databases. /// </summary> /// <param name="query"></param> /// <returns></returns> protected virtual List<String> ParseDatabases(IDatabaseObject query) { return query.Where(statement => statement is Builders.Database).Select(database => this.ParseDatabase(database as Builders.Database)).ToList(); }
private static string ApplyContentToCriteria(IDatabaseObject databaseObject, string criteria) { var regex = new Regex("{[^{]*\\.[^{]*}"); var processedCriteria = criteria; while (regex.IsMatch(processedCriteria)) { var currentMatch = regex.Match(processedCriteria); foreach (var capture in currentMatch.Captures) { var replacementString = capture.ToString(); replacementString = replacementString.Replace("{", string.Empty).Replace("}", string.Empty); var replacementStringParts = replacementString.Split(".".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); var tableName = replacementStringParts.Length > 0 ? replacementStringParts[0] : string.Empty; if (string.IsNullOrEmpty(tableName)) { continue; } var properties = databaseObject.Properties; while (null != properties) { if (properties.ContainsKey(tableName)) { break; } properties = databaseObject.ParentObject?.Properties; } if (null == properties) { continue; } var fieldName = replacementStringParts.Length > 1 ? replacementStringParts[1] : string.Empty; if (string.IsNullOrEmpty(fieldName)) { continue; } if (!properties[tableName].ContainsKey(fieldName)) { continue; } var fieldValue = properties[tableName][fieldName].ToString(); processedCriteria = processedCriteria.Replace(capture.ToString(), fieldValue); } } return processedCriteria; }
public void Add(IDatabaseObject obj) { _objects.Add(obj.Name, obj); }
/// <summary> /// Returns whether the object is locked. /// </summary> public bool IsLocked(IDatabaseObjects objCollection, IDatabaseObject objObject) { return this.LockRecordExists(objCollection.TableName(), objObject); }
/// -------------------------------------------------------------------------------- /// <summary> /// Indicates that the first the object in collection should be loaded. /// After this call the Object property will return this first object. /// Specifically, this function calls Database.ObjectByOrdinalFirst(). /// </summary> /// -------------------------------------------------------------------------------- public void ObjectSetToOrdinalFirst() { pobjObject = pobjDatabase.ObjectByOrdinalFirst(pobjCollection); pobjDistinctValue = pobjObject.DistinctValue; }
/// <summary> /// Returns whether the object is locked by the current user. Specifically, the user that was specified /// in the constructor. /// </summary> public bool IsLockedByCurrentUser(IDatabaseObjects objCollection, IDatabaseObject objObject) { return this.LockRecordExists(objCollection.TableName(), objObject, new SQL.SQLCondition("UserID", SQL.ComparisonOperator.EqualTo, pstrCurrentUserID)); }
/// -------------------------------------------------------------------------------- /// <summary> /// Locks an object. /// Throws an exception if the object is already locked. /// Throws an exception if the object is not been saved. /// Because it is possible that between calling IsLocked and calling Lock another /// user may have locked the object. Therefore, it is recommended calling Lock and then /// trapping the Exceptions.ObjectAlreadyExistsException to determine whether the object is already locked. /// </summary> /// <exception cref="Exceptions.DatabaseObjectsException">Thrown if the object has not been saved.</exception> /// <exception cref="Exceptions.ObjectAlreadyExistsException">Thrown if the object has already been locked.</exception> /// -------------------------------------------------------------------------------- public void Lock(IDatabaseObjects objCollection, IDatabaseObject objObject) { if (!objObject.IsSaved) throw new Exceptions.DatabaseObjectsException("Object is not saved and cannot be locked"); SQL.SQLInsert objInsert = new SQL.SQLInsert(); objInsert.TableName = pstrLockTableName; objInsert.Fields.Add("TableName", objCollection.TableName()); objInsert.Fields.Add("RecordID", objObject.DistinctValue.ToString()); objInsert.Fields.Add("UserID", pstrCurrentUserID); //If another user/connection has managed to add a record to the database just before //this connection has a DatabaseObjectsException will be thrown because duplicate keys will //be added to the table. using (ConnectionScope connection = new ConnectionScope(pobjDatabase)) { try { connection.ExecuteNonQuery(objInsert); } catch (Exceptions.DatabaseObjectsException) { throw new Exceptions.ObjectAlreadyLockedException(objCollection, objObject); } } }
/// <summary> /// Fetches the numeric value from a skip object /// </summary> /// <param name="query"></param> /// <returns></returns> protected virtual long? ParseSkip(IDatabaseObject query) { return query.Where(skip => skip is Skip && skip.Any(value => value is NumericValue)).Select(skip => ((NumericValue)skip.First(value => value is NumericValue)).Long).FirstOrDefault(); }
/// <summary> /// Query the open driver /// </summary> /// <param name="query"></param> public abstract List<IDatabaseObject> Query(IDatabaseObject query);
/// <summary> /// Fetches the numeric value from a limit object /// </summary> /// <param name="query"></param> /// <returns></returns> protected virtual long? ParseLimit(IDatabaseObject query) { return query.Where(limit => limit is Limit && limit.Any(value => value is NumericValue)).Select(limit => ((NumericValue)limit.First(value => value is NumericValue)).Long).FirstOrDefault(); }
/// <summary> /// Returns the user ID that has the object locked. /// Throws an exception if the object is not locked. /// </summary> public string LockedByUserID(IDatabaseObjects objCollection, IDatabaseObject objObject) { SQL.SQLSelect objSelect = new SQL.SQLSelect(); objSelect.Fields.Add("UserID"); objSelect.Tables.Add(pstrLockTableName); objSelect.Where.Add("TableName", SQL.ComparisonOperator.EqualTo, objCollection.TableName()); objSelect.Where.Add("RecordID", SQL.ComparisonOperator.EqualTo, objObject.DistinctValue.ToString()); using (ConnectionScope connection = new ConnectionScope(pobjDatabase)) { using (IDataReader objReader = connection.Execute(objSelect)) { if (objReader.Read()) return objReader[0].ToString(); else throw new Exceptions.DatabaseObjectsException("Object is not locked"); } } }
public override IDatabaseObject EscapeStringValues(IDatabaseObject query) { foreach (StringValue item in query.DescendantsAndSelf<StringValue>()) { item.Data = MySqlHelper.EscapeString(item.Data); } return query; }
public override List<IDatabaseObject> Query(IDatabaseObject query) { this.Connect(); return this.Query(new SerializerMySql().Parse(this.EscapeStringValues(query)).Compile()); }
/// -------------------------------------------------------------------------------- /// <summary> /// UnLocks this object. Throws an exception if the object is not locked by the current /// user or the object has not been saved. /// </summary> /// -------------------------------------------------------------------------------- public void UnLock(IDatabaseObjects objCollection, IDatabaseObject objObject) { //If the table is locked by someone else if (!this.IsLockedByCurrentUser(objCollection, objObject)) throw new MethodAccessException("Object already locked"); else if (!objObject.IsSaved) throw new MethodAccessException("Object is not saved and cannot be unlocked"); SQL.SQLDelete objDelete = new SQL.SQLDelete(); objDelete.TableName = pstrLockTableName; objDelete.Where.Add("TableName", SQL.ComparisonOperator.EqualTo, objCollection.TableName()); objDelete.Where.Add("RecordID", SQL.ComparisonOperator.EqualTo, objObject.DistinctValue.ToString()); objDelete.Where.Add("UserID", SQL.ComparisonOperator.EqualTo, pstrCurrentUserID); using (ConnectionScope connection = new ConnectionScope(pobjDatabase)) connection.ExecuteNonQuery(objDelete); }
public override string AddMotions(IDatabaseObject databaseObject) { if (databaseObject is AcceptanceOfGoods) { var item = databaseObject as AcceptanceOfGoods; AddMotion(Nomenclature, item.Nomenclature); AddMotion(Cell, item.NomenclatureCell); AddMotion(State, item.NomenclatureState); AddMotion(Party, item.NomenclatureParty); AddMotion(Code, item.NomenclatureCode); AddMotion(Quantity, item.NomenclatureFact); SetExceptionsValues("MarkForDeleting", 1); SetRequirementValue(item.NomenclatureState, RowsStates.Completed); return(item.NomenclatureRowDate.ColumnName); } else if (databaseObject is Inventory) { var item = databaseObject as Inventory; AddMotion(Nomenclature, item.Nomenclature); AddMotion(Cell, item.FinalCell); AddMotion(State, item.RowState); AddMotion(Party, item.Party); AddMotion(Code, item.PalletCode); AddMotion(Quantity, item.FactValue); SetExceptionsValues("MarkForDeleting", 1); SetExceptionsValues(item.FactValue, 0); SetRequirementValue(item.RowState, RowsStates.Completed); StartNewMotionsCollection(); AddMotion(Nomenclature, item.Nomenclature); AddMotion(Cell, item.StartCell); AddMotion(State, item.RowState); AddMotion(Party, item.Party); AddMotion(Code, item.PalletCode); AddMotion(Quantity, item.PlanValue, true); SetExceptionsValues("MarkForDeleting", 1); SetExceptionsValues(item.PlanValue, 0); SetRequirementValue(item.RowState, RowsStates.Completed); return(item.RowDate.ColumnName); } else if (databaseObject is Moving) { var item = databaseObject as Moving; AddMotion(Nomenclature, item.Nomenclature); AddMotion(Cell, item.FinalCell); AddMotion(State, item.RowState); AddMotion(Party, item.Party); AddMotion(Code, item.PalletCode); AddMotion(Quantity, item.FactValue); SetExceptionsValues("MarkForDeleting", 1); SetExceptionsValues(item.FinalCell, Consts.RedemptionCell.Id); SetExceptionsValues(item.FactValue, 0); SetRequirementValue(item.RowState, RowsStates.Completed); StartNewMotionsCollection(); AddMotion(Nomenclature, item.Nomenclature); AddMotion(Cell, item.StartCell); AddMotion(State, item.RowState); AddMotion(Party, item.Party); AddMotion(Code, item.PalletCode); AddMotion(Quantity, item.FactValue, true); SetExceptionsValues("MarkForDeleting", 1); SetExceptionsValues(item.PlanValue, 0); SetRequirementValue(item.RowState, RowsStates.Completed); return(item.RowDate.ColumnName); } return(null); }
public override string AddMotions(IDatabaseObject databaseObject) { if (databaseObject is AcceptanceOfGoods) { var item = databaseObject as AcceptanceOfGoods; AddMotion(Pallet, item.NomenclatureCode); AddMotion(PreviousPallet, item.PreviousPalletCode); AddMotion(Quantity, string.Empty); SetExceptionsValues("MarkForDeleting", 1); SetExceptionsValues("NomenclatureCell.AccessToAllWares", 1); SetRequirementValue(item.NomenclatureState, RowsStates.Completed); SetExceptionsValues(item.PreviousPalletCode, 0); SetExceptionsValues(item.IsTare, 1); return item.NomenclatureRowDate.ColumnName; } else if (databaseObject is Inventory) { var item = databaseObject as Inventory; AddMotion(Pallet, item.PalletCode); AddMotion(PreviousPallet, item.FinalCodeOfPreviousPallet); AddMotion(Quantity, string.Empty); SetRequirementValue(item.RowState, RowsStates.Completed); SetExceptionsValues(item.FinalCodeOfPreviousPallet, 0); SetExceptionsValues("FinalCell.AccessToAllWares", 1); SetExceptionsValues("MarkForDeleting", 1); StartNewMotionsCollection(); AddMotion(Pallet, item.PalletCode); AddMotion(PreviousPallet, item.StartCodeOfPreviousPallet); AddMotion(Quantity, string.Empty, true); SetRequirementValue(item.RowState, RowsStates.Completed); SetExceptionsValues(item.StartCodeOfPreviousPallet, 0); SetExceptionsValues("StartCell.AccessToAllWares", 1); SetExceptionsValues("MarkForDeleting", 1); return item.RowDate.ColumnName; } else if (databaseObject is Moving) { var item = databaseObject as Moving; AddMotion(Pallet, item.PalletCode); AddMotion(PreviousPallet, item.FinalCodeOfPreviousPallet); AddMotion(Quantity, string.Empty); SetExceptionsValues("MarkForDeleting", 1); SetExceptionsValues("FinalCell.AccessToAllWares", 1); SetRequirementValue(item.RowState, RowsStates.Completed); SetExceptionsValues(item.FinalCodeOfPreviousPallet, 0); StartNewMotionsCollection(); AddMotion(Pallet, item.PalletCode); AddMotion(PreviousPallet, item.StartCodeOfPreviousPallet); AddMotion(Quantity, string.Empty, true); SetExceptionsValues("MarkForDeleting", 1); SetExceptionsValues("StartCell.AccessToAllWares", 1); SetRequirementValue(item.RowState, RowsStates.Completed); SetExceptionsValues(item.StartCodeOfPreviousPallet, 0); return item.RowDate.ColumnName; } return null; }